npm.io
2.1.1 • Published 3 months ago

@hazae41/binary

Licence
MIT
Version
2.1.1
Deps
1
Size
12 kB
Vulns
0
Weekly
0
Stars
3

Binary

Zero-copy binary data types for the web

npm install @hazae41/binary

NPM

Features

Current features

  • 100% TypeScript and ESM
  • No external dependencies
  • Zero-copy reading and writing
  • Rust-like patterns
  • Unit-tested

Usage

Writable
class MyObject implements Writable {

  constructor(
    readonly x: number,
    readonly y: number
  ) {}

  size() {
    return 1 + 2
  }

  write(cursor: Cursor) {
    cursor.writeUint8(this.x)
    cursor.writeUint16(this.y)
  }

}
const myobject = new MyObject(1, 515)
const bytes = Writable.writeToBytes(myobject) // Uint8Array([1, 2, 3])
Readable
class MyObject {

  constructor(
    readonly x: number,
    readonly y: number
  ) {}

  static read(cursor: Cursor): MyObject {
    const x = cursor.readUint8()
    const y = cursor.readUint16()

    return new MyObject(x, y)
  }

}
const bytes = new Uint8Array([1, 2, 3])
const myobject = Readable.readFromBytes(MyObject, bytes) // MyObject(1, 515)
Opaque

This is a binary data type that just holds bytes, it can be used when a binary data type is required

const bytes = new Uint8Array([1, 2, 3])
const opaque = Readable.readFromBytes(Opaque.Uncopied, bytes) // Opaque(Uint8Array([1, 2, 3]))
const myobject = opaque.readInto(MyObject) // MyObject(1, 515)
const myobject = new MyObject(1, 515)
const opaque = Opaque.writeFrom(myobject) // Opaque.Copied(Uint8Array([1, 2, 3]))
const bytes = Writable.writeToBytes(opaque) // Uint8Array([1, 2, 3])

Keywords