Skip to main content
Deno 2 is finally here 🎉️
Learn more
Module

x/bencodex/mod.ts>encodeInto

An alternative take on implementing Bencodex in TypeScript/JavaScript
Latest
function encodeInto
import { encodeInto } from "https://deno.land/x/bencodex@0.2.2/mod.ts";

Encodes a value into the given buffer.

This does not allocate a new buffer, and fills the given buffer with the encoded value from the beginning. If you want to fill the buffer from somewhere else, pass a sliced subarray of the buffer to this function.

Examples

Encoding a Bencodex list into a pre-allocated buffer

const buffer = new Uint8Array(100);
const state = encodeInto(["foo", 123n], buffer);
if (!state.complete) console.error("Failed to encode the value");
else console.log(buffer.subarray(0, state.written));
// Uint8Array(13) [ 0x6c, 0x75, 0x33, 0x3a, 0x66, 0x6f, 0x6f, 0x69, 0x31,
//                  0x32, 0x33, 0x65, 0x65 ]

Parameters

value: Value

A value to encode.

buffer: Uint8Array

A buffer that the encoded value will be written into. This buffer will be modified.

optional
options: NonAllocEncodingOptions = [UNSUPPORTED]

Encoding options.

Returns

EncodingState

The object which indicates the number of bytes written into the buffer and whether the encoding is complete.