Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/cid.js
Original file line number Diff line number Diff line change
Expand Up @@ -78,17 +78,21 @@ export class CID {
/** @readonly */
this.bytes = bytes

// ArrayBufferView
/** @readonly */
this.byteOffset = bytes.byteOffset
/** @readonly */
this.byteLength = bytes.byteLength

// Circular reference
/** @readonly */
this.asCID = this
}

// ArrayBufferView
get byteOffset () {
return this.bytes.byteOffset
}

// ArrayBufferView
get byteLength () {
return this.bytes.byteLength
}

/**
* @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
*/
Expand Down Expand Up @@ -274,6 +278,10 @@ export class CID {
throw new Error('String codecs are no longer supported')
}

if (!(digest.bytes instanceof Uint8Array)) {
throw new Error('Invalid digest')
}

switch (version) {
case 0: {
if (code !== DAG_PB_CODE) {
Expand Down
30 changes: 30 additions & 0 deletions test/test-cid.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -708,4 +708,34 @@ describe('CID', () => {
sender.close()
receiver.close()
})

describe('decode', () => {
const tests = {
v0: 'QmTFHZL5CkgNz19MdPnSuyLAi6AVq9fFp81zmPpaL2amED',
v1: 'bafybeif2pall7dybz7vecqka3zo24irdwabwdi4wc55jznaq75q7eaavvu'
}

Object.entries(tests).forEach(([version, cidString]) => {
it(`decode ${version} from bytes`, () => {
const cid1 = CID.parse(cidString)
const cid2 = CID.decode(cid1.bytes)

assert.deepStrictEqual(cid1, cid2)
})

it(`decode ${version} from subarray`, () => {
const cid1 = CID.parse(cidString)
// a byte array with an extra byte at the start and end
const bytes = new Uint8Array(cid1.bytes.length + 2)
bytes.set(cid1.bytes, 1)
// slice the cid bytes out of the middle to have a subarray with a non-zero .byteOffset
const subarray = bytes.subarray(1, cid1.bytes.length + 1)
const cid2 = CID.decode(subarray)

assert.deepStrictEqual(cid1, cid2)
assert.equal(cid1.byteLength, cid2.byteLength)
assert.equal(typeof cid2.byteOffset, 'number')
})
})
})
})