Socket
Socket
Sign inDemoInstall

@hazae41/binary

Package Overview
Dependencies
8
Maintainers
1
Versions
63
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    @hazae41/binary

Zero-copy binary data types


Version published
Weekly downloads
4
increased by33.33%
Maintainers
1
Created
Weekly downloads
 

Readme

Source
npm i @hazae41/binary

Node Package 📦

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): Result<void, Error> {
    return Result.unthrowSync(() => {
      cursor.tryWriteUint8(this.x).throw()
      cursor.tryWriteUint16(this.y).throw()

      return Ok.void()
    })
  }

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

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

  static read(cursor: Cursor): Result<MyObject, Error> {
    return Result.unthrowSync(() => {
      const x = cursor.tryReadUint8().throw()
      const y = cursor.tryReadUint16().throw()

      return new Ok(new this(x, y))
    })
  }

}
const bytes = new Uint8Array([1, 2, 3])
const myobject = Readable.tryReadFromBytes(MyObject, bytes).unwrap() // 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.tryReadFromBytes(SafeOpaque, bytes).unwrap() // Opaque(Uint8Array([1, 2, 3]))
const myobject = opaque.tryInto(MyObject).unwrap() // MyObject(1, 515)
const myobject = new MyObject(1, 515)
const opaque = Opaque.tryWriteFrom(myobject).unwrap() // Opaque(Uint8Array([1, 2, 3]))
const bytes = Writable.tryWriteToBytes(opaque).unwrap() // Uint8Array([1, 2, 3])

Keywords

FAQs

Last updated on 14 Nov 2023

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc