import { Cbor } from "."; const read = (value: string) => { if (value.charAt(0) === "6") { return value.substring( 2, 2 + parseInt(Cbor.read(value.substring(1, 2)), 16) * 2 ); } else if (value.charAt(0) === "7") { switch (value.charAt(1).toLowerCase()) { case "8": return value.substring( 4, 4 + parseInt(Cbor.read(value.substring(2, 4)), 16) * 2 ); case "9": return value.substring( 4, 4 + parseInt(Cbor.read(value.substring(2, 6)), 16) * 2 ); case "a": return value.substring( 4, 4 + parseInt(Cbor.read(value.substring(2, 10)), 16) * 2 ); case "b": return value.substring( 4, 4 + parseInt(Cbor.read(value.substring(2, 18)), 16) * 2 ); case "f": throw "Unsupported text size"; // TODO: Read byte until a break is found to determine the size default: const size = parseInt(Cbor.read(value.substring(1, 2)), 16); return value.substring(2, 2 + (size + 16) * 2); } } else { console.log(value); throw "Not a text"; } }; const getLength = (value: string) => { const firstByte = Cbor.read(value); if (firstByte === "78") { return 4 + parseInt(value.substring(2, 4), 16) * 2; } else if (firstByte === "79") { return 6 + parseInt(value.substring(2, 6), 16) * 2; } else if (firstByte === "7a") { return 10 + parseInt(value.substring(2, 10), 16) * 2; } else if (firstByte === "7b") { return 18 + parseInt(value.substring(2, 18), 16) * 2; } else if (value.charAt(0) === "6") { return 2 + parseInt(value.substring(1, 2), 16) * 2; } else if (value.charAt(0) === "7") { return 2 + (parseInt(value.substring(1, 2), 16) + 16) * 2; } else { throw "Not a text"; } }; const encode = (value: string): string => { const textLength = value.length / 2; if (textLength <= 15) { return `6${textLength.toString(16)}${value}`; } else if (textLength >= 16 && textLength <= 23) { return `7${(textLength - 16).toString(16)}${value}`; } else if (textLength >= 24 && textLength <= 255) { return `78${textLength.toString(16).padStart(2, "0")}${value}`; } else if (textLength >= 256 && textLength <= 65535) { return `79${textLength.toString(16).padStart(4, "0")}${value}`; } else { throw "Text is too long, not supported."; } }; export const CborText = { read, encode, getLength, };