-
Notifications
You must be signed in to change notification settings - Fork 33
/
Copy pathencoder.ts
75 lines (62 loc) · 2.12 KB
/
encoder.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import { Uint8ArrayList } from 'uint8arraylist'
import { alloc as uint8ArrayAlloc, allocUnsafe as uint8ArrayAllocUnsafe } from 'uint8arrays/alloc'
import type { bytes } from './@types/basic.js'
import type { MessageBuffer } from './@types/handshake.js'
import type { LengthDecoderFunction } from 'it-length-prefixed'
export const uint16BEEncode = (value: number): Uint8Array => {
const target = uint8ArrayAllocUnsafe(2)
target[0] = value >> 8
target[1] = value
return target
}
uint16BEEncode.bytes = 2
export const uint16BEDecode: LengthDecoderFunction = (data: Uint8Array | Uint8ArrayList): number => {
if (data.length < 2) throw RangeError('Could not decode int16BE')
if (data instanceof Uint8Array) {
let value = 0
value += data[0] << 8
value += data[1]
return value
}
return data.getUint16(0)
}
uint16BEDecode.bytes = 2
export function encode0 (message: MessageBuffer): Uint8ArrayList {
return new Uint8ArrayList(message.ne, message.ciphertext)
}
export function encode1 (message: MessageBuffer): Uint8ArrayList {
return new Uint8ArrayList(message.ne, message.ns, message.ciphertext)
}
export function encode2 (message: MessageBuffer): Uint8ArrayList {
return new Uint8ArrayList(message.ns, message.ciphertext)
}
export function decode0 (input: bytes): MessageBuffer {
if (input.length < 32) {
throw new Error('Cannot decode stage 0 MessageBuffer: length less than 32 bytes.')
}
return {
ne: input.subarray(0, 32),
ciphertext: input.subarray(32, input.length),
ns: uint8ArrayAlloc(0)
}
}
export function decode1 (input: bytes): MessageBuffer {
if (input.length < 80) {
throw new Error('Cannot decode stage 1 MessageBuffer: length less than 80 bytes.')
}
return {
ne: input.subarray(0, 32),
ns: input.subarray(32, 80),
ciphertext: input.subarray(80, input.length)
}
}
export function decode2 (input: bytes): MessageBuffer {
if (input.length < 48) {
throw new Error('Cannot decode stage 2 MessageBuffer: length less than 48 bytes.')
}
return {
ne: uint8ArrayAlloc(0),
ns: input.subarray(0, 48),
ciphertext: input.subarray(48, input.length)
}
}