UNPKG

json-bufferify

Version:

This is a tiny module to help you convert between JSON data and ArrayBuffer, and you can use it in both Node.js and browsers.

9 lines 2.35 kB
/** * json-bufferify 0.2.3 * Date: 2025-03-11 * © 2017-2025 LangZhai(智能小菜菜) * This is licensed under the GNU LGPL, version 3 or later. * For details, see: https://www.gnu.org/licenses/lgpl.html * Project home: https://github.com/LangZhai-rebirth/json-bufferify */ (e=>{const t=[{type:"Uint8",offset:1},{type:"Int8",offset:1},{type:"Uint16",offset:2},{type:"Int16",offset:2},{type:"Uint32",offset:4},{type:"Int32",offset:4},{type:"Float32",offset:4},{type:"Float64",offset:8}],f=(...e)=>{let t,n;return"boolean"==typeof e[0]?(t=e.slice(1),n=e[0]):t=e.slice(),t.forEach(e=>{e instanceof Object?Object.keys(e).forEach(o=>t[0][o]=n?f(n,e[o]instanceof Array?[]:{},e[o]):e[o]):t[0]=e}),t[0]},n=(e,f,o)=>(o instanceof Array&&f.push({val:o.length,type:"Uint8",offset:e++}),o instanceof Array&&o[0]instanceof Object?o.forEach(t=>e=n(e,f,t)):Object.keys(o).sort().forEach(a=>{if(o[a]instanceof Object)e=n(e,f,o[a]);else if("number"==typeof o[a]){let n,s;s=o[a]%1||(n=-2147483648>o[a]||o[a]>4294967295)?n||-3.4e38>o[a]||o[a]>3.4e38?7:6:0>o[a]?o[a]>-128?1:o[a]>-32768?3:5:256>o[a]?0:65536>o[a]?2:4,f.push({val:s,type:"Uint8",offset:e++},{val:o[a],type:t[s].type,offset:e}),e+=t[s].offset}else"boolean"==typeof o[a]?f.push({val:o[a]?1:0,type:"Uint8",offset:e++}):(o[a]=o[a].split("").map(e=>e.charCodeAt(0)),f.push({val:o[a].length,type:"Uint8",offset:e++}),o[a].forEach(t=>{f.push({val:t,type:"Uint16",offset:e}),e+=2}))}),e),o=(e,n,a)=>{let s;if(n instanceof Object)return s=a instanceof DataView?a:new DataView(a instanceof ArrayBuffer?a:new Uint8Array(a).buffer),n instanceof Array&&(n.length=s.getUint8(e++))&&n.fill(null,1).forEach((e,t)=>n[t]=f(!0,n[0]instanceof Array?[]:{},n[0])),n instanceof Array&&n[0]instanceof Object?n.forEach(t=>e=o(e,t,s)):Object.keys(n).sort().forEach(f=>{if(n[f]instanceof Object)e=o(e,n[f],s);else if("number"===n[f]){let o=t[s.getUint8(e++)];n[f]=s[`get${o.type}`](e),e+=o.offset}else"boolean"===n[f]?n[f]=!!s.getUint8(e++):n[f]=(n[f]=s.getUint8(e++))?String.fromCharCode(...Array(n[f]).fill().map(()=>{let t=s.getUint16(e);return e+=2,t})):""}),e};e.encode=((e,t)=>{let f=[],o=new DataView(new ArrayBuffer(n(e,f,t)));return f.forEach(e=>{o[`set${e.type}`](e.offset,e.val)}),o}),e.decode=((e,t,f)=>(o(e,t,f),t))})("undefined"!=typeof module&&module.exports?module.exports:self.bufferify=self.bufferify||{});