Skip to main content

Simple Types

Custom types work just like built-in ones. Use the customType() function to create them.

Danger

Encodexx does not enforce bounds on the data written by the type, so it is crucial to read exactly what was written.

Parameters

customType<T>(params: TUserCustomType<T>): TCustomType<T>
  • params - Object for configuring and creating a custom type.

Usage

./custom-types/int24.ts
import { customType } from "encodexx";
const MIN = -(2 ** 23);
const MAX = 2 ** 23 - 1;
export const int24 = customType<number>({
decode(buffer) {
const b0 = buffer.readUint8();
const b1 = buffer.readUint8();
const b2 = buffer.readUint8();
// Combine bytes into a 24-bit value:
let val24 = (b0 << 16) | (b1 << 8) | b2;
// We can set sign by shifting left and then right with sign:
val24 = (val24 << 8) >> 8;
return val24;
},
encode(val, buffer) {
// Convert negative numbers to their two's complement representation in 24 bits.
if (val < 0) {
val += 2 ** 24;
}
// Store the value in Big Endian order (most significant byte first).
buffer.writeUint8(Number((val >> 16) & 0xff));
buffer.writeUint8(Number((val >> 8) & 0xff));
buffer.writeUint8(Number(val & 0xff));
},
guard(data): data is number {
if (typeof data !== "number") return false;
return data <= MAX && data >= MIN;
},
name: "int24",
});
  • encode(val: T, buffer: Buffer) - Encodes the value. It receives the value to encode and a Buffer instance.
  • decode(buffer: Buffer): T - Decodes the value. It receives a Buffer and returns the decoded result.
  • guard(data): data is T - Used in the implementation of t.or() and in strict mode. This function determines if the value conforms to the type.

Tip

We recommend thoroughly validating type conformance to ensure optimal performance of internal mechanisms.

  • name - The type name as a string. It must be unique.

Serialization

A custom type can be used just like any other, unlocking new possibilities for serialization.

index.ts
import { t, Serializer } from "encodexx"
import { int24 } from "./custom-types/my-type.ts"
const serializer = new Serializer({
values: [t.or(t.str, int24)],
});
const encoded = serializer.encode({
values: [
122_254,
"hello"
],
});
console.log(serializer.decode(encoded))

Info

All built-in types are implemented using customType(). You can view their implementation on GitHub