Skip to content
Nahara-OSSPublic

About

Structured binary format construction and serialization kit

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Nahara's Codec

Structured binary format construction and serialization kit.

Example usage

import {
    BufferDuplexStream,
    type Codec,
    dynamicArrayCodec,
    primitive,
    structCodec,
    switchCodec,
    type SwitchingObject,
} from "@nahara/codec";

// Define types
type Employee = { name: string; pronouns: string };
type Instruction = SwitchingObject<InstructionMap, "type">;
type InstructionMap = {
    introduce: { employee: Employee; task: string };
    walk: { steps: number };
};

// Create codecs
const utf8 = primitive.dynamicUtf8(primitive.uvarLE);
const employeeCodec: Codec<Employee> = structCodec([
    { property: "name", codec: utf8 },
    { property: "pronouns", codec: utf8 },
]);
const insnCodec: Codec<Instruction> = switchCodec<InstructionMap, "type">(
    "type",
    utf8 as Codec<keyof InstructionMap>,
    {
        introduce: structCodec([
            { property: "employee", codec: employeeCodec },
            { property: "task", codec: utf8 },
        ]),
        walk: structCodec([
            { property: "steps", codec: primitive.u32LE },
        ]),
    },
);
const insnListCodec = dynamicArrayCodec<Instruction, Instruction[]>(
    primitive.uvarLE,
    insnCodec,
    Array // If you are using primitive.u8, Uint8Array is highly recommended
);

// Encoding instructions and then send it to server
const stream = new BufferDuplexStream(1024);
insnListCodec.encode([
    { type: "walk", steps: 10 },
    {
        type: "introduce",
        employee: { name: "Alice", pronouns: "She" },
        task: "cooking dinner"
    },
    { type: "walk", steps: 15 },
    {
        type: "introduce",
        employee: { name: "Bob", pronouns: "He" },
        task: "watching birds"
    },
], stream);

// Decode instructions on server
stream.flip();
insnListCodec.decode(stream).forEach(insn => {
    switch (insn.type) {
        case "introduce":
            return console.log(`This is ${insn.employee.name}. ${insn.employee.pronouns} is ${insn.task}.`);
        case "walk":
            return console.log(`Walk ${insn.steps} steps.`);
        default:
            return;
    }
});
$ deno example.ts
Walk 10 steps.
This is Alice. She is cooking dinner.
Walk 15 steps.
This is Bob. He is watching birds.

See test.ts for more example usages.

What can you do with this?

  • Serialize or deserialize your own custom binary format for storage.
  • Handle packet serialization for efficient client-server communication with switchCodec().

License

MIT License.

About

Structured binary format construction and serialization kit

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages