Api
Boolean Methods
Methods for serializing and deserializing boolean values as single bytes.
Sia encodes boolean values as a single byte, where 1 represents true and 0 represents false. Available as both a class method and standalone functions:
// Class API
import { Sia } from "@timeleap/sia";
// Functional API (tree-shakeable)
import { Buffer, addBool, readBool } from "@timeleap/sia";
addBool(b) / readBool()
Writes or reads a boolean value.
addBool(b: boolean): Sia
readBool(): boolean
| Parameter | Type | Description |
|---|---|---|
b | boolean | The boolean value to serialize |
Returns (add): this (for chaining)
Returns (read): boolean — true if the byte is 1, false otherwise.
Encoding Detail
| Value | Encoded Byte |
|---|---|
true | 0x01 |
false | 0x00 |
On read, readBool() compares the byte strictly against 1. Any byte value other than 1 (including values like 2 or 255) will return false.
Booleans always occupy exactly 1 byte. If you need to pack multiple boolean
flags efficiently, consider using a bitmask stored as a
UInt8 or UInt16
instead.Example
import { Sia } from "@timeleap/sia";
interface FeatureFlags {
darkMode: boolean;
notifications: boolean;
betaAccess: boolean;
}
// Serialize
const sia = new Sia();
sia
.addBool(true) // darkMode
.addBool(false) // notifications
.addBool(true); // betaAccess
const bytes = sia.toUint8Array();
console.log(bytes); // Uint8Array [1, 0, 1]
// Deserialize
const reader = new Sia(bytes);
const flags: FeatureFlags = {
darkMode: reader.readBool(), // true
notifications: reader.readBool(), // false
betaAccess: reader.readBool(), // true
};
console.log(flags);
// { darkMode: true, notifications: false, betaAccess: true }
Bitmask Alternative
When serializing many boolean flags, packing them into a bitmask saves space:
import { Sia } from "@timeleap/sia";
// Pack 8 booleans into 1 byte instead of 8 bytes
const flags = {
darkMode: true,
notifications: false,
betaAccess: true,
analytics: false,
autoSave: true,
sounds: false,
tooltips: true,
animations: true,
};
const bitmask =
(Number(flags.darkMode) << 0) |
(Number(flags.notifications) << 1) |
(Number(flags.betaAccess) << 2) |
(Number(flags.analytics) << 3) |
(Number(flags.autoSave) << 4) |
(Number(flags.sounds) << 5) |
(Number(flags.tooltips) << 6) |
(Number(flags.animations) << 7);
const sia = new Sia();
sia.addUInt8(bitmask); // 1 byte for 8 flags
sia.seek(0);
const read = sia.readUInt8();
console.log(Boolean(read & (1 << 0))); // darkMode: true
console.log(Boolean(read & (1 << 2))); // betaAccess: true
console.log(Boolean(read & (1 << 5))); // sounds: false