From 2378751af43fc6a02b6bb063207dca261b83197d Mon Sep 17 00:00:00 2001 From: achingbrain Date: Wed, 21 Feb 2024 08:11:03 +0000 Subject: [PATCH] feat: add version method to CarWriter The `version()` method retrieves the version number from the underlying encoder. Fixes #161 --- src/api.ts | 1 + src/coding.ts | 2 ++ src/encoder.js | 11 ++++++++++- src/writer-browser.js | 9 +++++++++ test/test-writer.spec.js | 7 +++++++ 5 files changed, 29 insertions(+), 1 deletion(-) diff --git a/src/api.ts b/src/api.ts index ceb0e38..a314482 100644 --- a/src/api.ts +++ b/src/api.ts @@ -55,6 +55,7 @@ export interface BlockBufferReader { export interface BlockWriter { put(block: Block): Promise close(): Promise + version(): number } export interface CarBufferWriter { diff --git a/src/coding.ts b/src/coding.ts index 7b5ade3..cf7d6bc 100644 --- a/src/coding.ts +++ b/src/coding.ts @@ -7,6 +7,8 @@ export interface CarEncoder { writeBlock(block: Block): Promise close(): Promise + + version(): number } export interface IteratorChannel_Writer { diff --git a/src/encoder.js b/src/encoder.js index dca7548..d42c69c 100644 --- a/src/encoder.js +++ b/src/encoder.js @@ -8,6 +8,8 @@ import varint from 'varint' * @typedef {import('./coding').IteratorChannel_Writer} IteratorChannel_Writer */ +const CAR_V1_VERSION = 1 + /** * Create a header from an array of roots. * @@ -15,7 +17,7 @@ import varint from 'varint' * @returns {Uint8Array} */ export function createHeader (roots) { - const headerBytes = dagCborEncode({ version: 1, roots }) + const headerBytes = dagCborEncode({ version: CAR_V1_VERSION, roots }) const varintBytes = varint.encode(headerBytes.length) const header = new Uint8Array(varintBytes.length + headerBytes.length) header.set(varintBytes, 0) @@ -60,6 +62,13 @@ function createEncoder (writer) { */ async close () { await writer.end() + }, + + /** + * @returns {number} + */ + version () { + return CAR_V1_VERSION } } } diff --git a/src/writer-browser.js b/src/writer-browser.js index 82c8c25..4336441 100644 --- a/src/writer-browser.js +++ b/src/writer-browser.js @@ -104,6 +104,15 @@ export class CarWriter { return this._encoder.close() } + /** + * Returns the version number of the CAR file being written + * + * @returns {number} + */ + version () { + return this._encoder.version() + } + /** * Create a new CAR writer "channel" which consists of a * `{ writer:CarWriter, out:AsyncIterable }` pair. diff --git a/test/test-writer.spec.js b/test/test-writer.spec.js index 60d463f..4539fd8 100644 --- a/test/test-writer.spec.js +++ b/test/test-writer.spec.js @@ -224,6 +224,13 @@ describe('CarWriter', () => { assert.strictEqual(toHex(bytes).substring(0, expectedStart.length), expectedStart) }) + it('version', async () => { + const { writer } = CarWriter.create(roots) + + // v1 only + assert.equal(writer.version(), 1) + }) + it('no roots', async () => { const { writer, out } = CarWriter.create() const collection = collector(out)