UNPKG

@ton-community/tlb-runtime

Version:

TL‑B Runtime is a library for parsing and (de)serializing data according to TL‑B schemas

48 lines (47 loc) 1.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringToBits = stringToBits; exports.bitsToString = bitsToString; exports.normalizeBitString = normalizeBitString; exports.toCell = toCell; const core_1 = require("@ton/core"); const TLBRuntime_1 = require("./TLBRuntime"); function stringToBits(text) { const bytes = Buffer.from(text, 'utf-8'); return new core_1.BitString(bytes, 0, bytes.length * 8); } function bitsToString(bits) { if (bits.length % 8 !== 0) { throw new Error('Bits must be at least 8 bits'); } let text = ''; for (let offset = 0; offset < bits.length; offset += 8) { text += String.fromCharCode(parseInt(`0x${bits.substring(offset, 8).toString()}`)); } return text; } function normalizeBitString(bits) { const length = bits.length; const newBuffer = Buffer.alloc(Math.ceil(length / 8)); for (let i = 0; i < length; i++) { const byteIndex = Math.floor(i / 8); const bitIndex = 7 - (i % 8); if (bits.at(i)) { newBuffer[byteIndex] |= 1 << bitIndex; } } return new core_1.BitString(newBuffer, 0, length); } function toCell(data) { try { return { success: true, value: core_1.Cell.fromBase64(data) }; } catch (_) { try { return { success: true, value: core_1.Cell.fromHex(data) }; } catch (_) { return { success: false, error: new TLBRuntime_1.TLBDataError('Bad BoC string') }; } } }