31 lines
1.0 KiB
JavaScript
31 lines
1.0 KiB
JavaScript
const MAX_REASONABLE_BYTES = 8 * 1024 ** 4;
|
|
|
|
function formatBytes(bytes) {
|
|
const value = Number(bytes);
|
|
if (!Number.isFinite(value) || value <= 0) return "0 B";
|
|
const units = ["B", "KB", "MB", "GB", "TB"];
|
|
const index = Math.min(units.length - 1, Math.floor(Math.log(value) / Math.log(1024)));
|
|
const amount = value / (1024 ** index);
|
|
return `${amount.toFixed(index === 0 ? 0 : amount >= 100 ? 0 : amount >= 10 ? 1 : 2)} ${units[index]}`;
|
|
}
|
|
|
|
function bytesFromMb(megabytes) {
|
|
const value = Number(megabytes);
|
|
return Number.isFinite(value) && value > 0 ? Math.round(value * 1048576) : 0;
|
|
}
|
|
|
|
function sanityCheckSize(label, bytes, expectedMaxBytes = MAX_REASONABLE_BYTES) {
|
|
const value = Number(bytes);
|
|
if (!Number.isFinite(value) || value < 0 || value > expectedMaxBytes) {
|
|
return {
|
|
valid: false,
|
|
label,
|
|
bytes: value,
|
|
message: `${label} reported an implausible byte count (${value}).`
|
|
};
|
|
}
|
|
return { valid: true, label, bytes: value };
|
|
}
|
|
|
|
module.exports = { formatBytes, bytesFromMb, sanityCheckSize };
|