formats.exposed/public/common/formatBytes.js

34 lines
665 B
JavaScript

// @ts-check
/**
* @param {Uint8Array} bytes
* @returns {string}
*/
export default (bytes, maxBytes = 1024) => {
let result = "";
let hasWrittenFirstByte = false;
// We truncate for performance.
//
// There are other ways to achieve this but this is the simplest.
const shouldTruncate = bytes.byteLength > maxBytes;
if (shouldTruncate) {
bytes = bytes.subarray(0, maxBytes);
}
for (const byte of bytes) {
if (hasWrittenFirstByte) {
result += " ";
} else {
hasWrittenFirstByte = true;
}
result += byte.toString(16).padStart(2, "0");
}
if (shouldTruncate) {
result += " … ";
}
return result;
};