Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/hazae41/binary
Zero-copy binary data types 🏎️
https://github.com/hazae41/binary
binary buffer cursor decoding encoding esmodules javascript nodejs typescript unit-testing zero-copy
Last synced: 4 months ago
JSON representation
Zero-copy binary data types 🏎️
- Host: GitHub
- URL: https://github.com/hazae41/binary
- Owner: hazae41
- Created: 2022-12-15T14:05:49.000Z (about 2 years ago)
- Default Branch: master
- Last Pushed: 2024-08-31T16:52:38.000Z (5 months ago)
- Last Synced: 2024-10-07T22:37:22.868Z (4 months ago)
- Topics: binary, buffer, cursor, decoding, encoding, esmodules, javascript, nodejs, typescript, unit-testing, zero-copy
- Language: TypeScript
- Homepage:
- Size: 310 KB
- Stars: 3
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
Awesome Lists containing this project
README
```bash
npm i @hazae41/binary
```[**Node Package 📦**](https://www.npmjs.com/package/@hazae41/binary)
## Features
### Current features
- 100% TypeScript and ESM
- No external dependencies
- Zero-copy reading and writing
- Rust-like patterns
- Unit-tested## Usage
#### Writable
```typescript
class MyObject implements Writable {constructor(
readonly x: number,
readonly y: number
) {}size() {
return 1 + 2
}write(cursor: Cursor): Result {
return Result.unthrowSync(() => {
cursor.tryWriteUint8(this.x).throw()
cursor.tryWriteUint16(this.y).throw()return Ok.void()
})
}}
``````typescript
const myobject = new MyObject(1, 515)
const bytes = Writable.tryWriteToBytes(myobject).unwrap() // Uint8Array([1, 2, 3])
```#### Readable
```typescript
class MyObject {constructor(
readonly x: number,
readonly y: number
) {}static read(cursor: Cursor): Result {
return Result.unthrowSync(() => {
const x = cursor.tryReadUint8().throw()
const y = cursor.tryReadUint16().throw()return new Ok(new this(x, y))
})
}}
``````typescript
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
```typescript
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)
``````typescript
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])
```