|
| 1 | +//-- vim: ft=javascript tabstop=2 softtabstop=2 expandtab shiftwidth=2 |
| 2 | +'use strict'; |
| 3 | +const { debug } = require('./utils'); |
| 4 | +console.log('debug is', debug); |
| 5 | + |
| 6 | +class BufferStruct extends Buffer { |
| 7 | + |
| 8 | + constructor(bufferStructType, value) { |
| 9 | + super(value); |
| 10 | + this._bufferStructType = bufferStructType; |
| 11 | + } |
| 12 | + |
| 13 | + toJSON() { |
| 14 | + return this._bufferStructType.toJSON(this) |
| 15 | + } |
| 16 | +} |
| 17 | + |
| 18 | +BufferStruct.forType = function forType(bufferStructType) { |
| 19 | + return new BufferStruct(bufferStructType, Buffer.alloc(bufferStructType.size)); |
| 20 | +} |
| 21 | + |
| 22 | + |
| 23 | +class BufferStructType { |
| 24 | + |
| 25 | + constructor(definitions) { |
| 26 | + this._fields = definitions; |
| 27 | + this._fields.forEach(function prepareDefinitions(def, defOrder) { |
| 28 | + if (defOrder == definitions.length - 1) def._isLast = true; |
| 29 | + |
| 30 | + switch (def.type) { |
| 31 | + case 'int': |
| 32 | + if (def.size === undefined) def.size = 4; |
| 33 | + def.type = `Int${def.size*8}`; |
| 34 | + if (def.size > 1) def.type += 'LE'; |
| 35 | + break; |
| 36 | + case 'uint': |
| 37 | + if (def.size === undefined) def.size = 4; |
| 38 | + def.type = `UInt${def.size*8}`; |
| 39 | + if (def.size > 1) def.type += 'LE'; |
| 40 | + break; |
| 41 | + case 'float': |
| 42 | + if (def.size == 8) { |
| 43 | + def.type = 'DoubleLE'; |
| 44 | + } else { |
| 45 | + def.type = 'FloatLE'; |
| 46 | + if (def.size === undefined) def.size = 4; |
| 47 | + } |
| 48 | + break; |
| 49 | + case 'double': |
| 50 | + if (def.size === undefined) def.size = 8; |
| 51 | + def.type = 'DoubleLE'; |
| 52 | + break; |
| 53 | + case 'buffer': |
| 54 | + if (def._isLast && def.size === 0) { |
| 55 | + // allow dynamic length |
| 56 | + def._dynamicSize = true; |
| 57 | + } |
| 58 | + break; |
| 59 | + case 'str': |
| 60 | + break; |
| 61 | + default: |
| 62 | + throw new Error(`Unkwnon type ${def.type} for field ${def.name}.`); |
| 63 | + break; |
| 64 | + } |
| 65 | + |
| 66 | + if ((!def.size || isNaN(def.size)) && !def._dynamicSize) { |
| 67 | + throw new Error(`Field ${def.name} has invalid size ${def.size}.`); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + |
| 73 | + pack(values) { |
| 74 | + const self = this; |
| 75 | + let offset = 0; |
| 76 | + let data = BufferStruct.forType(this); |
| 77 | + this._fields.forEach(function packField(def, n) { |
| 78 | + const val = values[n]; |
| 79 | + let realSize; |
| 80 | + if (def._dynamicSize) { // last item |
| 81 | + if (def.type != 'buffer') throw new Error("Dynamic size is supported on 'buffer' type."); |
| 82 | + if (! (val instanceof Buffer)) throw new Error(`Expected type Buffer for ${def.name} but got '${val}'.`); |
| 83 | + if (def.size) throw new Error(`Dynamic must not have a size specified.`); |
| 84 | + debug(`-- ${JSON.stringify(val)}`); |
| 85 | + const sizeBuffer = Buffer.alloc(4); |
| 86 | + sizeBuffer.writeUInt32LE(val.length); |
| 87 | + debug(`Pack dynamic ${def.name} of size ${sizeBuffer} ${offset}+${val.length}+${sizeBuffer.length}.`); |
| 88 | + data = Buffer.concat([ |
| 89 | + data.subarray(0, offset), // original message |
| 90 | + sizeBuffer, // size indicator (till the end of record) |
| 91 | + val, // the buffer |
| 92 | + ], offset + sizeBuffer.length + val.length); |
| 93 | + realSize = val.length + sizeBuffer.length; |
| 94 | + } else { |
| 95 | + const target = data.subarray(offset, offset + def.size); |
| 96 | + // debug(`pack ${offset}, ${def.size}`, val); |
| 97 | + realSize = self._packField(def, val, target); |
| 98 | + } |
| 99 | + offset += realSize; |
| 100 | + }); |
| 101 | + return data.subarray(0, offset); |
| 102 | + } |
| 103 | + |
| 104 | + _packField(def, val, target) { |
| 105 | + let realSize = def.size; |
| 106 | + if (def.type == 'str' || def.type == 'buffer') { |
| 107 | + if (typeof val == 'string' || val instanceof String) { |
| 108 | + realSize = val.length; |
| 109 | + target.writeUInt32LE(realSize); |
| 110 | + target.write(val, 4); |
| 111 | + } else if (val instanceof Buffer) { |
| 112 | + realSize = val.length; |
| 113 | + val.copy(target, 4); |
| 114 | + } else { |
| 115 | + realSize = val.length; |
| 116 | + target.write(val.toString(), 4); |
| 117 | + } |
| 118 | + target.writeUInt32LE(realSize); |
| 119 | + realSize += 4; |
| 120 | + } else { |
| 121 | + // TODO: guess type by size |
| 122 | + const packMeth = `write${def.type}`; |
| 123 | + if (target[packMeth]) { |
| 124 | + target[packMeth](val); |
| 125 | + } else { |
| 126 | + throw new Error(`Invalid type ${def.type} (Buffer has not method '${packMeth}'.`); |
| 127 | + } |
| 128 | + } |
| 129 | + return realSize; |
| 130 | + } |
| 131 | + |
| 132 | + unpack(data) { |
| 133 | + const self = this; |
| 134 | + let offset = 0; |
| 135 | + const values = []; |
| 136 | + if (!(data instanceof Buffer)) { |
| 137 | + throw new Error(`Data is expected to be Buffer found ${data} instead.`); |
| 138 | + } |
| 139 | + this._fields.forEach(function unpackField(def, n) { |
| 140 | + const val = data.subarray(offset, def.size ? (offset + def.size) : undefined); |
| 141 | + // debug(`unpack ${def.name} at ${offset}, size ${def.size}`, val); |
| 142 | + let [unpackedValue, realSize] = self._unpackField(def, val); |
| 143 | + values.push(unpackedValue); |
| 144 | + offset += realSize; |
| 145 | + }); |
| 146 | + return values; |
| 147 | + } |
| 148 | + |
| 149 | + _unpackField(def, val) { |
| 150 | + let realSize = def.size; |
| 151 | + let unpackedValue; |
| 152 | + if (def.type == 'str' || def.type == 'buffer') { |
| 153 | + realSize = val.readUInt32LE(); |
| 154 | + debug(`unpack ${def.name} of type ${def.type} size ${realSize}/${def.size}`); |
| 155 | + if (realSize) { |
| 156 | + if (def.type == 'str') { |
| 157 | + unpackedValue = val.toString('utf8', 4, 4 + realSize); |
| 158 | + } else { |
| 159 | + unpackedValue = val.subarray(4, 4 + realSize); |
| 160 | + } |
| 161 | + } else { // the string was a buffer |
| 162 | + unpackedValue = val.subarray(4); |
| 163 | + } |
| 164 | + realSize += 4; |
| 165 | + } else { |
| 166 | + debug(`unpack ${def.name} of type ${def.type} size -/${def.size}`); |
| 167 | + const packMeth = `read${def.type}`; |
| 168 | + if (val[packMeth]) { |
| 169 | + unpackedValue = val[packMeth](); |
| 170 | + } else { |
| 171 | + throw new Error(`Invalid type ${def.type} (Buffer has not method '${packMeth}'.`); |
| 172 | + } |
| 173 | + } |
| 174 | + return [unpackedValue, realSize]; |
| 175 | + } |
| 176 | + |
| 177 | + toJSON(data) { |
| 178 | + const values = this.unpack(data); |
| 179 | + const obj = {}; |
| 180 | + this._fields.forEach((def, n) => obj[def.name] = values[n]); |
| 181 | + return obj; |
| 182 | + } |
| 183 | + |
| 184 | + fromJSON(obj) { |
| 185 | + const values = []; |
| 186 | + this._fields.forEach((def, n) => values.push(obj[def.name])); |
| 187 | + return this.pack(values); |
| 188 | + } |
| 189 | + |
| 190 | + get size() { |
| 191 | + if (!this._size) { |
| 192 | + this._size = this._fields.reduce((a,b)=>{ |
| 193 | + return {size: a.size+b.size}; |
| 194 | + } |
| 195 | + ,{size:0}).size; |
| 196 | + } |
| 197 | + return this._size; |
| 198 | + } |
| 199 | +} |
| 200 | + |
| 201 | + |
| 202 | +if (require.main == module) { |
| 203 | + const print = console.log.bind(console); |
| 204 | + print("Running tests ..."); |
| 205 | + |
| 206 | + const struct = new BufferStructType([ |
| 207 | + {name: 'title', type: 'str', size: 20}, |
| 208 | + {name: 'offset', type: 'uint'}, |
| 209 | + {name: 'myFloat', type: 'float'}, |
| 210 | + {name: 'myDouble', type: 'float'}, |
| 211 | + {name: 'smallInt', type: 'int', size: 1}, |
| 212 | + {name: 'data', type: 'buffer', size: 20}, |
| 213 | + {name: 'payload', type: 'buffer', size: 0}, |
| 214 | + |
| 215 | + ]) |
| 216 | + |
| 217 | + const data = { |
| 218 | + title: 'pokus', |
| 219 | + data: Buffer.from([10, 13, 0, 45]), |
| 220 | + offset: 10, |
| 221 | + myFloat: 10.5, |
| 222 | + myDouble: 124132412, |
| 223 | + smallInt: 30, |
| 224 | + payload: Buffer.from('012345678901', 'ascii'), |
| 225 | + } |
| 226 | + |
| 227 | + print('>', data); |
| 228 | + |
| 229 | + const buf = struct.fromJSON(data); |
| 230 | + print('-----', buf.toString('hex'), '-----'); |
| 231 | + |
| 232 | + |
| 233 | + print('<', struct.toJSON(buf)); |
| 234 | +} |
| 235 | + |
| 236 | +module.exports = { |
| 237 | + BufferStructType: BufferStructType, |
| 238 | + BufferStruct: BufferStruct, |
| 239 | +} |
0 commit comments