npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dlenroc/binary-decoder

v0.1.1

Published

Incremental binary data parser powered by generators.

Downloads

147

Readme

@dlenroc/binary-decoder · NPM Version

A library for implementing incremental binary data parsers using generators.

Installation

npm install @dlenroc/binary-decoder

Usage

The BinaryDecoder class enables streaming binary decoding using a generator function. It leverages yield to read bytes, return unused data, and produce the decoded result.

import { BinaryDecoder } from '@dlenroc/binary-decoder';

const decoder = new BinaryDecoder(function* () {
  // ✨ N ≥ 0 | Read exactly N bytes.
  const fixedLengthBytes: Uint8Array = yield 2;

  // ✨ N < 0 | Read at most |N| bytes, at least 1 byte.
  const variableLengthBytes: Uint8Array = yield -2;

  // ✨ ArrayBufferView | Pushback bytes to the internal buffer.
  yield Uint8Array.of(40, 50);

  // ✨ Other | Enqueue parsed data.
  yield { fixedLengthBytes, variableLengthBytes, extraBytes: yield -Infinity };
});

console.log(decoder.decode(Uint8Array.of(10, 20, 30)));
// [
//   {
//     fixedLengthBytes: Uint8Array(2) [ 10, 20 ],
//     variableLengthBytes: Uint8Array(1) [ 30 ],
//     extraBytes: Uint8Array(2) [ 40, 50 ]
//   }
// ]

Examples

Stateful Parsing

Suppose we need to parse a simple protocol defined as follows:

| No. of bytes | Type [Value] | Description | | ------------ | ------------ | ----------- | | 4 | U32 | length | | length | U8 array | text |

import type { Decoder } from '@dlenroc/binary-decoder';
import { BinaryDecoder, getUint32 } from '@dlenroc/binary-decoder';

function* parse(): Decoder<string> {
  while (true) {
    const length = yield* getUint32();
    const bytes = yield length;

    yield new TextDecoder().decode(bytes);
  }
}

const decoder = new BinaryDecoder(parse);

// create a message
const textBytes = new TextEncoder().encode('Hello, World!');
const chunk = new Uint8Array([...new Uint8Array(4), ...textBytes]);
new DataView(chunk.buffer).setUint32(0, textBytes.byteLength);

// [1] Parse a message
console.log(decoder.decode(chunk));
// [ 'Hello, World!' ]

// [2] Parse multiple messages
console.log(decoder.decode(Uint8Array.of(...chunk, ...chunk)));
// [ 'Hello, World!', 'Hello, World!' ]

// [3] Parse a message split across chunks
console.log(decoder.decode(chunk.subarray(0, 3)));
// []
console.log(decoder.decode(chunk.subarray(3, 5)));
// []
console.log(decoder.decode(chunk.subarray(5)));
// [ 'Hello, World!' ]

Handling Large Messages

Update the decoder to stream decoded chunks directly, avoiding buffering.

import { getUint32, streamBytes } from '@dlenroc/binary-decoder';

function* parse(): Decoder<TextDecoderStream> {
  while (true) {
    const length = yield* getUint32();
    const stream = new TextDecoderStream();
    const writer = stream.writable.getWriter();

    try {
      yield stream;
      yield* streamBytes(length, (chunk) => writer.write(chunk));
    } finally {
      writer.close();
    }
  }
}

// ... 👀 See previous example

// [3] Parse a message split across chunks (streaming output)
console.log(decoder.decode(chunk.subarray(0, 3)));
// []
console.log(decoder.decode(chunk.subarray(3, 5)));
// [ TextDecoderStream { ... } ]
console.log(decoder.decode(chunk.subarray(5)));
// []