Files
serialize-js/README.md

69 lines
1.5 KiB
Markdown

# serialize-js
```js
import * as s from '@sek1ro/serialize'
const User = s.Struct({
id: s.Int(32, 'unsigned'),
name: String,
age: Number,
array: [Array, Boolean],
raw_data: DataView,
})
const user = {
id: 1,
name: 'john',
age: 20,
array: [true, false],
raw_data: s.filledDataView([0x00, 0x00, 0x00, 0xff]),
}
const dv = s.sizedDataView(sizeof(user, User))
s.serialize(dv, user, User)
const user_copy = s.parse(dv, User)
```
## Contents
- [Types](#types)
- [What is headless?](#headless)
## Types
### ES types
- Boolean
- Number
- String (headless)
- Array (headless)
- DataView (headless)
### Built-in types
- Int(bits: 8 | 16 | 32, sign: 'signed' | 'unsigned')
- ConstString(size: number)
- ConstArray(size: number)
- ConstDataView(byte_size: number)
- Struct(type_obj: Record<string, SerializableType | SerializableType[]>)
- Sequence(types: (SerializableType | SerializableType[])[])
## Headless
If type has variable size in bytes, if sizeof type different for specific object, it's called headless.
```js
const array = [true, false]
sizeof(ConstArray(2), Boolean) // 2
sizeof(array, ConstArray(2), Boolean) // 2
sizeof(Array, Boolean) // Error: unknown sizeof Array, Boolean
sizeof(array, Array, Boolean) // 2
```
Library has function `isHeadless(...types: SerializableType[])` to check this.
It's used in `Structure`, if type is headless, in head of structure it's stored as uint32 offset to beginning of type's body, if type isn't headless, it's stored directly in head of structure