|
|
import { IndexedByteArray } from "../indexed_array.js"; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function readBytesAsString(dataArray, bytes, encoding = undefined, trimEnd = true) |
|
|
{ |
|
|
if (!encoding) |
|
|
{ |
|
|
let finished = false; |
|
|
let string = ""; |
|
|
for (let i = 0; i < bytes; i++) |
|
|
{ |
|
|
let byte = dataArray[dataArray.currentIndex++]; |
|
|
if (finished) |
|
|
{ |
|
|
continue; |
|
|
} |
|
|
if ((byte < 32 || byte > 127) && byte !== 10) |
|
|
{ |
|
|
if (trimEnd) |
|
|
{ |
|
|
finished = true; |
|
|
continue; |
|
|
} |
|
|
else |
|
|
{ |
|
|
if (byte === 0) |
|
|
{ |
|
|
finished = true; |
|
|
continue; |
|
|
} |
|
|
} |
|
|
} |
|
|
string += String.fromCharCode(byte); |
|
|
} |
|
|
return string; |
|
|
} |
|
|
else |
|
|
{ |
|
|
let byteBuffer = dataArray.slice(dataArray.currentIndex, dataArray.currentIndex + bytes); |
|
|
dataArray.currentIndex += bytes; |
|
|
let decoder = new TextDecoder(encoding.replace(/[^\x20-\x7E]/g, "")); |
|
|
return decoder.decode(byteBuffer.buffer); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function getStringBytes(string, padLength = 0) |
|
|
{ |
|
|
let len = string.length; |
|
|
if (padLength > 0) |
|
|
{ |
|
|
len = padLength; |
|
|
} |
|
|
const arr = new IndexedByteArray(len); |
|
|
writeStringAsBytes(arr, string, padLength); |
|
|
return arr; |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function getStringBytesZero(string) |
|
|
{ |
|
|
return getStringBytes(string, string.length + 1); |
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
export function writeStringAsBytes(outArray, string, padLength = 0) |
|
|
{ |
|
|
if (padLength > 0) |
|
|
{ |
|
|
if (string.length > padLength) |
|
|
{ |
|
|
string = string.slice(0, padLength); |
|
|
} |
|
|
} |
|
|
for (let i = 0; i < string.length; i++) |
|
|
{ |
|
|
outArray[outArray.currentIndex++] = string.charCodeAt(i); |
|
|
} |
|
|
|
|
|
|
|
|
if (padLength > string.length) |
|
|
{ |
|
|
for (let i = 0; i < padLength - string.length; i++) |
|
|
{ |
|
|
outArray[outArray.currentIndex++] = 0; |
|
|
} |
|
|
} |
|
|
return outArray; |
|
|
} |