Skip to content

Commit

Permalink
fix: convert byteOffset and byteLength to getters (#215)
Browse files Browse the repository at this point in the history
* fix: convert byteOffset and byteLength to getters

Fixes #208 by converting `.byteOffset` and `.byteLength` properties
to getters.

Supersedes #210

* Apply suggestions from code review

* Update test/test-cid.spec.js

Co-authored-by: Irakli Gozalishvili <[email protected]>
  • Loading branch information
achingbrain and Gozala authored Oct 17, 2022
1 parent 0ec751a commit 4e09490
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
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')
})
})
})
})

0 comments on commit 4e09490

Please sign in to comment.