-
Notifications
You must be signed in to change notification settings - Fork 1
/
hex.ts
42 lines (37 loc) · 1.32 KB
/
hex.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
import { pipe } from 'fp-ts/function';
import * as RE from 'fp-ts/ReaderEither';
import { ask, validate, VariableDecoder, withOpt } from './VariableDecoder';
type Options = {
/**
* Length of the buffer (in bytes)
*/
length?: number | undefined;
/**
* Maximum length of the buffer that will be accepted (in bytes, inclusive)
*/
maxLength?: number | undefined;
/**
* Minimum length of the buffer that will be accepted (in bytes, inclusive)
*/
minLength?: number | undefined;
};
const pat = /^[0-9A-Fa-f]+$/;
/**
* Decodes hexadecimal string to a `Buffer`
*/
const hex = (options: Options = {}): VariableDecoder<Buffer> =>
pipe(
ask(),
RE.chain(validate(pat.test.bind(pat), 'must be a valid hexadecimal string')),
RE.map((value) => Buffer.from(value, 'hex')),
withOpt(options.length)((len) =>
RE.chain(validate((buf) => buf.length === len, `must be ${len}-byte hexadecimal string`)),
),
withOpt(options.maxLength)((max) =>
RE.chain(validate((buf) => buf.length > max, `must be smaller than or equal to ${max} bytes`)),
),
withOpt(options.minLength)((min) =>
RE.chain(validate((buf) => buf.length < min, `must be greater than or equal to ${min} bytes`)),
),
);
export { hex };