byte-encodings
Version:
Utilities for encoding and decoding common formats like hex, base64, and varint. Ported from Deno's @std/encoding.
2 lines (1 loc) • 2.02 kB
JavaScript
var y=Object.defineProperty;var b=Object.getOwnPropertyDescriptor;var h=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var T=(t,r)=>{for(var e in r)y(t,e,{get:r[e],enumerable:!0})},w=(t,r,e,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of h(r))!g.call(t,o)&&o!==e&&y(t,o,{get:()=>r[o],enumerable:!(n=b(r,o))||n.enumerable});return t};var E=t=>w(y({},"__esModule",{value:!0}),t);var q={};T(q,{HexDecoderStream:()=>A,HexEncoderStream:()=>x});module.exports=E(q);var u=new TextEncoder().encode("0123456789abcdef"),c=new Uint8Array(128).fill(16);u.forEach((t,r)=>c[t]=r);new TextEncoder().encode("ABCDEF").forEach((t,r)=>c[t]=r+10);function U(t){return t*2}function l(t,r,e,n){for(;r<t.length;++r){let o=t[r];t[e++]=n[o>>4],t[e++]=n[o&15]}return e}function p(t,r,e,n){if((t.length-e)%2===1)throw new RangeError(`Cannot decode input as hex: Length (${t.length-e}) must be divisible by 2`);for(r+=1;r<t.length;r+=2)t[e++]=m(t[r-1],n)<<4|m(t[r],n);return e}function m(t,r){let e=r[t]??16;if(e===16)throw new TypeError(`Cannot decode input as hex: Invalid character (${String.fromCharCode(t)})`);return e}function d(t,r){let e=t.length;if(t.byteOffset){let n=new Uint8Array(t.buffer);n.set(t),t=n.subarray(0,e)}return t=new Uint8Array(t.buffer.transfer(r)),t.set(t.subarray(0,e),r-e),[t,r-e]}var f=new TextEncoder,C=new TextDecoder,x=class extends TransformStream{constructor(r={}){let e=function(){return r.output==="bytes"?n=>n:n=>C.decode(n)}();super({transform(n,o){let[s,i]=d(n,U(n.length));l(s,i,0,u),o.enqueue(e(s))}})}},A=class extends TransformStream{constructor(r={}){let e=function(){return r.input==="bytes"?s=>s:s=>f.encode(s)}(),n=new Uint8Array(1),o=0;super({transform(s,i){let a=e(s);o&&(a=d(a,o+a.length)[0],a.set(n.subarray(0,o))),o=a.length%2,o&&n.set(a.subarray(-o));let _=p(a.subarray(0,-o||void 0),0,0,c);i.enqueue(a.subarray(0,_))},flush(s){if(o){let i=p(n.subarray(0,o),0,0,c);s.enqueue(n.subarray(0,i))}}})}};0&&(module.exports={HexDecoderStream,HexEncoderStream});