Add basic buffer utilities (#6)

* Add basic buffer utilities

* Add buffer to main exports
This commit is contained in:
Jaco Greeff
2017-11-19 20:42:18 +01:00
committed by GitHub
parent c5d8dcf8b5
commit 3e43bd9ac2
8 changed files with 124 additions and 5 deletions
+19
View File
@@ -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');
};
+10
View File
@@ -0,0 +1,10 @@
// ISC, Copyright 2017 Jaco Greeff
// @flow
const bufferFromHex = require('./fromHex');
const bufferToHex = require('./toHex');
module.exports = {
bufferFromHex,
bufferToHex
};
+49
View File
@@ -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/);
});
});
});
+21
View File
@@ -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')
);
};