Skip to content

Instantly share code, notes, and snippets.

@gunzip
Created August 9, 2022 09:01
Show Gist options
  • Save gunzip/94547ff40a0aeae2cde03e79bc4452df to your computer and use it in GitHub Desktop.
Save gunzip/94547ff40a0aeae2cde03e79bc4452df to your computer and use it in GitHub Desktop.
refactor.ts
import { pipe } from "fp-ts/lib/function";
import * as E from "fp-ts/lib/Either";
import * as t from "io-ts";
import { WithinRangeInteger } from "./numbers";
export const NonEmptyUint8Array = new t.Type<Uint8Array, String, Array<number>>(
"NonEmptyUint8Array",
(u): u is Uint8Array =>
t.array(WithinRangeInteger(0, 256)).is(u) && u.length > 0,
(u, c) =>
t.array(WithinRangeInteger(0, 256)).is(u) && u.length > 0
? t.success(new Uint8Array(u))
: t.failure(u, c, "NonEmptyUint8Array"),
JSON.stringify
);
export type NonEmptyUint8Array = t.TypeOf<typeof NonEmptyUint8Array>;
export const NonEmptyBuffer = new t.Type<Buffer, String, Buffer>(
"NonEmptyBuffer",
(u): u is Buffer => Buffer.isBuffer(u) && u.length > 0,
(u, c) =>
Buffer.isBuffer(u) && u.length > 0
? t.success(u)
: t.failure(u, c, "NonEmptyBuffer"),
Buffer.toString
);
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,
String,
Array<number>
>(
"BinaryFromArray",
NonEmptyBuffer.is,
(u, c) =>
pipe(
NonEmptyUint8Array.validate(u, c),
E.map(_ => Buffer.from(_)),
E.chain(_ =>
_.length > 0
? t.success(_)
: t.failure(_, c, "Cannot parse to a BinaryFromArray")
)
),
Buffer.toString
);
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