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

Commit

Permalink
perf: cache buffer form of CID when created
Browse files Browse the repository at this point in the history
refs ipfs/js-ipfs#1788

License: MIT
Signed-off-by: Alan Shaw <[email protected]>
  • Loading branch information
Alan Shaw authored and vmx committed Mar 12, 2019
1 parent bdf1d30 commit c7fc646
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 6 deletions.
20 changes: 14 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -122,18 +122,26 @@ class CID {
* @memberOf CID
*/
get buffer () {
switch (this.version) {
case 0:
return this.multihash
case 1:
return Buffer.concat([
let buffer = this._buffer

if (!buffer) {
if (this.version === 0) {
buffer = this.multihash
} else if (this.version === 1) {
buffer = Buffer.concat([
Buffer.from('01', 'hex'),
multicodec.getCodeVarint(this.codec),
this.multihash
])
default:
} else {
throw new Error('unsupported version')
}

// Cache this buffer so it doesn't have to be recreated
Object.defineProperty(this, '_buffer', { value: buffer })
}

return buffer
}

/**
Expand Down
11 changes: 11 additions & 0 deletions test/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -300,4 +300,15 @@ describe('CID', () => {
})
})
})

describe('buffer reuse', () => {
it('should cache CID as buffer', done => {
multihashing(Buffer.from(`TEST${Date.now()}`), 'sha2-256', (err, hash) => {
if (err) return done(err)
const cid = new CID(1, 'dag-pb', hash)
expect(cid.buffer).to.equal(cid.buffer)
done()
})
})
})
})

0 comments on commit c7fc646

Please sign in to comment.