From 76959ae6086f0e56f27a19d1dd41c0ca92139dbc Mon Sep 17 00:00:00 2001 From: Irakli Gozalishvili Date: Wed, 10 Jun 2020 19:21:26 -0700 Subject: [PATCH] feat: add Uint8Array support --- src/index.js | 6 ++++-- test/index.spec.js | 9 +++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index 0b87fb5..4cd8f2b 100644 --- a/src/index.js +++ b/src/index.js @@ -16,8 +16,10 @@ const withIs = require('class-is') */ class Block { constructor (data, cid) { - if (!data || !Buffer.isBuffer(data)) { - throw new Error('first argument must be a buffer') + if (!data || !ArrayBuffer.isView(data)) { + throw new Error('first argument must be a buffer or typed array') + } else if (!Buffer.isBuffer(data)) { + data = Buffer.from(data.buffer, data.byteOffset, data.byteLength) } if (!cid || !CID.isCID(cid)) { diff --git a/test/index.spec.js b/test/index.spec.js index 63de2bc..2fc6ae0 100644 --- a/test/index.spec.js +++ b/test/index.spec.js @@ -27,6 +27,15 @@ describe('block', () => { expect(Block.isBlock(b)).to.eql(true) }) + it('create with Uint8Array', () => { + const b = new Block( + new Uint8Array([104, 101, 108, 108, 111]), + new CID('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n') + ) + + expect(Block.isBlock(b)).to.eql(true) + }) + it('block stays immutable', () => { const b = new Block(Buffer.from('hello'), new CID('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'))