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> {
try {
cursor.tryWriteUint8(this.x).throw()
cursor.tryWriteUint16(this.y).throw()
return Ok.void()
} catch(e: unknown) {
return Err.catch(e, Error)
}
}
}
const myobject = new MyObject(1, 515)
const bytes = Writable.tryToBytes(myobject).unwrap()
Readable
class MyObject {
constructor(
readonly x: number,
readonly y: number
) {}
static read(cursor: Cursor): Result<MyObject, Error> {
try {
const x = cursor.tryReadUint8().throw()
const y = cursor.tryReadUint16().throw()
return new Ok(new this(x, y))
} catch(e: unknown) {
return Err.catch(e, Error)
}
}
}
const bytes = new Uint8Array([1, 2, 3])
const myobject = Readable.tryFromBytes(MyObject, bytes).unwrap()
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.fromBytes(SafeOpaque, bytes).unwrap()
const myobject = opaque.tryInto(MyObject).unwrap()
const myobject = new MyObject(1, 515)
const opaque = Opaque.tryFrom(myobject).unwrap()
const bytes = Writable.toBytes(opaque).unwrap()