|
| 1 | +function getSize(bytes: (number | Uint8Array)[]): number { |
| 2 | + let size = 0; |
| 3 | + for (let i = 0, len = bytes.length; i < len; i++) { |
| 4 | + const current = bytes[i]; |
| 5 | + if (typeof current === 'number') { |
| 6 | + size++; |
| 7 | + } else { |
| 8 | + size += current.length; |
| 9 | + } |
| 10 | + } |
| 11 | + return size; |
| 12 | +} |
| 13 | + |
| 14 | +export function mergeBytes(bytes: (number | Uint8Array)[]) { |
| 15 | + const newArr = new Uint8Array(getSize(bytes)); |
| 16 | + |
| 17 | + let index = 0; |
| 18 | + |
| 19 | + for (let i = 0, len = bytes.length; i < len; i++) { |
| 20 | + const current = bytes[i]; |
| 21 | + if (typeof current === 'number') { |
| 22 | + newArr[index++] = current; |
| 23 | + } else { |
| 24 | + const size = current.length; |
| 25 | + newArr.set(current, index); |
| 26 | + index += size; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + return newArr; |
| 31 | +} |
| 32 | + |
| 33 | +export function encodeInteger(value: number): Uint8Array { |
| 34 | + const arr = new Uint8Array(4); |
| 35 | + arr[0] = (value & 0xff000000) >> 24; |
| 36 | + arr[1] = (value & 0x00ff0000) >> 16; |
| 37 | + arr[2] = (value & 0x0000ff00) >> 8; |
| 38 | + arr[3] = value & 0x000000ff; |
| 39 | + return arr; |
| 40 | +} |
| 41 | + |
| 42 | +export function encodeNumber(value: number): Uint8Array { |
| 43 | + const buffer = new ArrayBuffer(8); |
| 44 | + const float = new Float64Array(buffer); |
| 45 | + float[0] = value; |
| 46 | + return new Uint8Array(buffer); |
| 47 | +} |
| 48 | + |
| 49 | +export function encodeString(value: string): Uint8Array { |
| 50 | + const encoder = new TextEncoder(); |
| 51 | + return encoder.encode(value); |
| 52 | +} |
0 commit comments