Skip to content

timreichen/Coder

Repository files navigation

Coder

Data encoder and decoder that cares about data types.

Why do I need Coder?

Coder encodes javascript data into a buffer and decodes it back. Therefore data can be sent over the network without losing data types.

  • Supports a lot of types out of the box
  • is extendable

I can do that with JSON, right?

JSON is great, except it doesn't support a lot of types.

const date = new Date();

const string = JSON.stringify(date); // "2020-02-13T13:16:43.096Z"
JSON.parse(string); // "2020-02-13T13:16:43.096Z"

Coder supports a lot of different types by default so your data will have the same type after decoding.

Usage

import { decode, encode } from "https://deno.land/x/coder/mod.ts";

const date = new Date();
const buffer = encode(date); // ArrayBuffer
decode(buffer); // Date()

Supported types

Coder supports lots of types out of the box:

It needs to be discussed what additional types should be supported by default. Some possible candidates are:

Custom DataType Definition

Coder can easily be extended with custom DataTypes. There are 16 slots reserved for custom DataTypes: 0xf0-0xff.

import { Coder, DataType, Decoder, Encoder } from "https://deno.land/x/coder/mod.ts";

class SymbolDataType implements DataType {
  // returns true if data should be decoded for that type
  test(data: unknown) {
    return typeof data === "Symbol";
  },
  // transforms data into a buffer
  encode(encoder: Encoder, data: Symbol) {
    const description = data.description; // get data to encode
    const dataBuffer = encoder.encodeString(description); // encode description
    const lengthBuffer = encoder.encodeUint8(dataBuffer.byteLength); // encode description length
    return encoder.combineBuffers(lengthBuffer, dataBuffer); // return combined buffer
  },
  // transforms buffer back to a value
  decode(decoder: Decoder) {
    const length = decoder.decodeUint8(); // decode length
    const description = decoder.decodeString(length); // decode description
    return Symbol(description); // return Symbol with description
  },
};

const coder = new Coder()
coder.set(0xf0, new SymbolDataType());

const data = { mySymbol: Symbol("foo") };
const buffer = coder.encode(data);
coder.decoder(buffer); // { mySymbol: Symbol(foo) }

About

Data encoder and decoder that cares about data types.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published