Skip to content

Commit 4e09490

Browse files
achingbrainGozala
andauthored
fix: convert byteOffset and byteLength to getters (#215)
* 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 <contact@gozala.io>
1 parent 0ec751a commit 4e09490

File tree

2 files changed

+44
-6
lines changed

2 files changed

+44
-6
lines changed

src/cid.js

+14-6
Original file line numberDiff line numberDiff line change
@@ -78,17 +78,21 @@ export class CID {
7878
/** @readonly */
7979
this.bytes = bytes
8080

81-
// ArrayBufferView
82-
/** @readonly */
83-
this.byteOffset = bytes.byteOffset
84-
/** @readonly */
85-
this.byteLength = bytes.byteLength
86-
8781
// Circular reference
8882
/** @readonly */
8983
this.asCID = this
9084
}
9185

86+
// ArrayBufferView
87+
get byteOffset () {
88+
return this.bytes.byteOffset
89+
}
90+
91+
// ArrayBufferView
92+
get byteLength () {
93+
return this.bytes.byteLength
94+
}
95+
9296
/**
9397
* @returns {CID<Data, API.DAG_PB, API.SHA_256, 0>}
9498
*/
@@ -274,6 +278,10 @@ export class CID {
274278
throw new Error('String codecs are no longer supported')
275279
}
276280

281+
if (!(digest.bytes instanceof Uint8Array)) {
282+
throw new Error('Invalid digest')
283+
}
284+
277285
switch (version) {
278286
case 0: {
279287
if (code !== DAG_PB_CODE) {

test/test-cid.spec.js

+30
Original file line numberDiff line numberDiff line change
@@ -708,4 +708,34 @@ describe('CID', () => {
708708
sender.close()
709709
receiver.close()
710710
})
711+
712+
describe('decode', () => {
713+
const tests = {
714+
v0: 'QmTFHZL5CkgNz19MdPnSuyLAi6AVq9fFp81zmPpaL2amED',
715+
v1: 'bafybeif2pall7dybz7vecqka3zo24irdwabwdi4wc55jznaq75q7eaavvu'
716+
}
717+
718+
Object.entries(tests).forEach(([version, cidString]) => {
719+
it(`decode ${version} from bytes`, () => {
720+
const cid1 = CID.parse(cidString)
721+
const cid2 = CID.decode(cid1.bytes)
722+
723+
assert.deepStrictEqual(cid1, cid2)
724+
})
725+
726+
it(`decode ${version} from subarray`, () => {
727+
const cid1 = CID.parse(cidString)
728+
// a byte array with an extra byte at the start and end
729+
const bytes = new Uint8Array(cid1.bytes.length + 2)
730+
bytes.set(cid1.bytes, 1)
731+
// slice the cid bytes out of the middle to have a subarray with a non-zero .byteOffset
732+
const subarray = bytes.subarray(1, cid1.bytes.length + 1)
733+
const cid2 = CID.decode(subarray)
734+
735+
assert.deepStrictEqual(cid1, cid2)
736+
assert.equal(cid1.byteLength, cid2.byteLength)
737+
assert.equal(typeof cid2.byteOffset, 'number')
738+
})
739+
})
740+
})
711741
})

0 commit comments

Comments
 (0)