UNPKG

@neurosity/sdk

Version:
37 lines (36 loc) 1.34 kB
import { Buffer } from "buffer/index.js"; // not including /index.js causes typescript to uses Node's native Buffer built-in and we want to use this npm package for both node and the browser import { TRANSPORT_TYPE } from "../types"; /** * @hidden */ export class TextCodec { constructor(transportType) { this.transportType = transportType; if (transportType === TRANSPORT_TYPE.WEB) { this.webEncoder = new TextEncoder(); this.webDecoder = new TextDecoder("utf-8"); } } encode(data) { if (this.transportType === TRANSPORT_TYPE.WEB) { const encoded = this.webEncoder.encode(data); return encoded; } if (this.transportType === TRANSPORT_TYPE.REACT_NATIVE) { // React Native BLE Manager expects a number[] instead of a Uint8Array const encoded = [...Buffer.from(data)]; return encoded; } const encoded = Buffer.from(data); return encoded; } decode(arrayBuffer) { if (this.transportType === TRANSPORT_TYPE.WEB) { const decoded = this.webDecoder.decode(arrayBuffer); return decoded; } // For React Native, and as a default const decoded = Buffer.from(arrayBuffer).toString("utf-8"); return decoded; } }