Skip to content

Instantly share code, notes, and snippets.

@gunzip
Last active August 9, 2022 16:59
Show Gist options
  • Save gunzip/bdfbbd5e3fbceeccacd96f5bbe064b15 to your computer and use it in GitHub Desktop.
Save gunzip/bdfbbd5e3fbceeccacd96f5bbe064b15 to your computer and use it in GitHub Desktop.
refactor using io-ts types
import { identity, pipe } from "fp-ts/lib/function";
import * as E from "fp-ts/lib/Either";
import * as t from "io-ts";
import { WithinRangeInteger } from "./numbers";
const _isNonEmptyUint8Array = (u: unknown): u is Uint8Array =>
Array.isArray(u) && u.length > 0 && t.array(WithinRangeInteger(0, 256)).is(u);
export const NonEmptyUint8Array = new t.Type<Uint8Array, Uint8Array, unknown>(
"NonEmptyUint8Array",
_isNonEmptyUint8Array,
(u, c) =>
_isNonEmptyUint8Array(u)
? t.success(u)
: t.failure(u, c, "NonEmptyUint8Array"),
identity
);
export type NonEmptyUint8Array = t.TypeOf<typeof NonEmptyUint8Array>;
const _isNonEmptyBuffer = (u: unknown): u is Buffer =>
Buffer.isBuffer(u) && u.length > 0;
export const NonEmptyBuffer = new t.Type<Buffer, Buffer, unknown>(
"NonEmptyBuffer",
_isNonEmptyBuffer,
(u, c) =>
_isNonEmptyBuffer(u) ? t.success(u) : t.failure(u, c, "NonEmptyBuffer"),
identity
);
export type NonEmptyBuffer = t.TypeOf<typeof NonEmptyBuffer>;
/**
* Decodes a non empty array of Uint8 into a non empty Buffer
*/
export const BinaryFromArray = new t.Type<NonEmptyBuffer, Buffer, unknown>(
"BinaryFromArray",
NonEmptyBuffer.is,
(u, c) =>
pipe(
NonEmptyUint8Array.validate(u, c),
E.map(_ => Buffer.from(_)),
E.chain(t.success)
),
identity
);
export type BinaryFromArray = t.TypeOf<typeof BinaryFromArray>;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment