From 46a9a6d83cc31ecd5229cba4cfa1b3995e09bcb4 Mon Sep 17 00:00:00 2001 From: Braydon Fuller Date: Fri, 12 Dec 2014 14:55:04 -0500 Subject: [PATCH] Opcode: Added toBuffer and fromBuffer methods --- lib/opcode.js | 14 ++++++++++++++ test/opcode.js | 7 +++++++ 2 files changed, 21 insertions(+) diff --git a/lib/opcode.js b/lib/opcode.js index 149d4e969..62a0c5192 100644 --- a/lib/opcode.js +++ b/lib/opcode.js @@ -2,6 +2,7 @@ var _ = require('lodash'); var $ = require('./util/preconditions'); +var BufferUtil = require('./util/buffer'); function Opcode(num) { if (!(this instanceof Opcode)) { @@ -26,6 +27,11 @@ function Opcode(num) { return this; } +Opcode.fromBuffer = function(buf) { + $.checkArgument(BufferUtil.isBuffer(buf)); + return new Opcode(Number('0x' + buf.toString('hex'))); +}; + Opcode.fromNumber = function(num) { $.checkArgument(_.isNumber(num)); return new Opcode(num); @@ -40,6 +46,14 @@ Opcode.fromString = function(str) { return new Opcode(value); }; +Opcode.prototype.toHex = function() { + return this.num.toString(16); +}; + +Opcode.prototype.toBuffer = function() { + return new Buffer(this.toHex(), 'hex'); +}; + Opcode.prototype.toNumber = function() { return this.num; }; diff --git a/test/opcode.js b/test/opcode.js index b2b8054c7..150ef86fe 100644 --- a/test/opcode.js +++ b/test/opcode.js @@ -52,6 +52,13 @@ describe('Opcode', function() { }); }); + describe('#buffer', function() { + it('should correctly input/output a buffer', function() { + var buf = new Buffer('a6', 'hex'); + Opcode.fromBuffer(buf).toBuffer().should.deep.equal(buf); + }); + }); + describe('#fromString', function() { it('should work for OP_0', function() { Opcode.fromString('OP_0').num.should.equal(0);