-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathenum.ts
More file actions
29 lines (22 loc) · 903 Bytes
/
enum.ts
File metadata and controls
29 lines (22 loc) · 903 Bytes
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
import { createCodec, CODEC_TYPES } from '../codec.ts'
import type { DecodeFunction, EncodeFunction, Codec } from '../codec.ts'
export function enumeration <T> (v: any): Codec<T> {
function findValue (val: string | number): number {
// Use the reverse mapping to look up the enum key for the stored value
// https://www.typescriptlang.org/docs/handbook/enums.html#reverse-mappings
if (v[val.toString()] == null) {
throw new Error('Invalid enum value')
}
return v[val]
}
const encode: EncodeFunction<number | string> = function enumEncode (val, writer) {
const enumValue = findValue(val)
writer.int32(enumValue)
}
const decode: DecodeFunction<number | string> = function enumDecode (reader) {
const val = reader.int32()
return findValue(val)
}
// @ts-expect-error yeah yeah
return createCodec('enum', CODEC_TYPES.VARINT, encode, decode)
}