Files
bare-operating-system/packages/bare-os-coreutils/src/sum.js
T
2026-04-03 23:04:42 -04:00

63 lines
1.6 KiB
JavaScript

function sumSysv(u8) {
let crc = 0
for (let i = 0; i < u8.length; i++) crc += u8[i]
crc = (crc & 0xffff) + ((crc >> 16) & 0xffff)
crc = (crc & 0xffff) + ((crc >> 16) & 0xffff)
return crc & 0xffff
}
function sumBsd(u8) {
let cksum = 0
for (let i = 0; i < u8.length; i++) {
cksum = (cksum >> 1) + ((cksum & 1) << 15)
cksum = (cksum + u8[i]) & 0xffff
}
return cksum
}
async function run(ctx, argv) {
let bsd = false
const paths = []
for (let i = 1; i < argv.length; i++) {
const a = argv[i]
if (a === '-h' || a === '--help') {
ctx.console.log(
'usage: sum [-r] [FILE]...\n' +
' -r BSD algorithm (default is SysV / CRC16-style sum)'
)
ctx.exitCode = 0
return
}
if (a === '-r') bsd = true
else if (a.startsWith('-') && a !== '-') {
ctx.console.error('sum: unsupported option ' + a)
ctx.exitCode = 1
return
} else paths.push(a)
}
const b4 = ctx.b4a
function one(name, buf) {
const u8 = buf instanceof Uint8Array ? buf : new Uint8Array(buf)
const blocks = Math.ceil(u8.length / 512) || 1
const v = bsd ? sumBsd(u8) : sumSysv(u8)
ctx.console.log(v + '\t' + blocks + '\t' + name)
}
if (!paths.length || (paths.length === 1 && paths[0] === '-')) {
one('-', b4.from(bareStdin(ctx)))
return
}
for (const p of paths) {
if (p === '-') {
one('-', b4.from(bareStdin(ctx)))
continue
}
const b = await ctx.vfs.readFile(p)
if (!b) {
ctx.console.error('sum: ' + p + ': No such file')
ctx.exitCode = 1
continue
}
one(p, b)
}
}