|
| 1 | +var { digitCount, getType } = require('./util') |
| 2 | + |
| 3 | +function listLength (list) { |
| 4 | + var length = 1 + 1 // type marker + end-of-type marker |
| 5 | + |
| 6 | + for (let value of list) { |
| 7 | + length += encodingLength(value) |
| 8 | + } |
| 9 | + |
| 10 | + return length |
| 11 | +} |
| 12 | + |
| 13 | +function mapLength (map) { |
| 14 | + var length = 1 + 1 // type marker + end-of-type marker |
| 15 | + |
| 16 | + for (let [ key, value ] of map) { |
| 17 | + let keyLength = Buffer.byteLength(key) |
| 18 | + length += digitCount(keyLength) + 1 + keyLength |
| 19 | + length += encodingLength(value) |
| 20 | + } |
| 21 | + |
| 22 | + return length |
| 23 | +} |
| 24 | + |
| 25 | +function objectLength (value) { |
| 26 | + var length = 1 + 1 // type marker + end-of-type marker |
| 27 | + var keys = Object.keys(value) |
| 28 | + |
| 29 | + for (var i = 0; i < keys.length; i++) { |
| 30 | + let keyLength = Buffer.byteLength(keys[i]) |
| 31 | + length += digitCount(keyLength) + 1 + keyLength |
| 32 | + length += encodingLength(value[ keys[i] ]) |
| 33 | + } |
| 34 | + |
| 35 | + return length |
| 36 | +} |
| 37 | + |
| 38 | +function stringLength (value) { |
| 39 | + var length = Buffer.byteLength(value) |
| 40 | + return digitCount(length) + 1 + length |
| 41 | +} |
| 42 | + |
| 43 | +function arrayBufferLength (value) { |
| 44 | + var length = value.byteLength - value.byteOffset |
| 45 | + return digitCount(length) + 1 + length |
| 46 | +} |
| 47 | + |
| 48 | +function encodingLength (value) { |
| 49 | + var length = 0 |
| 50 | + |
| 51 | + if (value == null) return length |
| 52 | + |
| 53 | + var type = getType(value) |
| 54 | + |
| 55 | + switch (type) { |
| 56 | + case 'buffer': return digitCount(value.length) + 1 + value.length |
| 57 | + case 'arraybufferview': return arrayBufferLength(value) |
| 58 | + case 'string': return stringLength(value) |
| 59 | + case 'array': case 'set': return listLength(value) |
| 60 | + case 'number': return 1 + digitCount(Math.floor(value)) + 1 |
| 61 | + case 'bigint': return 1 + value.toString().length + 1 |
| 62 | + case 'object': return objectLength(value) |
| 63 | + case 'map': return mapLength(value) |
| 64 | + default: |
| 65 | + throw new TypeError(`Unsupported value of type "${type}"`) |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +module.exports = encodingLength |
0 commit comments