Skip to content
This repository was archived by the owner on Sep 3, 2021. It is now read-only.

Commit c8be465

Browse files
committed
feat: allow array-like objects as input
Support not only Node.js Buffers, but also Uint8Arrays and normal Arrays as input for CIDs.
1 parent 537f604 commit c8be465

File tree

2 files changed

+34
-4
lines changed

2 files changed

+34
-4
lines changed

src/index.js

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -92,15 +92,16 @@ class CID {
9292
return
9393
}
9494

95-
if (Buffer.isBuffer(version)) {
96-
const firstByte = version.slice(0, 1)
97-
const v = parseInt(firstByte.toString('hex'), 16)
95+
// It is an array-like object, e.g. Arraym, Buffer or TypedArray
96+
if (version.length) {
97+
// The first byte is the actual version
98+
const v = version[0]
9899
if (v === 0 || v === 1) {
99100
// version is a CID buffer
100101
const cid = version
101102
this.version = v
102103
this.codec = multicodec.getCodec(cid.slice(1))
103-
this.multihash = multicodec.rmPrefix(cid.slice(1))
104+
this.multihash = Buffer.from(multicodec.rmPrefix(cid.slice(1)))
104105
this.multibaseName = (v === 0) ? 'base58btc' : multibaseName
105106
} else {
106107
// version is a raw multihash buffer, so v0

test/index.spec.js

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,35 @@ describe('CID', () => {
125125
expect(cid.toBaseEncodedString()).to.be.eql(cidStr)
126126
})
127127

128+
it('handled CID by Uint8Array', () => {
129+
const cidStr = 'zdj7Wd8AMwqnhJGQCbFxBVodGSBG84TM7Hs1rcJuQMwTyfEDS'
130+
const cidBuf = Buffer.from('017012207252523e6591fb8fe553d67ff55a86f84044b46a3e4176e10c58fa529a4aabd5', 'hex')
131+
const cidUint8 = Uint8Array.from(cidBuf)
132+
console.log('vmx: uint:', cidUint8)
133+
134+
const cid = new CID(cidUint8)
135+
136+
expect(cid).to.have.property('codec', 'dag-pb')
137+
expect(cid).to.have.property('version', 1)
138+
expect(cid).to.have.property('multihash')
139+
140+
expect(cid.toBaseEncodedString()).to.be.eql(cidStr)
141+
})
142+
143+
it('handled CID by Array', () => {
144+
const cidStr = 'zdj7Wd8AMwqnhJGQCbFxBVodGSBG84TM7Hs1rcJuQMwTyfEDS'
145+
const cidBuf = Buffer.from('017012207252523e6591fb8fe553d67ff55a86f84044b46a3e4176e10c58fa529a4aabd5', 'hex')
146+
const cidArray = Array.from(cidBuf)
147+
148+
const cid = new CID(cidArray)
149+
150+
expect(cid).to.have.property('codec', 'dag-pb')
151+
expect(cid).to.have.property('version', 1)
152+
expect(cid).to.have.property('multihash')
153+
154+
expect(cid.toBaseEncodedString()).to.be.eql(cidStr)
155+
})
156+
128157
it('create by parts', () => {
129158
const cid = new CID(1, 'dag-cbor', hash)
130159

0 commit comments

Comments
 (0)