Files
suaveplan/packages/foundation/flow/streams/src/utils/buffer/uint8-slice/uint8-slice.md
2026-05-27 23:47:53 +01:00

2.4 KiB

createUint8ArraySlice

(no submodules)

Purpose

createUint8ArraySlice returns an independent copy of a sub-range of a Uint8Array. The streams package favours explicit copy-vs-view semantics over the conventional subarray (view) / slice (copy) ambiguity that has bitten many consumers writing both browser and Node code. This helper makes the intent obvious at the call site: when you call createUint8ArraySlice, you get back memory you fully own.

It is functionally a thin wrapper around Uint8Array.prototype.slice, but named to communicate the copy semantics, and centralised so that future optimisations (e.g. fast-path detection of zero-length, large-buffer pooling) have a single place to live.

Features

  • Always copies — never returns a view aliasing the source buffer.
  • Clamps end past length per the standard slice algorithm.
  • Returns an empty Uint8Array when start === end.
  • Pure, synchronous, dependency-free.

Usage: Basic Example

import { createUint8ArraySlice } from "@suaveplan/streams/utils/buffer/uint8-slice/uint8-slice";

const src = new Uint8Array([1, 2, 3, 4, 5]);
const middle = createUint8ArraySlice(src, 1, 4); // Uint8Array(3) [2, 3, 4]

Usage: Advanced Example

import { createUint8ArraySlice } from "@suaveplan/streams/utils/buffer/uint8-slice/uint8-slice";

// Frame parser: each frame owns its bytes so the surrounding ring buffer can
// be recycled without stalling downstream consumers.
function parseFrames(buf: Uint8Array, frameSize: number): Uint8Array[] {
    const out: Uint8Array[] = [];
    for (let i = 0; i + frameSize <= buf.byteLength; i += frameSize) {
        out.push(createUint8ArraySlice(buf, i, i + frameSize));
    }
    return out;
}

API Reference

createUint8ArraySlice(array, start, end): Uint8Array

  • array: Uint8Array — source buffer.
  • start: number — inclusive start index.
  • end: number — exclusive end index; clamped to array.length.
  • Returns — a fresh Uint8Array of length max(0, end - start).
  • Throws — never.

Implementation Notes

  • Implemented as array.slice(start, end). The function exists because the copy-vs-view distinction matters for streams correctness (subarray would hold the entire upstream buffer alive) and a named helper documents intent better than an inline .slice call would.
  • Universal: zero environment dependencies.