UNPKG

@ton3/liteclient

Version:
135 lines (96 loc) 3.38 kB
import { Utils } from 'ton3-core' import { uintToBytes } from './utils' import { TLBoolean } from '../types/boolean' export class StreamWriter { private _buffer = new ArrayBuffer(0) private concat (values: ArrayBuffer[]): ArrayBuffer { const length = values.reduce((acc, el) => acc += el.byteLength, 0) const { temp } = values.reduce((acc, el) => { acc.temp.set(new Uint8Array(el), acc.offset) return { temp: acc.temp, offset: acc.offset += el.byteLength } }, { temp: new Uint8Array(length), offset: 0 }) return temp.buffer } private append (value: ArrayBuffer): this { this._buffer = this.concat([ this._buffer, value ]) return this } private view (size: number): DataView { const buffer = new ArrayBuffer(size) return new DataView(buffer) } public writeBytes (value: Uint8Array): this { const lengthSize = value.length < 254 ? 1 : 4 const paddingSize = 4 - (((lengthSize + value.length) % 4) || 4) const buffer = new Uint8Array(lengthSize + value.length + paddingSize).fill(0) if (value.length < 254) { buffer.set([ value.length ], 0) } else { buffer.set([ 0xfe ], 0) // Write 3 bytes number in little-endian order buffer.set(uintToBytes(value.length, 3).reverse(), 1) } buffer.set(value, lengthSize) this.append(buffer.buffer) return this } public writeBuffer (value: Uint8Array): this { this.append(value) return this } public writeBool (value: boolean): this { this.writeUint32LE(value ? TLBoolean.TRUE : TLBoolean.FALSE) return this } public writeUint8 (value: number): this { const view = this.view(1) view.setUint8(0, value) this.append(view.buffer) return this } public writeInt32LE (value: number): this { const view = this.view(4) view.setInt32(0, value, true) this.append(view.buffer) return this } public writeUint32LE (value: number): this { const view = this.view(4) view.setUint32(0, value, true) this.append(view.buffer) return this } public writeInt64LE (value: bigint): this { const view = this.view(8) view.setBigInt64(0, value, true) this.append(view.buffer) return this } public writeUint64LE (value: bigint): this { const view = this.view(8) view.setBigUint64(0, value, true) this.append(view.buffer) return this } public writeInt128 (value: string | Uint8Array): this { const buffer = new Uint8Array(16).fill(0) const bytes = typeof value === 'string' ? Utils.Helpers.hexToBytes(value) : value buffer.set(bytes, 0) this.append(buffer.buffer) return this } public writeInt256 (value: string | Uint8Array): this { const buffer = new Uint8Array(32).fill(0) const bytes = typeof value === 'string' ? Utils.Helpers.hexToBytes(value) : value buffer.set(bytes, 0) this.append(buffer.buffer) return this } get buffer (): Uint8Array { return new Uint8Array(this._buffer) } }