2.8 KiB
IdentityCodec
Purpose
IdentityCodec is the Codec<Uint8Array> implementation that passes bytes through without encoding overhead. Use it when the cached T is already binary — chunked file data, pre-serialised protobufs, encrypted blobs, audio samples — and reserialising through JSON would be wasteful or lossy. The codec is paired with StorageCache<Uint8Array> to provide a byte-cache surface over any AbstractStorage.
Features
- Zero-copy
encode— returns the inputUint8Arrayby reference. Suitable for high-throughput paths where allocations matter. - Defensive-copy
decode— returns a freshUint8Arrayso callers mutating the result cannot corrupt the underlying storage buffer. - No throws — every input is valid because the encode step is the identity function.
- Stateless — a single instance is safe to share across cache instances and concurrent operations.
Usage: Basic Example
import { IdentityCodec } from "@suaveplan/cache-storage/codec/identity";
import { StorageCache } from "@suaveplan/cache-storage";
import { MemoryStorage } from "@suaveplan/storage/memory";
const cache = new StorageCache<Uint8Array>({
storage: new MemoryStorage(),
codec: new IdentityCodec(),
});
await cache.set("blob:1", new Uint8Array([1, 2, 3, 4]));
const out = await cache.get("blob:1");
Usage: Advanced Example
import { IdentityCodec } from "@suaveplan/cache-storage/codec/identity";
import { StorageCache } from "@suaveplan/cache-storage";
// Cache pre-compressed payloads: avoid re-encoding on every cache hit.
const cache = new StorageCache<Uint8Array>({
storage: filesystemStorage,
codec: new IdentityCodec(),
defaultTtl: 60_000,
});
const compressed = await gzip(payload);
await cache.set(`gz:${id}`, compressed);
const cached = await cache.get(`gz:${id}`);
if (cached !== undefined) {
// Stream straight to the response without a decode step.
res.setHeader("content-encoding", "gzip");
res.end(cached);
}
API Reference
| Member | Signature | Description |
|---|---|---|
new IdentityCodec() |
— | Constructs a stateless codec. No arguments. |
encode(value) |
(Uint8Array) → Uint8Array |
Returns value by reference. |
decode(bytes) |
(Uint8Array) → Uint8Array |
Returns a fresh copy of bytes. |
Conforms to Codec<Uint8Array> from @suaveplan/cache-storage/codec.
Implementation Notes
The encode step is intentionally non-copying. StorageCache immediately wraps the returned bytes in a fresh combined buffer (header + body), so referential sharing does not bleed into the on-disk representation. The decode step copies because the storage backend may hand out its internal buffer for performance — MemoryStorage and storage-file both do — and a caller that mutated the result would otherwise see arbitrary corruption on the next read.