-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathenum.ts
More file actions
33 lines (24 loc) · 1.01 KB
/
enum.ts
File metadata and controls
33 lines (24 loc) · 1.01 KB
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
import { unsigned } from '../utils/varint.js'
import { DecodeFunction, EncodeFunction, createCodec, EncodingLengthFunction, Codec, CODEC_TYPES } from './codec.js'
export function enumeration <T> (e: T): Codec<T> {
const encodingLength: EncodingLengthFunction<string> = function enumEncodingLength (val: string) {
const keys = Object.keys(e)
const index = keys.indexOf(val)
return unsigned.encodingLength(index)
}
const encode: EncodeFunction<string> = function enumEncode (val, buf, offset) {
const keys = Object.keys(e)
const index = keys.indexOf(val)
return unsigned.encode(index, buf, offset)
}
const decode: DecodeFunction<string> = function enumDecode (buf, offset) {
const index = unsigned.decode(buf, offset)
const keys = Object.keys(e)
if (keys[index] == null) {
throw new Error('Could not find enum key for value')
}
return keys[index]
}
// @ts-expect-error yeah yeah
return createCodec('enum', CODEC_TYPES.VARINT, encode, decode, encodingLength)
}