UNPKG

@cloudpss/ubjson

Version:

Opinionated UBJSON encoder/decoder for CloudPSS.

64 lines 2.01 kB
import { EncodeTransformer } from './encoder.js'; import { DecodeTransformer } from './decoder.js'; export { UnexpectedEofError as UnexpectedEof } from '../helper/errors.js'; /** 编码为 UBJSON */ export function encode(value, options) { if (value == null) { return new ReadableStream({ type: 'bytes', start(controller) { const data = new Uint8Array([value === null ? 90 /* constants.NULL */ : 78 /* constants.NO_OP */]); controller.enqueue(data); controller.close(); }, }); } return new ReadableStream({ start(controller) { controller.enqueue(value); controller.close(); }, }).pipeThrough(encoder(options)); } /** 编码为 UBJSON */ export function encodeMany(value, options) { return new ReadableStream({ async start(controller) { for await (const v of value) { if (v == null) controller.enqueue(undefined); else controller.enqueue(v); } controller.close(); }, }).pipeThrough(encoder(options)); } /** 编码为 UBJSON */ export function encoder(options) { return new TransformStream(new EncodeTransformer(options)); } /** 解码 UBJSON */ export async function decode(stream, options) { const s = stream.pipeThrough(decoder(options)); const r = s.getReader(); const result = await r.read(); void r.cancel(); return result.done ? undefined : result.value; } /** 解码 UBJSON */ export async function* decodeMany(stream, options) { const s = stream.pipeThrough(decoder(options)); const r = s.getReader(); for (;;) { const { done, value } = await r.read(); if (done) break; yield value; } } /** 解码 UBJSON */ export function decoder(options) { return new TransformStream(new DecodeTransformer(options)); } //# sourceMappingURL=index.js.map