import { createCodec, createDecoder, Bytes } from 'scale-ts';
import { compactNumber } from './compact.mjs';
import { mergeUint8 } from '@pezkuwi/papi-utils';

const dec = (isLsb = true) => createDecoder((data) => {
  const bitsLen = compactNumber.dec(data);
  const bytesLen = Math.ceil(bitsLen / 8);
  const bytes = Bytes(bytesLen).dec(data);
  const result = new Array(bitsLen);
  let resultIdx = 0;
  bytes.forEach((val) => {
    for (let i = 0; i < 8 && resultIdx < bitsLen; i++) {
      const actualIdx = isLsb ? i : 7 - i;
      result[resultIdx++] = val >> actualIdx & 1;
    }
  });
  return result;
});
const enc = (isLsb = true) => (input) => {
  const lenEncoded = compactNumber.enc(input.length);
  const nBytes = Math.ceil(input.length / 8);
  const bytes = new Uint8Array(nBytes);
  for (let byteIdx = 0; byteIdx < nBytes; byteIdx++) {
    let inputIdx = byteIdx * 8;
    let byte = 0;
    for (let i = 0; i < 8 && inputIdx < input.length; i++, inputIdx++)
      byte |= input[inputIdx] << (isLsb ? i : 7 - i);
    bytes[byteIdx] = byte;
  }
  return mergeUint8([lenEncoded, bytes]);
};
const BitSeq = (isLsb) => createCodec(enc(isLsb), dec(isLsb));
BitSeq.enc = enc;
BitSeq.dec = dec;

export { BitSeq };
//# sourceMappingURL=BitSeq.mjs.map
