From ed372e6f3935e54534f256f6eb9e31979d9f2f16 Mon Sep 17 00:00:00 2001 From: roblabla Date: Fri, 28 Aug 2015 15:21:59 +0000 Subject: [PATCH] Add option type --- src/datatypes/conditional.js | 28 ++++++++++++++++++++++++++++ test/test.js | 3 +++ 2 files changed, 31 insertions(+) diff --git a/src/datatypes/conditional.js b/src/datatypes/conditional.js index 679fdd2..683a510 100644 --- a/src/datatypes/conditional.js +++ b/src/datatypes/conditional.js @@ -2,6 +2,7 @@ var { getField, getFieldInfo } = require('../utils'); module.exports = { 'switch': [readSwitch, writeSwitch, sizeOfSwitch], + 'option': [readOption, writeOption, sizeOfOption], }; function readSwitch(buffer, offset, typeArgs, rootNode) { @@ -39,3 +40,30 @@ function sizeOfSwitch(value, typeArgs, rootNode) { fieldInfo = getFieldInfo(typeArgs.fields[compareTo]); return this.sizeOf(value, fieldInfo, rootNode); } + +function readOption(buffer, offset, typeArgs, context) { + var val = buffer.readUInt8(offset++); + if (val !== 0) { + var retVal = this.read(buffer, offset, typeArgs, context); + retval.size++; + return retval; + } else { + return { + size: 1 + }; + } +} + +function writeOption(value, buffer, offset, typeArgs, context) { + if (value != null) { + buffer.writeUInt8(1, offset++); + this.write(value, buffer, offset, typeArgs, context); + } else { + buffer.writeUInt8(0, offset++); + } + return offset; +} + +function sizeOfOption(value, typeArgs, context) { + return value == null ? 1 : this.sizeOf(value, typeArgs, context) + 1; +} diff --git a/test/test.js b/test/test.js index 5a955d4..a8b1794 100644 --- a/test/test.js +++ b/test/test.js @@ -120,6 +120,9 @@ var values = { else return getValue(i, packet); }, + 'option': function(typeArgs, packet) { + return getValue(typeArgs, packet); + } }; function getValue(_type, packet) {