|
1 | | -import { Buffer } from 'buffer' |
2 | 1 | import { bytes } from './@types/basic' |
3 | 2 | import { MessageBuffer } from './@types/handshake' |
4 | | -import BufferList from 'bl' |
| 3 | +import BufferList from 'bl/BufferList' |
| 4 | +import { concat as uint8ArrayConcat } from 'uint8arrays/concat' |
| 5 | +import allocUnsafe from './alloc-unsafe' |
5 | 6 |
|
6 | | -export const uint16BEEncode = (value: number, target: Buffer, offset: number): Buffer => { |
7 | | - target = target || Buffer.allocUnsafe(2) |
8 | | - target.writeUInt16BE(value, offset) |
| 7 | +export const uint16BEEncode = (value: number, target: Uint8Array, offset: number): Uint8Array => { |
| 8 | + target = target || allocUnsafe(2) |
| 9 | + new DataView(target.buffer, target.byteOffset, target.byteLength).setUint16(offset, value, false) |
9 | 10 | return target |
10 | 11 | } |
11 | 12 | uint16BEEncode.bytes = 2 |
12 | 13 |
|
13 | | -export const uint16BEDecode = (data: Buffer | BufferList): number => { |
| 14 | +export const uint16BEDecode = (data: Uint8Array | BufferList): number => { |
14 | 15 | if (data.length < 2) throw RangeError('Could not decode int16BE') |
15 | | - return data.readUInt16BE(0) |
| 16 | + |
| 17 | + if (data instanceof BufferList) { |
| 18 | + return data.readUInt16BE(0) |
| 19 | + } |
| 20 | + |
| 21 | + return new DataView(data.buffer, data.byteOffset, data.byteLength).getUint16(0, false) |
16 | 22 | } |
17 | 23 | uint16BEDecode.bytes = 2 |
18 | 24 |
|
19 | 25 | // Note: IK and XX encoder usage is opposite (XX uses in stages encode0 where IK uses encode1) |
20 | 26 |
|
21 | 27 | export function encode0 (message: MessageBuffer): bytes { |
22 | | - return Buffer.concat([message.ne, message.ciphertext]) |
| 28 | + return Buffer.from(uint8ArrayConcat([message.ne, message.ciphertext], message.ne.length + message.ciphertext.length)) |
23 | 29 | } |
24 | 30 |
|
25 | 31 | export function encode1 (message: MessageBuffer): bytes { |
26 | | - return Buffer.concat([message.ne, message.ns, message.ciphertext]) |
| 32 | + return Buffer.from(uint8ArrayConcat([message.ne, message.ns, message.ciphertext], message.ne.length + message.ns.length + message.ciphertext.length)) |
27 | 33 | } |
28 | 34 |
|
29 | 35 | export function encode2 (message: MessageBuffer): bytes { |
30 | | - return Buffer.concat([message.ns, message.ciphertext]) |
| 36 | + return Buffer.from(uint8ArrayConcat([message.ns, message.ciphertext], message.ns.length + message.ciphertext.length)) |
31 | 37 | } |
32 | 38 |
|
33 | 39 | export function decode0 (input: bytes): MessageBuffer { |
|
0 commit comments