### Install Dependencies using pnpm Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Command to install all project dependencies using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Install SABCOM Package Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Installs the sabcom library using npm. This is the first step to using the library in your Node.js or TypeScript project. ```bash npm install sabcom ``` -------------------------------- ### Sabcom Minimum Buffer Size Calculation Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Explains the minimum buffer size requirement for Sabcom, considering the `HEADER_SIZE` and the need for payload space. It provides an example of creating a practically sized buffer. ```typescript import { HEADER_SIZE } from 'sabcom'; // Minimum: HEADER_SIZE + at least 1 byte for payload // Practical minimum: 1024 bytes (1KB) const buffer = new SharedArrayBuffer(1024); ``` -------------------------------- ### Main Thread Communication Example (TypeScript) Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Sets up a main thread to communicate with a worker using a SharedArrayBuffer. It sends a large message and receives a processed reply using sabcom's async API. ```typescript import { Worker } from 'worker_threads'; import { write, read } from 'sabcom'; import path from 'path'; async function main() { // 1. Create a SharedArrayBuffer (must be multiple of 4) // 4KB buffer const buffer = new SharedArrayBuffer(4096); // 2. Start the worker and pass the buffer via workerData const worker = new Worker(path.resolve(__dirname, 'worker.ts'), { workerData: buffer }); // 3. Prepare data const text = "Hello from the main thread! ".repeat(500); // Larger than buffer const data = new TextEncoder().encode(text); console.log(`Main: Sending ${data.byteLength} bytes...`); // 4. Write data to the shared buffer // The 'read' operation in the worker will pick this up. await write(data, buffer); const reply = await read(buffer); console.log('Main: Reply:', new TextDecoder().decode(reply)); } main().catch(console.error); ``` -------------------------------- ### Worker Thread Communication Example (TypeScript) Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Demonstrates a worker thread receiving data from the main thread via a SharedArrayBuffer, processing it, and sending a reply. Uses sabcom's sync API for reading and writing. ```typescript import { workerData } from 'worker_threads'; import { readSync, writeSync } from 'sabcom'; const buffer = workerData as SharedArrayBuffer; try { console.log('Worker: Waiting for data...'); const receivedData = readSync(buffer); const message = new TextDecoder().decode(receivedData); console.log('Worker: Received message:', message); const reply = new TextEncoder().encode(message.toUpperCase()); writeSync(reply, buffer); } catch (err) { console.error('Worker: Error', err); process.exit(1); } ``` -------------------------------- ### Advanced Sabcom Generator Usage Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Shows how to use Sabcom's `writeGenerator` for fine-grained control over data transfer. This example demonstrates iterating through the generator, performing custom logic, and waiting for reader signals using Atomics. ```typescript import { writeGenerator } from 'sabcom'; const gen = writeGenerator(data, buffer); let result = gen.next(); while (!result.done) { // Perform custom logic here (e.g. check for cancellation) // Wait for the reader signal const request = result.value; const waitResult = Atomics.wait(request.target, request.index, request.value, request.timeout); // Resume generator result = gen.next(waitResult); } ``` -------------------------------- ### Build Project using pnpm Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Command to build the project using the pnpm package manager. ```bash pnpm build ``` -------------------------------- ### Run Tests using pnpm Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Command to execute the project's test suite using the pnpm package manager. ```bash pnpm test ``` -------------------------------- ### Lint Project using pnpm Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Command to run the project's linter using the pnpm package manager to check for code style and quality issues. ```bash pnpm lint ``` -------------------------------- ### Handle Errors with Try-Catch in TypeScript Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Illustrates how to implement robust error handling for sabcom operations, specifically catching timeouts during write operations. It shows how to check the error message to identify the type of error and log appropriate messages. ```typescript try { await write(data, buffer, { timeout: 5000 }); } catch (err) { if (err.message.includes('timeout')) { console.error('Reader did not respond in time'); } } ``` -------------------------------- ### Main Thread Worker Communication with Sabcom Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Demonstrates how the main thread creates multiple workers, each with its own SharedArrayBuffer, and communicates with them in parallel using Sabcom's async read/write functions. It handles sending tasks and receiving responses. ```typescript import { Worker } from 'worker_threads'; import { write, read } from 'sabcom'; interface WorkerChannel { worker: Worker; buffer: SharedArrayBuffer; } async function createWorker(id: number): Promise { const buffer = new SharedArrayBuffer(4096); const worker = new Worker('./worker.js', { workerData: { id, buffer } }); return { worker, buffer }; } async function main() { // Create multiple workers, each with its own buffer const channels: WorkerChannel[] = await Promise.all([ createWorker(0), createWorker(1), createWorker(2), ]); // Send data to all workers in parallel const tasks = ['task-a', 'task-b', 'task-c']; await Promise.all( channels.map((ch, i) => write(new TextEncoder().encode(tasks[i]), ch.buffer) ) ); // Read responses from all workers in parallel const responses = await Promise.all( channels.map(ch => read(ch.buffer)) ); responses.forEach((data, i) => { console.log(`Worker ${i}: ${new TextDecoder().decode(data)}`); }); // Cleanup await Promise.all(channels.map(ch => ch.worker.terminate())); } main(); ``` -------------------------------- ### Configuring SABCOM Options Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Illustrates how to pass an options object to SABCOM functions, specifically setting a custom timeout for write operations. The default timeout is 5000 milliseconds. ```typescript await write(data, buffer, { timeout: 10000 // Timeout in milliseconds (default: 5000) }); ``` -------------------------------- ### Sabcom API Reference Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md This section details the core functions provided by the Sabcom library for inter-thread communication. ```APIDOC ## write(data: Uint8Array, buffer: SharedArrayBuffer, options?: Options): Promise ### Description Writes bytes to the buffer. Resolves when the reader has received all data. ### Method `POST` (conceptual, as it modifies buffer state) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Uint8Array) - Required - The bytes to write to the buffer. - **buffer** (SharedArrayBuffer) - Required - The SharedArrayBuffer to write to. - **options** (Options) - Optional - Additional configuration options. ### Request Example ```typescript import { write } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); const data = new TextEncoder().encode('Hello from writer!'); write(data, buffer).then(() => { console.log('Data written successfully.'); }); ``` ### Response #### Success Response (200) - **void** - The promise resolves when the data has been successfully written and acknowledged by the reader. #### Response Example N/A (Promise resolves with no value) ``` ```APIDOC ## read(buffer: SharedArrayBuffer, options?: Options): Promise ### Description Waits for and reads bytes from the buffer. Resolves with the complete data. ### Method `GET` (conceptual, as it retrieves data from buffer) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buffer** (SharedArrayBuffer) - Required - The SharedArrayBuffer to read from. - **options** (Options) - Optional - Additional configuration options. ### Request Example ```typescript import { read } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); // Assume data has been written to the buffer by another thread read(buffer).then((data) => { console.log(`Received data: ${new TextDecoder().decode(data)}`); }); ``` ### Response #### Success Response (200) - **Uint8Array** - The data read from the buffer. #### Response Example ```json { "example": "[104, 101, 108, 108, 111]" // Example byte array for 'hello' } ``` ``` ```APIDOC ## writeSync(data: Uint8Array, buffer: SharedArrayBuffer, options?: Options): void ### Description Synchronous version of `write`. Blocks until completion. ### Method `POST` (conceptual) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Uint8Array) - Required - The bytes to write to the buffer. - **buffer** (SharedArrayBuffer) - Required - The SharedArrayBuffer to write to. - **options** (Options) - Optional - Additional configuration options. ### Request Example ```typescript import { writeSync } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); const data = new TextEncoder().encode('Sync write!'); writeSync(data, buffer); console.log('Data written synchronously.'); ``` ### Response #### Success Response (200) N/A (Function does not return a value upon success) #### Response Example N/A ``` ```APIDOC ## readSync(buffer: SharedArrayBuffer, options?: Options): Uint8Array ### Description Synchronous version of `read`. Blocks until data is received. ### Method `GET` (conceptual) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buffer** (SharedArrayBuffer) - Required - The SharedArrayBuffer to read from. - **options** (Options) - Optional - Additional configuration options. ### Request Example ```typescript import { readSync } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); // Assume data has been written to the buffer by another thread const data = readSync(buffer); console.log(`Received data synchronously: ${new TextDecoder().decode(data)}`); ``` ### Response #### Success Response (200) - **Uint8Array** - The data read from the buffer. #### Response Example ```json { "example": "[87, 111, 114, 107, 101, 114, 32, 48, 32, 114, 101, 99, 101, 105, 118, 101, 100, 58, 32, 116, 97, 115, 107, 45, 97]" // Example byte array } ``` ``` -------------------------------- ### Timeout Configuration Source: https://context7.com/3axap4ehko/sabcom/llms.txt Configure timeout behavior for asynchronous and synchronous read/write operations. Custom timeouts can be set to override the default 5000ms. ```APIDOC ## Options - Timeout Configuration All functions accept an optional options object to configure timeout behavior. ### Async API with custom timeout ```typescript import { write, read } from 'sabcom'; // Async API with custom timeout (default is 5000ms) await write(data, buffer, { timeout: 10000 // 10 seconds }); const result = await read(buffer, { timeout: 30000 // 30 seconds for large transfers }); ``` ### Sync API with custom timeout ```typescript import { writeSync, readSync } from 'sabcom'; // Sync API with custom timeout writeSync(data, buffer, { timeout: 15000 }); const syncResult = readSync(buffer, { timeout: 15000 }); ``` ### Error handling for timeouts ```typescript try { await write(data, buffer, { timeout: 5000 }); } catch (err) { if (err.message.includes('timeout')) { console.error('Reader did not respond in time'); } } ``` ``` -------------------------------- ### Sabcom Buffer Pool Implementation Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md A TypeScript class demonstrating the buffer pool pattern for managing SharedArrayBuffers in a dynamic multi-worker environment. It allows acquiring and releasing buffers to reuse them efficiently. ```typescript class BufferPool { private available: SharedArrayBuffer[] = []; acquire(size = 4096): SharedArrayBuffer { return this.available.pop() ?? new SharedArrayBuffer(size); } release(buffer: SharedArrayBuffer): void { this.available.push(buffer); } } ``` -------------------------------- ### Multiple Workers with Separate Buffers (TypeScript) Source: https://context7.com/3axap4ehko/sabcom/llms.txt Demonstrates creating multiple workers, each with its own SharedArrayBuffer for independent communication with the main thread. It covers sending tasks to workers and receiving their responses using the sabcom library. ```typescript // main.ts import { Worker } from 'worker_threads'; import { write, read } from 'sabcom'; interface WorkerChannel { worker: Worker; buffer: SharedArrayBuffer; } async function createWorker(id: number): Promise { const buffer = new SharedArrayBuffer(4096); const worker = new Worker('./worker.js', { workerData: { id, buffer } }); return { worker, buffer }; } async function main() { // Create multiple workers, each with its own buffer const channels: WorkerChannel[] = await Promise.all([ createWorker(0), createWorker(1), createWorker(2), ]); // Send data to all workers in parallel const tasks = ['task-a', 'task-b', 'task-c']; await Promise.all( channels.map((ch, i) => write(new TextEncoder().encode(tasks[i]), ch.buffer) ) ); // Read responses from all workers in parallel const responses = await Promise.all( channels.map(ch => read(ch.buffer)) ); responses.forEach((data, i) => { console.log(`Worker ${i}: ${new TextDecoder().decode(data)}`); }); // Output: Worker 0: TASK-A-done // Worker 1: TASK-B-done // Worker 2: TASK-C-done // Cleanup await Promise.all(channels.map(ch => ch.worker.terminate())); } main(); // worker.ts import { workerData } from 'worker_threads'; import { readSync, writeSync } from 'sabcom'; const { id, buffer } = workerData as { id: number; buffer: SharedArrayBuffer }; // Receive task from main const task = new TextDecoder().decode(readSync(buffer)); console.log(`Worker ${id} received: ${task}`); // Process and respond const result = `${task.toUpperCase()}-done`; writeSync(new TextEncoder().encode(result), buffer); ``` -------------------------------- ### Generators for Fine-Grained Control Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Utilize generator functions for advanced control over data transfer, enabling features like progress bars, cancellation, and custom scheduling. ```APIDOC ## writeGenerator(data: Uint8Array, buffer: SharedArrayBuffer) ### Description Returns a generator object for fine-grained control over the writing process. ### Method `POST` (conceptual) ### Endpoint N/A (Function call) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (Uint8Array) - Required - The bytes to write. - **buffer** (SharedArrayBuffer) - Required - The SharedArrayBuffer to use. ### Request Example ```typescript import { writeGenerator } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); const data = new TextEncoder().encode('Progressive data'); const gen = writeGenerator(data, buffer); let result = gen.next(); while (!result.done) { // Custom logic, e.g., check for cancellation const request = result.value; // Wait for reader signal Atomics.wait(request.target, request.index, request.value, request.timeout); result = gen.next(waitResult); } console.log('Generator write complete.'); ``` ### Response #### Success Response (200) N/A (Generator yields control and resumes execution) #### Response Example N/A ``` -------------------------------- ### Configure Timeout for Sabcom Read/Write Operations Source: https://context7.com/3axap4ehko/sabcom/llms.txt Demonstrates how to set custom timeouts for asynchronous and synchronous read/write operations using the sabcom library. Supports error handling for timeout events. Default timeout is 5000ms. ```typescript import { write, read, writeSync, readSync } from 'sabcom'; // Async API with custom timeout (default is 5000ms) await write(data, buffer, { timeout: 10000 // 10 seconds }); const result = await read(buffer, { timeout: 30000 // 30 seconds for large transfers }); // Sync API with custom timeout writeSync(data, buffer, { timeout: 15000 }); const syncResult = readSync(buffer, { timeout: 15000 }); // Error handling for timeouts try { await write(data, buffer, { timeout: 5000 }); } catch (err) { if (err.message.includes('timeout')) { console.error('Reader did not respond in time'); } } ``` -------------------------------- ### Reuse Buffer After Transfer in TypeScript Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Demonstrates that a sabcom buffer can be reused for subsequent transfers after a previous transfer completes, whether successfully or with an error. The buffer automatically resets to the `READY` state. ```typescript const buffer = new SharedArrayBuffer(4096); // First transfer await write(data1, buffer); const result1 = await read(buffer); // Second transfer - same buffer await write(data2, buffer); const result2 = await read(buffer); ``` -------------------------------- ### Sabcom Buffer Header Size Constant Source: https://context7.com/3axap4ehko/sabcom/llms.txt Explains the HEADER_SIZE constant from the sabcom library, which defines the space reserved for the protocol header within a SharedArrayBuffer. It shows how to calculate the usable payload size and recommends a minimum buffer size. ```typescript import { HEADER_SIZE } from 'sabcom'; console.log('Header size:', HEADER_SIZE); // 16 bytes // Calculate usable payload size const buffer = new SharedArrayBuffer(4096); const usableSize = buffer.byteLength - HEADER_SIZE; console.log('Usable payload:', usableSize); // 4080 bytes // Minimum practical buffer size const minBuffer = new SharedArrayBuffer(1024); // 1KB minimum recommended ``` -------------------------------- ### Buffer Pool Pattern for Dynamic Workers (TypeScript) Source: https://context7.com/3axap4ehko/sabcom/llms.txt Implements a BufferPool class to manage a collection of reusable SharedArrayBuffers, optimizing memory usage when dealing with a dynamic number of workers. This pattern helps in acquiring and releasing buffers efficiently. ```typescript class BufferPool { private available: SharedArrayBuffer[] = []; acquire(size = 4096): SharedArrayBuffer { return this.available.pop() ?? new SharedArrayBuffer(size); } release(buffer: SharedArrayBuffer): void { this.available.push(buffer); } } // Usage const pool = new BufferPool(); async function processTask(taskData: string) { const buffer = pool.acquire(4096); const worker = new Worker('./worker.js', { workerData: buffer }); try { await write(new TextEncoder().encode(taskData), buffer); const result = await read(buffer); return new TextDecoder().decode(result); } finally { await worker.terminate(); pool.release(buffer); // Return buffer to pool for reuse } } ``` -------------------------------- ### Sending JSON Objects with sabcom (TypeScript) Source: https://context7.com/3axap4ehko/sabcom/llms.txt Illustrates how to send JSON objects between threads using sabcom by serializing the object to a JSON string, encoding it to bytes, and then decoding and parsing the received bytes back into an object. This is necessary as sabcom transfers raw bytes. ```typescript import { write, read } from 'sabcom'; // Writer - serialize object to bytes const obj = { hello: 'world', count: 42, nested: { data: [1, 2, 3] } }; const json = JSON.stringify(obj); const data = new TextEncoder().encode(json); await write(data, buffer); // Reader - deserialize bytes back to object const receivedData = await read(buffer); const receivedJson = new TextDecoder().decode(receivedData); const receivedObj = JSON.parse(receivedJson); console.log(receivedObj); // Output: { hello: 'world', count: 42, nested: { data: [1, 2, 3] } } ``` -------------------------------- ### Sync API for SABCOM Communication Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Offers synchronous functions for writing and reading data to/from a SharedArrayBuffer. Suitable for CPU-bound workers where blocking is acceptable. ```typescript import { writeSync, readSync } from 'sabcom'; // Writer writeSync(data, buffer); // Reader const result = readSync(buffer); ``` -------------------------------- ### Low-level Write with writeGenerator in Sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Utilizes the writeGenerator from sabcom for low-level data writing, enabling custom flow control for progress tracking, cancellation, or scheduling. It involves manual iteration and waiting for reader acknowledgments. ```typescript import { writeGenerator } from 'sabcom'; const data = new TextEncoder().encode('Large payload data...'); const buffer = new SharedArrayBuffer(4096); const gen = writeGenerator(data, buffer, { timeout: 10000 }); let chunks = 0; // Manual iteration with progress tracking for (const request of gen) { // Check for cancellation before each chunk if (shouldCancel) { console.log('Transfer cancelled'); break; // finally block resets buffer to READY state } // Wait for reader acknowledgment const result = Atomics.wait( request.target, request.index, request.value, request.timeout ); if (result === 'timed-out') { throw new Error('Transfer timeout'); } console.log(`Chunk ${++chunks} sent`); } console.log(`Transfer complete: ${chunks} chunks`); // Output: Chunk 1 sent // Chunk 2 sent // Transfer complete: 2 chunks ``` -------------------------------- ### Async API for SABCOM Communication Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Provides asynchronous functions for writing and reading data to/from a SharedArrayBuffer. Ideal for non-blocking operations in event-driven environments. ```typescript import { write, read } from 'sabcom'; // Writer await write(data, buffer); // Reader const result = await read(buffer); ``` -------------------------------- ### writeGenerator - Low-level Write Generator Source: https://context7.com/3axap4ehko/sabcom/llms.txt A low-level generator for writing data, offering custom flow control. It's suitable for implementing progress tracking, cancellation, or custom scheduling of data transfers. ```APIDOC ## Advanced API ### writeGenerator - Low-level Write Generator Low-level generator for writing data with custom flow control. Use for progress tracking, cancellation, or custom scheduling. ```typescript import { writeGenerator } from 'sabcom'; const data = new TextEncoder().encode('Large payload data...'); const buffer = new SharedArrayBuffer(4096); const gen = writeGenerator(data, buffer, { timeout: 10000 }); let chunks = 0; // Manual iteration with progress tracking for (const request of gen) { // Check for cancellation before each chunk if (shouldCancel) { console.log('Transfer cancelled'); break; // finally block resets buffer to READY state } // Wait for reader acknowledgment const result = Atomics.wait( request.target, request.index, request.value, request.timeout ); if (result === 'timed-out') { throw new Error('Transfer timeout'); } console.log(`Chunk ${++chunks} sent`); } console.log(`Transfer complete: ${chunks} chunks`); // Output: Chunk 1 sent // Chunk 2 sent // Transfer complete: 2 chunks ``` ``` -------------------------------- ### Low-level Read with readGenerator in Sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Employs the readGenerator from sabcom for low-level data reading, providing custom flow control for progress tracking, cancellation, or scheduling. This involves iterating through chunks and using Atomics.wait for synchronization. ```typescript import { readGenerator } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); const gen = readGenerator(buffer, { timeout: 10000 }); let result = gen.next(); let chunks = 0; while (!result.done) { // Custom logic before each wait console.log(`Waiting for chunk ${chunks}...`); const waitResult = Atomics.wait( result.value.target, result.value.index, result.value.value, result.value.timeout ); if (waitResult === 'timed-out') { throw new Error(`Timeout waiting for chunk ${chunks}`); } chunks++; result = gen.next(waitResult); } const data = result.value; // Uint8Array console.log(`Received ${data.byteLength} bytes in ${chunks} chunks`); // Output: Waiting for chunk 0... // Waiting for chunk 1... // Received 8192 bytes in 2 chunks ``` -------------------------------- ### Cancel Transfer Mid-way using Generators in TypeScript Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Explains how to cancel a sabcom transfer in progress by using generators with a `for...of` loop. Breaking out of the loop automatically triggers cleanup, resetting the buffer to the `READY` state. ```typescript const gen = writeGenerator(data, buffer); for (const request of gen) { if (shouldCancel) break; // finally block resets buffer to READY const result = Atomics.wait(request.target, request.index, request.value, request.timeout); if (result === 'timed-out') break; } ``` -------------------------------- ### readGenerator - Low-level Read Generator Source: https://context7.com/3axap4ehko/sabcom/llms.txt A low-level generator for reading data, providing custom flow control. This API is useful for implementing progress tracking, cancellation, or custom scheduling during data reception. ```APIDOC ### readGenerator - Low-level Read Generator Low-level generator for reading data with custom flow control. Use for progress tracking, cancellation, or custom scheduling. ```typescript import { readGenerator } from 'sabcom'; const buffer = new SharedArrayBuffer(4096); const gen = readGenerator(buffer, { timeout: 10000 }); let result = gen.next(); let chunks = 0; while (!result.done) { // Custom logic before each wait console.log(`Waiting for chunk ${chunks}...`); const waitResult = Atomics.wait( result.value.target, result.value.index, result.value.value, result.value.timeout ); if (waitResult === 'timed-out') { throw new Error(`Timeout waiting for chunk ${chunks}`); } chunks++; result = gen.next(waitResult); } const data = result.value; // Uint8Array console.log(`Received ${data.byteLength} bytes in ${chunks} chunks`); // Output: Waiting for chunk 0... // Waiting for chunk 1... // Received 8192 bytes in 2 chunks ``` ``` -------------------------------- ### Async Read Data using sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Asynchronously reads byte data from a SharedArrayBuffer written by another thread. This non-blocking API is suitable for the main thread and resolves when all data has been received. It waits for the writer to complete its operation. ```typescript import { Worker } from 'worker_threads'; import { write, read } from 'sabcom'; async function receiveFromWorker() { const buffer = new SharedArrayBuffer(4096); const worker = new Worker('./worker.js', { workerData: buffer }); // Worker will write data to the shared buffer // read() waits for and receives that data const data = await read(buffer); const message = new TextDecoder().decode(data); console.log('Received:', message); // Output: Received: Hello from worker! await worker.terminate(); } receiveFromWorker(); ``` -------------------------------- ### Async Write Data using sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Asynchronously writes byte data to a SharedArrayBuffer for cross-thread transfer. This non-blocking API is suitable for the main thread and resolves once the reader has received all data. It handles data chunking if the data exceeds the buffer size. ```typescript import { Worker } from 'worker_threads'; import { write, read } from 'sabcom'; import path from 'path'; async function main() { // Create a SharedArrayBuffer (must be multiple of 4, minimum 1024 bytes) const buffer = new SharedArrayBuffer(4096); // Start worker and pass buffer via workerData const worker = new Worker(path.resolve(__dirname, 'worker.js'), { workerData: buffer }); // Prepare and send data (can be larger than buffer - auto-chunked) const text = "Hello from the main thread! ".repeat(500); const data = new TextEncoder().encode(text); console.log(`Main: Sending ${data.byteLength} bytes...`); await write(data, buffer); // Wait for response from worker const reply = await read(buffer); console.log('Main: Reply:', new TextDecoder().decode(reply)); // Output: Main: Reply: HELLO FROM THE MAIN THREAD! HELLO FROM... await worker.terminate(); } main().catch(console.error); ``` -------------------------------- ### HEADER_SIZE - Buffer Header Constant Source: https://context7.com/3axap4ehko/sabcom/llms.txt The HEADER_SIZE constant defines the size in bytes reserved for the protocol header within a SharedArrayBuffer. The usable payload size is calculated as `buffer.byteLength - HEADER_SIZE`. ```APIDOC ## HEADER_SIZE - Buffer Header Constant Size in bytes reserved for protocol header in the SharedArrayBuffer. The usable payload size is `buffer.byteLength - HEADER_SIZE`. ```typescript import { HEADER_SIZE } from 'sabcom'; console.log('Header size:', HEADER_SIZE); // 16 bytes // Calculate usable payload size const buffer = new SharedArrayBuffer(4096); const usableSize = buffer.byteLength - HEADER_SIZE; console.log('Usable payload:', usableSize); // 4080 bytes // Minimum practical buffer size const minBuffer = new SharedArrayBuffer(1024); // 1KB minimum recommended ``` ``` -------------------------------- ### Synchronous Read Data using sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Synchronously reads byte data from a SharedArrayBuffer, blocking until all data has been received. This API is ideal for worker threads where blocking is permissible. It ensures the complete data packet is available before execution continues. ```typescript // worker.ts import { workerData } from 'worker_threads'; import { readSync, writeSync } from 'sabcom'; const buffer = workerData as SharedArrayBuffer; // Blocking read - waits for writer to send data const data = readSync(buffer); const message = new TextDecoder().decode(data); console.log('Worker received:', message); // Output: Worker received: Task data from main thread // Process and respond const result = new TextEncoder().encode(`Processed: ${message}`); writeSync(result, buffer); ``` -------------------------------- ### Worker Thread Communication with Sabcom Source: https://github.com/3axap4ehko/sabcom/blob/master/README.md Illustrates a worker thread receiving data from the main thread via a SharedArrayBuffer using Sabcom's synchronous read/write functions. It processes the received task and sends a result back. ```typescript import { workerData, parentPort } from 'worker_threads'; import { readSync, writeSync } from 'sabcom'; const { id, buffer } = workerData as { id: number; buffer: SharedArrayBuffer }; // Receive task from main const task = new TextDecoder().decode(readSync(buffer)); console.log(`Worker ${id} received: ${task}`); // Process and respond const result = `${task.toUpperCase()}-done`; writeSync(new TextEncoder().encode(result), buffer); ``` -------------------------------- ### Synchronous Write Data using sabcom Source: https://context7.com/3axap4ehko/sabcom/llms.txt Synchronously writes byte data to a SharedArrayBuffer, blocking until the reader has acknowledged receipt of all data. This API is best suited for use within worker threads where blocking operations are acceptable. It ensures data is fully transferred before proceeding. ```typescript // worker.ts - runs in a worker thread import { workerData } from 'worker_threads'; import { readSync, writeSync } from 'sabcom'; const buffer = workerData as SharedArrayBuffer; try { // Wait for data from main thread (blocking) console.log('Worker: Waiting for data...'); const receivedData = readSync(buffer); const message = new TextDecoder().decode(receivedData); console.log('Worker: Received message:', message); // Output: Worker: Received message: Hello from main // Process and send response (blocking) const reply = new TextEncoder().encode(message.toUpperCase()); writeSync(reply, buffer); console.log('Worker: Sent reply'); } catch (err) { console.error('Worker: Error', err); process.exit(1); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.