bend_puzzle/archive-codec.js
2026-07-31 12:54:46 +09:00

19 lines
1.2 KiB
JavaScript

'use strict';
(function attachArchiveCodec(root,factory){
const api=factory();
if(typeof module==='object'&&module.exports)module.exports=api;
if(root)root.BendArchiveCodec=api;
})(typeof globalThis!=='undefined'?globalThis:this,()=>{
const encoder=new TextEncoder(),crcTable=new Uint32Array(256);
for(let index=0;index<256;index++){let value=index;for(let bit=0;bit<8;bit++)value=value&1?0xedb88320^(value>>>1):value>>>1;crcTable[index]=value>>>0}
function encodeUtf8(value){return encoder.encode(String(value))}
function encodeRecord(record){return encodeUtf8(`${JSON.stringify(record)}\n`)}
function crc32Update(crc,bytes){let value=crc>>>0;for(const byte of bytes)value=crcTable[(value^byte)&255]^(value>>>8);return value>>>0}
function crc32Hex(crc){return((crc^0xffffffff)>>>0).toString(16).padStart(8,'0')}
function parseRecordLine(sourceLine){
const line=String(sourceLine).replace(/\r$/,'');let record;
try{record=JSON.parse(line)}catch(_){throw new Error('An archive record is not valid JSON.')}
return{line,record,bytes:encodeUtf8(`${line}\n`)};
}
return Object.freeze({encodeUtf8,encodeRecord,crc32Update,crc32Hex,parseRecordLine});
});