-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
option.ts
34 lines (27 loc) · 1.02 KB
/
option.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
import type { Coder } from './abstract-coder';
import type { InputValueOf, DecodedValueOf } from './enum';
import { EnumCoder } from './enum';
type SwayOption<T> = { None: [] } | { Some: T };
export type Option<T> = T | undefined;
export class OptionCoder<TCoders extends Record<string, Coder>> extends EnumCoder<TCoders> {
encode(value: InputValueOf<TCoders>): Uint8Array {
const result = super.encode(this.toSwayOption(value) as unknown as InputValueOf<TCoders>);
return result;
}
toSwayOption(input: InputValueOf<TCoders>): SwayOption<unknown> {
if (input !== undefined) {
return { Some: input };
}
return { None: [] };
}
decode(data: Uint8Array, offset: number): [DecodedValueOf<TCoders>, number] {
const [decoded, newOffset] = super.decode(data, offset);
return [this.toOption(decoded) as DecodedValueOf<TCoders>, newOffset];
}
toOption(output?: DecodedValueOf<TCoders>): Option<unknown> {
if (output && 'Some' in output) {
return output.Some;
}
return undefined;
}
}