import { Cbor, CborByte, CborInteger, CborSet } from "."; import { CborText } from "./text"; const readArraySize = (value: string) => { if (value.charAt(0) === "8") { return parseInt(value.charAt(1), 16); } else if (value.charAt(0) === "9") { switch (value.charAt(1)) { case "8": return parseInt(value.substring(2, 4), 16); case "9": return parseInt(value.substring(2, 6), 16); case "a": return parseInt(value.substring(2, 10), 16); case "b": return parseInt(value.substring(2, 18), 16); case "f": return Cbor.countItemsUntilBreak(value); default: return parseInt(value.charAt(1), 16) + 16; } } else { throw "Not an array"; } }; const sizeToCbor = (arrayLength: number) => { if (arrayLength <= 15) { return `8${arrayLength.toString(16)}`; } else if (arrayLength >= 16 && arrayLength <= 23) { return `9${(arrayLength - 16).toString(16)}`; } else if (arrayLength >= 24 && arrayLength <= 255) { return `98${arrayLength.toString(16).padStart(2, "0")}`; } else if (arrayLength >= 256 && arrayLength <= 65535) { return `99${arrayLength.toString(16).padStart(4, "0")}`; } else { throw "Array is too long, not supported."; } }; const decode = (cborArray: string): Array => { const size = readArraySize(cborArray); const arrayBody = cborArray.substring(2); let cursor = 0; let finalArray = []; for (let i = 0; i < size; i++) { const nextValue = arrayBody.substring(cursor); const setItemLength = Cbor.readNextItemStringLength(nextValue); if (Cbor.identifyType(nextValue) === "set") { finalArray.push(CborSet.read(nextValue)); } else if ( Cbor.identifyType(nextValue) === "integer" || Cbor.identifyType(nextValue) === "unsigned" ) { finalArray.push(CborInteger.read(nextValue)); } else if (Cbor.identifyType(nextValue) === "array") { finalArray.push(decode(nextValue)); } else if (Cbor.identifyType(nextValue) === "byte") { finalArray.push(CborByte.read(nextValue)); } else if (Cbor.identifyType(nextValue) === "text") { finalArray.push(CborText.read(nextValue)); } else if (Cbor.identifyType(nextValue) === "primitive") { const val = nextValue.substring(0, 2).toLowerCase(); finalArray.push(val === "f4" ? false : true); } else { throw `Unidentified array value ${nextValue}`; } cursor += setItemLength; } return finalArray; }; export const CborArray = { decode, sizeToCbor, };