Add basic buffer utilities (#6)
* Add basic buffer utilities * Add buffer to main exports
This commit is contained in:
@@ -0,0 +1,19 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const isHex = require('../is/hex');
|
||||
const { stripHexPrefix } = require('../hex');
|
||||
|
||||
const EMPTY_BUFFER = Buffer.from([]);
|
||||
|
||||
module.exports = function fromHex (value?: string): Buffer {
|
||||
if (!value) {
|
||||
return EMPTY_BUFFER;
|
||||
}
|
||||
|
||||
if (!isHex(value)) {
|
||||
throw new Error(`Cannot convert non-hex value '${value}' to Buffer`);
|
||||
}
|
||||
|
||||
return Buffer.from(stripHexPrefix(value), 'hex');
|
||||
};
|
||||
@@ -0,0 +1,10 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const bufferFromHex = require('./fromHex');
|
||||
const bufferToHex = require('./toHex');
|
||||
|
||||
module.exports = {
|
||||
bufferFromHex,
|
||||
bufferToHex
|
||||
};
|
||||
@@ -0,0 +1,49 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
|
||||
/* eslint-disable no-unused-expressions */
|
||||
|
||||
const { bufferFromHex, bufferToHex } = require('./');
|
||||
|
||||
describe('buffer', () => {
|
||||
describe('bufferFromHex', () => {
|
||||
it('returns an empty buffer when null provided', () => {
|
||||
expect(
|
||||
bufferFromHex(null).length
|
||||
).to.equal(0);
|
||||
});
|
||||
|
||||
it('returns a buffer with the correct values', () => {
|
||||
expect(
|
||||
Buffer.from([128, 0, 10]).equals(
|
||||
bufferFromHex('0x80000a')
|
||||
)
|
||||
).to.be.true;
|
||||
});
|
||||
|
||||
it('throws error on non-hex inputs', () => {
|
||||
expect(
|
||||
() => bufferFromHex('notAHex')
|
||||
).to.throw(/Cannot convert non-hex value/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('bufferToHex', () => {
|
||||
it('returns 0x when the buffer is null', () => {
|
||||
expect(
|
||||
bufferToHex(null)
|
||||
).to.equal('0x');
|
||||
});
|
||||
|
||||
it('returns the hex value for the buffer', () => {
|
||||
expect(
|
||||
bufferToHex(Buffer.from([128, 0, 10]))
|
||||
).to.equal('0x80000a');
|
||||
});
|
||||
|
||||
it('throws when non-buffer value is supplied', () => {
|
||||
expect(
|
||||
() => bufferToHex('noABuffer')
|
||||
).to.throw(/Cannot convert non-buffer/);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
// ISC, Copyright 2017 Jaco Greeff
|
||||
// @flow
|
||||
|
||||
const isBuffer = require('../is/buffer');
|
||||
const { addHexPrefix } = require('../hex');
|
||||
|
||||
const ZERO_HEX = '0x';
|
||||
|
||||
module.exports = function toHex (value?: Buffer): string {
|
||||
if (!value) {
|
||||
return ZERO_HEX;
|
||||
}
|
||||
|
||||
if (!isBuffer(value)) {
|
||||
throw new Error(`Cannot convert non-buffer to hex`);
|
||||
}
|
||||
|
||||
return addHexPrefix(
|
||||
value.toString('hex')
|
||||
);
|
||||
};
|
||||
Reference in New Issue
Block a user