Public
Edited
Jan 2, 2024
Insert cell
Insert cell
import { base64, CBOR, varint } from "@gozala/ipld"
Insert cell
/**
* @param {number | bigint | string | Uint8Array} payload
* @returns {Uint8Array}
*/
toCBOR = (payload) => {
if (typeof payload === 'number') {
if (Number.isInteger(payload)) {
return payload >= 0
? new Uint8Array([0x00, payload])
: new Uint8Array([0x01, -payload]);
} else {
// Handle floating-point numbers
// Implement as needed
}
} else if (typeof payload === 'bigint') {
// Handle negative bigints
if (payload < 0n) {
return new Uint8Array([0x01, ...encodeNegativeBigInt(payload)]);
}
// Handle positive bigints
return new Uint8Array([0x01, ...encodePositiveBigInt(payload)]);
} else if (typeof payload === 'string') {
// Handle string encoding
// Implement as needed
} else if (payload instanceof Uint8Array) {
// Handle Uint8Array encoding
// Implement as needed
}

return new Uint8Array();
}
Insert cell
/**
* Helper function to encode a positive bigint
* @param {bigint} value
* @returns {number[]}
*/
encodePositiveBigInt = (value) => {
const bytes = [];
while (value > 0n) {
bytes.unshift(Number(value & 0xffn));
value >>= 8n;
}
return bytes;
}


Insert cell
/**
* Helper function to encode a negative bigint
* @param {bigint} value
* @returns {number[]}
*/
encodeNegativeBigInt = (value) => {
const bytes = encodePositiveBigInt(-value);
if (bytes[0] >= 0x80) {
bytes.unshift(0x00);
} else {
bytes[0] |= 0x80;
}
return bytes;
}
Insert cell
toCBOR(4)
Insert cell
CBOR.encode(4)
Insert cell
CBOR.encode(1067)
Insert cell
toCBOR(1067)
Insert cell
new Uint8Array([256])
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more