Encoding Spec With Examples
Summary of Data Types
Molecule categorizes data types into fixed and dynamic sizes:
| Fixed Size | Dynamic Size | |
|---|---|---|
| Types | byte array struct | vector table option union |
Memory Layout
| Type | Header | Body | |||||||
|---|---|---|---|---|---|---|---|---|---|
| array | item-0 | item-1 | ... | item-N | |||||
| struct | field-0 | field-1 | ... | field-N | |||||
| fixvec | items-count | item-0 | item-1 | ... | item-N | ||||
| dynvec | full-size | offset-0 | offset-1 | ... | offset-N | item-0 | item-1 | ... | item-N |
| table | full-size | offset-0 | offset-1 | ... | offset-N | filed-0 | field-1 | ... | field-N |
| option | item or none (zero bytes) | ||||||||
| union | item-type-id | item |
note
All items in Header are 32-bit unsigned integers in little-endian.
Primitive Data Type
byte
| Name | Description | Example |
|---|---|---|
byte | A single byte | 00 |
Composite Data Types
array
| Name | Description | Size | Serialization |
|---|---|---|---|
array | A fixed-size type with a fixed-size inner type and a fixed length. All items are stored consecutively. | The size of an array is the size of inner type times length. | Serializing an array is to serialize all fields in it. No overhead incurs since all items are stored consecutively without extra space. |
Examples
| Definition | Stored Value | Serialized Bytes |
|---|---|---|
array Byte3 [byte; 3]; | 01, 02, 03 | 01 02 03 |
array Uint32 [byte; 4]; | A 32-bit unsigned integer 0x01020304 in little-endian | 04 03 02 01 |
array TwoUint32 [Uint32; 2]; | Two 32-bit unsigned integers 0x01020304 and 0xabcde in little-endian | 04 03 02 01 de bc 0a 00 |
struct
| Name | Description | Size | Serialization |
|---|---|---|---|
struct | A fixed-size type with all fields being fixed-size and a fixed quantity of fields. | The size of a struct is the sum of all its fields. | Serializing a struct is to serialize all fields in it. No overhead incurs since all items are stored consecutively without extra space. |