Merge pull request #730 from braydonf/feature/opcode-script-standard-interface

Opcode: Added toBuffer and fromBuffer methods
This commit is contained in:
Manuel Aráoz 2014-12-12 17:48:57 -03:00
commit 78d3dcecf2
2 changed files with 21 additions and 0 deletions

View File

@ -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;
};

View File

@ -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);