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

pdu-codec

v1.0.3

Published

PDU builder/parser

Downloads

16

Readme

PDU codec

A codec for easily converting between JavaScript objects and binary PDUs, with full TypeScript typings.

Installation

$ npm install pdu-codec

Usage

Building PDUs

Example of building a PDU from some bytes, strings, 16-bit words and hex data:

import {PduBuilder} from 'pdu-codec'; 

const pdu = new PduBuilder()
  .uint8(65, 66)
  .string('hello, ', {lengthBits: 16})
  .string('world')
  .uint16(0xCAFE)
  .string('abcde', {lengthBits: 0, nullTerminate: true})
  .hex('abcdef', {lengthBits: 32})
  .build()

Resulting PDU:

                          ┌ 8-bit length of 'world'
                          │
                          │  ┌ 'world'                     ┌ 32-bit length of hex 'abcdef'
                          │  │          ┌ 0xcafe           │
                          │  │          │                  │        ┌ hex 'abcdef'
4142 0007 68656c6c6f2c20 05 776f726c64 cafe 6162636465 00 00000003 abcdef
 │    │    │                                 │         │
 │    │    └ 'hello, '                       │         │
 │    │                                      │         └ null terminator of 'abcde'
 │    └ 16-bit length of 'hello, '           └ 'abcde'
 │
 └ uint8 [0x41, 0x42]

Bookmarks can be set to enable going back to fill in data:

import {PduBuilder} from 'pdu-codec'; 

const pdu = new PduBuilder()
  .uint8(65, 66)
  .string('hello, ')
  .saveMark('NAME_TO_BE_REPLACED')
  .string('world')
  .uint16(0xcafe)
  .string('whatever')
  .loadMark('NAME_TO_BE_REPLACED')
  .string('abcde')
  .end() // go back to tail of buffer
  .string('suffix')
  .build()

Parsing PDUs

import {PduParser} from 'pdu-codec'; 

const obj = PduParser.parse('1177cafebabe056162636465')
  .uint16(word => ({word}))
  .uint8(4, bytes => ({bytes}))
  .string(foo => ({foo}))
  .value; 

This PDU is parsed as:

               ┌ length of string 'abcde'
               │
               │  ┌ string 'abcde'
               │  │
1177 cafebabe 05 6162636465
 │    │
 │    └ uint8 [0xca, 0xfe, 0xba, 0xbe]
 │
 └ uint16 0x1177

Each value is parsed by passing the value to a function that returns an object which is merged with the current value of the parser, resulting in:

{
  word: 0x1177,
  bytes: [0xca, 0xfe, 0xba, 0xbe],
  foo: 'abcde'
}

For such simple mapping to property names, the property name can be passed instead of a function:

import {PduParser} from 'pdu-codec'; 

const obj = PduParser.parse('1177cafebabe056162636465')
  .uint16('word')
  .uint8(4, 'bytes')
  .string('foo')
  .value; 

For more advanced mapping, custom attributes may of course be produced:

import {PduParser} from 'pdu-codec'; 

const obj = PduParser.parse('666f6f2062617200002b')
  .string(s => {
     const [firstName, lastName] = s.split(' ');
     
     return {firstName, lastName};
   }, {lengthBits: 0, nullTerminate: true})
  .uint16('age')
  .value; 

Results in:

{
  firstName: 'foo',
  lastName: 'bar',
  age: 43
}

Note that the parser fully types the complete value as it is parsed. Parser functions may however also return void if some external attribute is assigned instead:

import {PduParser} from 'pdu-codec'; 

let c: number;

const obj = PduParser.parse('616263')
  .uint8('a')
  .uint8('b')
  .uint8(n => {
     c = n;
   }).value; 

In this case, obj will not include the found 63 which is assigned to the external variable c during parsing, i.e., value will now be typed only as {a: number; b: number}.

Full encode/decode example

Example of type safe encode/decode functions for an interface:

import PduBuilder from './PduBuilder';
import PduParser from './PduParser';

interface Data {
  foo: string;
  bar: number[];
  baz: Buffer;
}

function encodeData(data: Data): string {
  return new PduBuilder()
      .string(data.foo)
      .uint16(data.bar.length)
      .uint16(...data.bar)
      .hex(data.baz)
      .build();
}

function decodeData(pdu: string): Data {
  let barLength: number = 0;
  
  return PduParser.parse(pdu)
      .string('foo')
      .uint16((n, value) => {
        barLength = n;
      })
      .uint16(barLength, 'bar')
      .hex(hex => ({baz: Buffer.from(hex, 'hex')}))
      .value;
}