BinaryMiddleware.js 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. */
  4. "use strict";
  5. const memoize = require("../util/memoize");
  6. const SerializerMiddleware = require("./SerializerMiddleware");
  7. /** @typedef {import("./types").BufferSerializableType} BufferSerializableType */
  8. /** @typedef {import("./types").PrimitiveSerializableType} PrimitiveSerializableType */
  9. /*
  10. Format:
  11. File -> Section*
  12. Section -> NullsSection |
  13. BooleansSection |
  14. F64NumbersSection |
  15. I32NumbersSection |
  16. I8NumbersSection |
  17. ShortStringSection |
  18. BigIntSection |
  19. I32BigIntSection |
  20. I8BigIntSection
  21. StringSection |
  22. BufferSection |
  23. NopSection
  24. NullsSection ->
  25. NullHeaderByte | Null2HeaderByte | Null3HeaderByte |
  26. Nulls8HeaderByte 0xnn (n:count - 4) |
  27. Nulls32HeaderByte n:ui32 (n:count - 260) |
  28. BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte
  29. F64NumbersSection -> F64NumbersSectionHeaderByte f64*
  30. I32NumbersSection -> I32NumbersSectionHeaderByte i32*
  31. I8NumbersSection -> I8NumbersSectionHeaderByte i8*
  32. ShortStringSection -> ShortStringSectionHeaderByte ascii-byte*
  33. StringSection -> StringSectionHeaderByte i32:length utf8-byte*
  34. BufferSection -> BufferSectionHeaderByte i32:length byte*
  35. NopSection --> NopSectionHeaderByte
  36. BigIntSection -> BigIntSectionHeaderByte i32:length ascii-byte*
  37. I32BigIntSection -> I32BigIntSectionHeaderByte i32
  38. I8BigIntSection -> I8BigIntSectionHeaderByte i8
  39. ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length)
  40. F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1)
  41. I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1)
  42. I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1)
  43. NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1)
  44. BooleansCountAndBitsByte ->
  45. 0b0000_1xxx (count = 3) |
  46. 0b0001_xxxx (count = 4) |
  47. 0b001x_xxxx (count = 5) |
  48. 0b01xx_xxxx (count = 6) |
  49. 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133)
  50. 0xff n:ui32 (n:count, 134 <= count < 2^32)
  51. StringSectionHeaderByte -> 0b0000_1110
  52. BufferSectionHeaderByte -> 0b0000_1111
  53. NopSectionHeaderByte -> 0b0000_1011
  54. BigIntSectionHeaderByte -> 0b0001_1010
  55. I32BigIntSectionHeaderByte -> 0b0001_1100
  56. I8BigIntSectionHeaderByte -> 0b0001_1011
  57. FalseHeaderByte -> 0b0000_1100
  58. TrueHeaderByte -> 0b0000_1101
  59. RawNumber -> n (n <= 10)
  60. */
  61. const LAZY_HEADER = 0x0b;
  62. const TRUE_HEADER = 0x0c;
  63. const FALSE_HEADER = 0x0d;
  64. const BOOLEANS_HEADER = 0x0e;
  65. const NULL_HEADER = 0x10;
  66. const NULL2_HEADER = 0x11;
  67. const NULL3_HEADER = 0x12;
  68. const NULLS8_HEADER = 0x13;
  69. const NULLS32_HEADER = 0x14;
  70. const NULL_AND_I8_HEADER = 0x15;
  71. const NULL_AND_I32_HEADER = 0x16;
  72. const NULL_AND_TRUE_HEADER = 0x17;
  73. const NULL_AND_FALSE_HEADER = 0x18;
  74. const BIGINT_HEADER = 0x1a;
  75. const BIGINT_I8_HEADER = 0x1b;
  76. const BIGINT_I32_HEADER = 0x1c;
  77. const STRING_HEADER = 0x1e;
  78. const BUFFER_HEADER = 0x1f;
  79. const I8_HEADER = 0x60;
  80. const I32_HEADER = 0x40;
  81. const F64_HEADER = 0x20;
  82. const SHORT_STRING_HEADER = 0x80;
  83. /** Uplift high-order bits */
  84. const NUMBERS_HEADER_MASK = 0xe0; // 0b1010_0000
  85. const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111
  86. const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111
  87. const HEADER_SIZE = 1;
  88. const I8_SIZE = 1;
  89. const I32_SIZE = 4;
  90. const F64_SIZE = 8;
  91. const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION");
  92. const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION");
  93. /** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */
  94. /** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */
  95. /**
  96. * Returns type of number for serialization.
  97. * @param {number} n number
  98. * @returns {0 | 1 | 2} type of number for serialization
  99. */
  100. const identifyNumber = (n) => {
  101. if (n === (n | 0)) {
  102. if (n <= 127 && n >= -128) return 0;
  103. if (n <= 2147483647 && n >= -2147483648) return 1;
  104. }
  105. return 2;
  106. };
  107. /**
  108. * Returns type of bigint for serialization.
  109. * @param {bigint} n bigint
  110. * @returns {0 | 1 | 2} type of bigint for serialization
  111. */
  112. const identifyBigInt = (n) => {
  113. if (n <= BigInt(127) && n >= BigInt(-128)) return 0;
  114. if (n <= BigInt(2147483647) && n >= BigInt(-2147483648)) return 1;
  115. return 2;
  116. };
  117. /** @typedef {PrimitiveSerializableType[]} DeserializedType */
  118. /** @typedef {BufferSerializableType[]} SerializedType} */
  119. /** @typedef {{ retainedBuffer?: (x: Buffer) => Buffer }} Context} */
  120. /**
  121. * Defines the lazy function type used by this module.
  122. * @template LazyInputValue
  123. * @template LazyOutputValue
  124. * @typedef {import("./SerializerMiddleware").LazyFunction<LazyInputValue, LazyOutputValue, BinaryMiddleware, undefined>} LazyFunction
  125. */
  126. /**
  127. * Represents BinaryMiddleware.
  128. * @extends {SerializerMiddleware<DeserializedType, SerializedType, Context>}
  129. */
  130. class BinaryMiddleware extends SerializerMiddleware {
  131. /**
  132. * Serializes this instance into the provided serializer context.
  133. * @param {DeserializedType} data data
  134. * @param {Context} context context object
  135. * @returns {SerializedType | Promise<SerializedType> | null} serialized data
  136. */
  137. serialize(data, context) {
  138. return this._serialize(data, context);
  139. }
  140. /**
  141. * Returns new lazy.
  142. * @param {LazyFunction<DeserializedType, SerializedType>} fn lazy function
  143. * @param {Context} context serialize function
  144. * @returns {LazyFunction<SerializedType, DeserializedType>} new lazy
  145. */
  146. _serializeLazy(fn, context) {
  147. return SerializerMiddleware.serializeLazy(fn, (data) =>
  148. this._serialize(data, context)
  149. );
  150. }
  151. /**
  152. * Returns serialized data.
  153. * @param {DeserializedType} data data
  154. * @param {Context} context context object
  155. * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope
  156. * @returns {SerializedType} serialized data
  157. */
  158. _serialize(
  159. data,
  160. context,
  161. allocationScope = {
  162. allocationSize: 1024,
  163. increaseCounter: 0,
  164. leftOverBuffer: null
  165. }
  166. ) {
  167. /** @type {Buffer | null} */
  168. let leftOverBuffer = null;
  169. /** @type {BufferSerializableType[]} */
  170. let buffers = [];
  171. /** @type {Buffer | null} */
  172. let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null;
  173. allocationScope.leftOverBuffer = null;
  174. let currentPosition = 0;
  175. if (currentBuffer === null) {
  176. currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize);
  177. }
  178. /**
  179. * Processes the provided bytes needed.
  180. * @param {number} bytesNeeded bytes needed
  181. */
  182. const allocate = (bytesNeeded) => {
  183. if (currentBuffer !== null) {
  184. if (currentBuffer.length - currentPosition >= bytesNeeded) return;
  185. flush();
  186. }
  187. if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) {
  188. currentBuffer = leftOverBuffer;
  189. leftOverBuffer = null;
  190. } else {
  191. currentBuffer = Buffer.allocUnsafe(
  192. Math.max(bytesNeeded, allocationScope.allocationSize)
  193. );
  194. if (
  195. !(allocationScope.increaseCounter =
  196. (allocationScope.increaseCounter + 1) % 4) &&
  197. allocationScope.allocationSize < 16777216
  198. ) {
  199. allocationScope.allocationSize <<= 1;
  200. }
  201. }
  202. };
  203. const flush = () => {
  204. if (currentBuffer !== null) {
  205. if (currentPosition > 0) {
  206. buffers.push(
  207. Buffer.from(
  208. currentBuffer.buffer,
  209. currentBuffer.byteOffset,
  210. currentPosition
  211. )
  212. );
  213. }
  214. if (
  215. !leftOverBuffer ||
  216. leftOverBuffer.length < currentBuffer.length - currentPosition
  217. ) {
  218. leftOverBuffer = Buffer.from(
  219. currentBuffer.buffer,
  220. currentBuffer.byteOffset + currentPosition,
  221. currentBuffer.byteLength - currentPosition
  222. );
  223. }
  224. currentBuffer = null;
  225. currentPosition = 0;
  226. }
  227. };
  228. /**
  229. * Processes the provided byte.
  230. * @param {number} byte byte
  231. */
  232. const writeU8 = (byte) => {
  233. /** @type {Buffer} */
  234. (currentBuffer).writeUInt8(byte, currentPosition++);
  235. };
  236. /**
  237. * Processes the provided ui32.
  238. * @param {number} ui32 ui32
  239. */
  240. const writeU32 = (ui32) => {
  241. /** @type {Buffer} */
  242. (currentBuffer).writeUInt32LE(ui32, currentPosition);
  243. currentPosition += 4;
  244. };
  245. /** @type {number[]} */
  246. const measureStack = [];
  247. const measureStart = () => {
  248. measureStack.push(buffers.length, currentPosition);
  249. };
  250. /**
  251. * Returns size.
  252. * @returns {number} size
  253. */
  254. const measureEnd = () => {
  255. const oldPos = /** @type {number} */ (measureStack.pop());
  256. const buffersIndex = /** @type {number} */ (measureStack.pop());
  257. let size = currentPosition - oldPos;
  258. for (let i = buffersIndex; i < buffers.length; i++) {
  259. size += buffers[i].length;
  260. }
  261. return size;
  262. };
  263. for (let i = 0; i < data.length; i++) {
  264. const thing = data[i];
  265. switch (typeof thing) {
  266. case "function": {
  267. if (!SerializerMiddleware.isLazy(thing)) {
  268. throw new Error(`Unexpected function ${thing}`);
  269. }
  270. /** @type {SerializedType | LazyFunction<SerializedType, DeserializedType> | undefined} */
  271. let serializedData =
  272. SerializerMiddleware.getLazySerializedValue(thing);
  273. if (serializedData === undefined) {
  274. if (SerializerMiddleware.isLazy(thing, this)) {
  275. flush();
  276. allocationScope.leftOverBuffer = leftOverBuffer;
  277. const result =
  278. /** @type {PrimitiveSerializableType[]} */
  279. (thing());
  280. const data = this._serialize(result, context, allocationScope);
  281. leftOverBuffer = allocationScope.leftOverBuffer;
  282. allocationScope.leftOverBuffer = null;
  283. SerializerMiddleware.setLazySerializedValue(thing, data);
  284. serializedData = data;
  285. } else {
  286. serializedData = this._serializeLazy(thing, context);
  287. flush();
  288. buffers.push(serializedData);
  289. break;
  290. }
  291. } else if (typeof serializedData === "function") {
  292. flush();
  293. buffers.push(serializedData);
  294. break;
  295. }
  296. /** @type {number[]} */
  297. const lengths = [];
  298. for (const item of serializedData) {
  299. /** @type {undefined | number} */
  300. let last;
  301. if (typeof item === "function") {
  302. lengths.push(0);
  303. } else if (item.length === 0) {
  304. // ignore
  305. } else if (
  306. lengths.length > 0 &&
  307. (last = lengths[lengths.length - 1]) !== 0
  308. ) {
  309. const remaining = 0xffffffff - last;
  310. if (remaining >= item.length) {
  311. lengths[lengths.length - 1] += item.length;
  312. } else {
  313. lengths.push(item.length - remaining);
  314. lengths[lengths.length - 2] = 0xffffffff;
  315. }
  316. } else {
  317. lengths.push(item.length);
  318. }
  319. }
  320. allocate(5 + lengths.length * 4);
  321. writeU8(LAZY_HEADER);
  322. writeU32(lengths.length);
  323. for (const l of lengths) {
  324. writeU32(l);
  325. }
  326. flush();
  327. for (const item of serializedData) {
  328. buffers.push(item);
  329. }
  330. break;
  331. }
  332. case "string": {
  333. const len = Buffer.byteLength(thing);
  334. if (len >= 128 || len !== thing.length) {
  335. allocate(len + HEADER_SIZE + I32_SIZE);
  336. writeU8(STRING_HEADER);
  337. writeU32(len);
  338. currentBuffer.write(thing, currentPosition);
  339. currentPosition += len;
  340. } else if (len >= 70) {
  341. allocate(len + HEADER_SIZE);
  342. writeU8(SHORT_STRING_HEADER | len);
  343. currentBuffer.write(thing, currentPosition, "latin1");
  344. currentPosition += len;
  345. } else {
  346. allocate(len + HEADER_SIZE);
  347. writeU8(SHORT_STRING_HEADER | len);
  348. for (let i = 0; i < len; i++) {
  349. currentBuffer[currentPosition++] = thing.charCodeAt(i);
  350. }
  351. }
  352. break;
  353. }
  354. case "bigint": {
  355. const type = identifyBigInt(thing);
  356. if (type === 0 && thing >= 0 && thing <= BigInt(10)) {
  357. // shortcut for very small bigints
  358. allocate(HEADER_SIZE + I8_SIZE);
  359. writeU8(BIGINT_I8_HEADER);
  360. writeU8(Number(thing));
  361. break;
  362. }
  363. switch (type) {
  364. case 0: {
  365. let n = 1;
  366. allocate(HEADER_SIZE + I8_SIZE * n);
  367. writeU8(BIGINT_I8_HEADER | (n - 1));
  368. while (n > 0) {
  369. currentBuffer.writeInt8(
  370. Number(/** @type {bigint} */ (data[i])),
  371. currentPosition
  372. );
  373. currentPosition += I8_SIZE;
  374. n--;
  375. i++;
  376. }
  377. i--;
  378. break;
  379. }
  380. case 1: {
  381. let n = 1;
  382. allocate(HEADER_SIZE + I32_SIZE * n);
  383. writeU8(BIGINT_I32_HEADER | (n - 1));
  384. while (n > 0) {
  385. currentBuffer.writeInt32LE(
  386. Number(/** @type {bigint} */ (data[i])),
  387. currentPosition
  388. );
  389. currentPosition += I32_SIZE;
  390. n--;
  391. i++;
  392. }
  393. i--;
  394. break;
  395. }
  396. default: {
  397. const value = thing.toString();
  398. const len = Buffer.byteLength(value);
  399. allocate(len + HEADER_SIZE + I32_SIZE);
  400. writeU8(BIGINT_HEADER);
  401. writeU32(len);
  402. currentBuffer.write(value, currentPosition);
  403. currentPosition += len;
  404. break;
  405. }
  406. }
  407. break;
  408. }
  409. case "number": {
  410. const type = identifyNumber(thing);
  411. if (type === 0 && thing >= 0 && thing <= 10) {
  412. // shortcut for very small numbers
  413. allocate(I8_SIZE);
  414. writeU8(thing);
  415. break;
  416. }
  417. /**
  418. * amount of numbers to write
  419. * @type {number}
  420. */
  421. let n = 1;
  422. for (; n < 32 && i + n < data.length; n++) {
  423. const item = data[i + n];
  424. if (typeof item !== "number") break;
  425. if (identifyNumber(item) !== type) break;
  426. }
  427. switch (type) {
  428. case 0:
  429. allocate(HEADER_SIZE + I8_SIZE * n);
  430. writeU8(I8_HEADER | (n - 1));
  431. while (n > 0) {
  432. currentBuffer.writeInt8(
  433. /** @type {number} */ (data[i]),
  434. currentPosition
  435. );
  436. currentPosition += I8_SIZE;
  437. n--;
  438. i++;
  439. }
  440. break;
  441. case 1:
  442. allocate(HEADER_SIZE + I32_SIZE * n);
  443. writeU8(I32_HEADER | (n - 1));
  444. while (n > 0) {
  445. currentBuffer.writeInt32LE(
  446. /** @type {number} */ (data[i]),
  447. currentPosition
  448. );
  449. currentPosition += I32_SIZE;
  450. n--;
  451. i++;
  452. }
  453. break;
  454. case 2:
  455. allocate(HEADER_SIZE + F64_SIZE * n);
  456. writeU8(F64_HEADER | (n - 1));
  457. while (n > 0) {
  458. currentBuffer.writeDoubleLE(
  459. /** @type {number} */ (data[i]),
  460. currentPosition
  461. );
  462. currentPosition += F64_SIZE;
  463. n--;
  464. i++;
  465. }
  466. break;
  467. }
  468. i--;
  469. break;
  470. }
  471. case "boolean": {
  472. let lastByte = thing === true ? 1 : 0;
  473. /** @type {number[]} */
  474. const bytes = [];
  475. let count = 1;
  476. /** @type {undefined | number} */
  477. let n;
  478. for (n = 1; n < 0xffffffff && i + n < data.length; n++) {
  479. const item = data[i + n];
  480. if (typeof item !== "boolean") break;
  481. const pos = count & 0x7;
  482. if (pos === 0) {
  483. bytes.push(lastByte);
  484. lastByte = item === true ? 1 : 0;
  485. } else if (item === true) {
  486. lastByte |= 1 << pos;
  487. }
  488. count++;
  489. }
  490. i += count - 1;
  491. if (count === 1) {
  492. allocate(HEADER_SIZE);
  493. writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER);
  494. } else if (count === 2) {
  495. allocate(HEADER_SIZE * 2);
  496. writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER);
  497. writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER);
  498. } else if (count <= 6) {
  499. allocate(HEADER_SIZE + I8_SIZE);
  500. writeU8(BOOLEANS_HEADER);
  501. writeU8((1 << count) | lastByte);
  502. } else if (count <= 133) {
  503. allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE);
  504. writeU8(BOOLEANS_HEADER);
  505. writeU8(0x80 | (count - 7));
  506. for (const byte of bytes) writeU8(byte);
  507. writeU8(lastByte);
  508. } else {
  509. allocate(
  510. HEADER_SIZE +
  511. I8_SIZE +
  512. I32_SIZE +
  513. I8_SIZE * bytes.length +
  514. I8_SIZE
  515. );
  516. writeU8(BOOLEANS_HEADER);
  517. writeU8(0xff);
  518. writeU32(count);
  519. for (const byte of bytes) writeU8(byte);
  520. writeU8(lastByte);
  521. }
  522. break;
  523. }
  524. case "object": {
  525. if (thing === null) {
  526. /** @type {number} */
  527. let n;
  528. for (n = 1; n < 0x100000104 && i + n < data.length; n++) {
  529. const item = data[i + n];
  530. if (item !== null) break;
  531. }
  532. i += n - 1;
  533. if (n === 1) {
  534. if (i + 1 < data.length) {
  535. const next = data[i + 1];
  536. if (next === true) {
  537. allocate(HEADER_SIZE);
  538. writeU8(NULL_AND_TRUE_HEADER);
  539. i++;
  540. } else if (next === false) {
  541. allocate(HEADER_SIZE);
  542. writeU8(NULL_AND_FALSE_HEADER);
  543. i++;
  544. } else if (typeof next === "number") {
  545. const type = identifyNumber(next);
  546. if (type === 0) {
  547. allocate(HEADER_SIZE + I8_SIZE);
  548. writeU8(NULL_AND_I8_HEADER);
  549. currentBuffer.writeInt8(next, currentPosition);
  550. currentPosition += I8_SIZE;
  551. i++;
  552. } else if (type === 1) {
  553. allocate(HEADER_SIZE + I32_SIZE);
  554. writeU8(NULL_AND_I32_HEADER);
  555. currentBuffer.writeInt32LE(next, currentPosition);
  556. currentPosition += I32_SIZE;
  557. i++;
  558. } else {
  559. allocate(HEADER_SIZE);
  560. writeU8(NULL_HEADER);
  561. }
  562. } else {
  563. allocate(HEADER_SIZE);
  564. writeU8(NULL_HEADER);
  565. }
  566. } else {
  567. allocate(HEADER_SIZE);
  568. writeU8(NULL_HEADER);
  569. }
  570. } else if (n === 2) {
  571. allocate(HEADER_SIZE);
  572. writeU8(NULL2_HEADER);
  573. } else if (n === 3) {
  574. allocate(HEADER_SIZE);
  575. writeU8(NULL3_HEADER);
  576. } else if (n < 260) {
  577. allocate(HEADER_SIZE + I8_SIZE);
  578. writeU8(NULLS8_HEADER);
  579. writeU8(n - 4);
  580. } else {
  581. allocate(HEADER_SIZE + I32_SIZE);
  582. writeU8(NULLS32_HEADER);
  583. writeU32(n - 260);
  584. }
  585. } else if (Buffer.isBuffer(thing)) {
  586. if (thing.length < 8192) {
  587. allocate(HEADER_SIZE + I32_SIZE + thing.length);
  588. writeU8(BUFFER_HEADER);
  589. writeU32(thing.length);
  590. thing.copy(currentBuffer, currentPosition);
  591. currentPosition += thing.length;
  592. } else {
  593. allocate(HEADER_SIZE + I32_SIZE);
  594. writeU8(BUFFER_HEADER);
  595. writeU32(thing.length);
  596. flush();
  597. buffers.push(thing);
  598. }
  599. }
  600. break;
  601. }
  602. case "symbol": {
  603. if (thing === MEASURE_START_OPERATION) {
  604. measureStart();
  605. } else if (thing === MEASURE_END_OPERATION) {
  606. const size = measureEnd();
  607. allocate(HEADER_SIZE + I32_SIZE);
  608. writeU8(I32_HEADER);
  609. currentBuffer.writeInt32LE(size, currentPosition);
  610. currentPosition += I32_SIZE;
  611. }
  612. break;
  613. }
  614. default: {
  615. throw new Error(
  616. `Unknown typeof "${typeof thing}" in binary middleware`
  617. );
  618. }
  619. }
  620. }
  621. flush();
  622. allocationScope.leftOverBuffer = leftOverBuffer;
  623. // avoid leaking memory
  624. currentBuffer = null;
  625. leftOverBuffer = null;
  626. allocationScope = /** @type {EXPECTED_ANY} */ (undefined);
  627. const _buffers = buffers;
  628. buffers = /** @type {EXPECTED_ANY} */ (undefined);
  629. return _buffers;
  630. }
  631. /**
  632. * Restores this instance from the provided deserializer context.
  633. * @param {SerializedType} data data
  634. * @param {Context} context context object
  635. * @returns {DeserializedType | Promise<DeserializedType>} deserialized data
  636. */
  637. deserialize(data, context) {
  638. return this._deserialize(data, context);
  639. }
  640. /**
  641. * Create lazy deserialized.
  642. * @private
  643. * @param {SerializedType} content content
  644. * @param {Context} context context object
  645. * @returns {LazyFunction<DeserializedType, SerializedType>} lazy function
  646. */
  647. _createLazyDeserialized(content, context) {
  648. return SerializerMiddleware.createLazy(
  649. memoize(() => this._deserialize(content, context)),
  650. this,
  651. undefined,
  652. content
  653. );
  654. }
  655. /**
  656. * Returns new lazy.
  657. * @private
  658. * @param {LazyFunction<SerializedType, DeserializedType>} fn lazy function
  659. * @param {Context} context context object
  660. * @returns {LazyFunction<DeserializedType, SerializedType>} new lazy
  661. */
  662. _deserializeLazy(fn, context) {
  663. return SerializerMiddleware.deserializeLazy(fn, (data) =>
  664. this._deserialize(data, context)
  665. );
  666. }
  667. /**
  668. * Returns deserialized data.
  669. * @param {SerializedType} data data
  670. * @param {Context} context context object
  671. * @returns {DeserializedType} deserialized data
  672. */
  673. _deserialize(data, context) {
  674. let currentDataItem = 0;
  675. /** @type {BufferSerializableType | null} */
  676. let currentBuffer = data[0];
  677. let currentIsBuffer = Buffer.isBuffer(currentBuffer);
  678. let currentPosition = 0;
  679. const retainedBuffer = context.retainedBuffer || ((x) => x);
  680. const checkOverflow = () => {
  681. if (currentPosition >= /** @type {Buffer} */ (currentBuffer).length) {
  682. currentPosition = 0;
  683. currentDataItem++;
  684. currentBuffer =
  685. currentDataItem < data.length ? data[currentDataItem] : null;
  686. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  687. }
  688. };
  689. /**
  690. * Checks whether this binary middleware is in current buffer.
  691. * @param {number} n n
  692. * @returns {boolean} true when in current buffer, otherwise false
  693. */
  694. const isInCurrentBuffer = (n) =>
  695. currentIsBuffer &&
  696. n + currentPosition <= /** @type {Buffer} */ (currentBuffer).length;
  697. const ensureBuffer = () => {
  698. if (!currentIsBuffer) {
  699. throw new Error(
  700. currentBuffer === null
  701. ? "Unexpected end of stream"
  702. : "Unexpected lazy element in stream"
  703. );
  704. }
  705. };
  706. /**
  707. * Returns buffer with bytes.
  708. * @param {number} n amount of bytes to read
  709. * @returns {Buffer} buffer with bytes
  710. */
  711. const read = (n) => {
  712. ensureBuffer();
  713. const rem =
  714. /** @type {Buffer} */ (currentBuffer).length - currentPosition;
  715. if (rem < n) {
  716. const buffers = [read(rem)];
  717. n -= rem;
  718. ensureBuffer();
  719. while (/** @type {Buffer} */ (currentBuffer).length < n) {
  720. const b = /** @type {Buffer} */ (currentBuffer);
  721. buffers.push(b);
  722. n -= b.length;
  723. currentDataItem++;
  724. currentBuffer =
  725. currentDataItem < data.length ? data[currentDataItem] : null;
  726. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  727. ensureBuffer();
  728. }
  729. buffers.push(read(n));
  730. return Buffer.concat(buffers);
  731. }
  732. const b = /** @type {Buffer} */ (currentBuffer);
  733. const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
  734. currentPosition += n;
  735. checkOverflow();
  736. return res;
  737. };
  738. /**
  739. * Reads up to n bytes
  740. * @param {number} n amount of bytes to read
  741. * @returns {Buffer} buffer with bytes
  742. */
  743. const readUpTo = (n) => {
  744. ensureBuffer();
  745. const rem =
  746. /** @type {Buffer} */
  747. (currentBuffer).length - currentPosition;
  748. if (rem < n) {
  749. n = rem;
  750. }
  751. const b = /** @type {Buffer} */ (currentBuffer);
  752. const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
  753. currentPosition += n;
  754. checkOverflow();
  755. return res;
  756. };
  757. /**
  758. * Returns u8.
  759. * @returns {number} U8
  760. */
  761. const readU8 = () => {
  762. ensureBuffer();
  763. /**
  764. * There is no need to check remaining buffer size here
  765. * since {@link checkOverflow} guarantees at least one byte remaining
  766. */
  767. const byte =
  768. /** @type {Buffer} */
  769. (currentBuffer).readUInt8(currentPosition);
  770. currentPosition += I8_SIZE;
  771. checkOverflow();
  772. return byte;
  773. };
  774. /**
  775. * Returns u32.
  776. * @returns {number} U32
  777. */
  778. const readU32 = () => read(I32_SIZE).readUInt32LE(0);
  779. /**
  780. * Processes the provided data.
  781. * @param {number} data data
  782. * @param {number} n n
  783. */
  784. const readBits = (data, n) => {
  785. let mask = 1;
  786. while (n !== 0) {
  787. result.push((data & mask) !== 0);
  788. mask <<= 1;
  789. n--;
  790. }
  791. };
  792. const dispatchTable = Array.from({ length: 256 }).map((_, header) => {
  793. switch (header) {
  794. case LAZY_HEADER:
  795. return () => {
  796. const count = readU32();
  797. const lengths = Array.from({ length: count }).map(() => readU32());
  798. /** @type {(Buffer | LazyFunction<SerializedType, DeserializedType>)[]} */
  799. const content = [];
  800. for (let l of lengths) {
  801. if (l === 0) {
  802. if (typeof currentBuffer !== "function") {
  803. throw new Error("Unexpected non-lazy element in stream");
  804. }
  805. content.push(currentBuffer);
  806. currentDataItem++;
  807. currentBuffer =
  808. currentDataItem < data.length ? data[currentDataItem] : null;
  809. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  810. } else {
  811. do {
  812. const buf = readUpTo(l);
  813. l -= buf.length;
  814. content.push(retainedBuffer(buf));
  815. } while (l > 0);
  816. }
  817. }
  818. result.push(this._createLazyDeserialized(content, context));
  819. };
  820. case BUFFER_HEADER:
  821. return () => {
  822. const len = readU32();
  823. result.push(retainedBuffer(read(len)));
  824. };
  825. case TRUE_HEADER:
  826. return () => result.push(true);
  827. case FALSE_HEADER:
  828. return () => result.push(false);
  829. case NULL3_HEADER:
  830. return () => result.push(null, null, null);
  831. case NULL2_HEADER:
  832. return () => result.push(null, null);
  833. case NULL_HEADER:
  834. return () => result.push(null);
  835. case NULL_AND_TRUE_HEADER:
  836. return () => result.push(null, true);
  837. case NULL_AND_FALSE_HEADER:
  838. return () => result.push(null, false);
  839. case NULL_AND_I8_HEADER:
  840. return () => {
  841. if (currentIsBuffer) {
  842. result.push(
  843. null,
  844. /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
  845. );
  846. currentPosition += I8_SIZE;
  847. checkOverflow();
  848. } else {
  849. result.push(null, read(I8_SIZE).readInt8(0));
  850. }
  851. };
  852. case NULL_AND_I32_HEADER:
  853. return () => {
  854. result.push(null);
  855. if (isInCurrentBuffer(I32_SIZE)) {
  856. result.push(
  857. /** @type {Buffer} */ (currentBuffer).readInt32LE(
  858. currentPosition
  859. )
  860. );
  861. currentPosition += I32_SIZE;
  862. checkOverflow();
  863. } else {
  864. result.push(read(I32_SIZE).readInt32LE(0));
  865. }
  866. };
  867. case NULLS8_HEADER:
  868. return () => {
  869. const len = readU8() + 4;
  870. for (let i = 0; i < len; i++) {
  871. result.push(null);
  872. }
  873. };
  874. case NULLS32_HEADER:
  875. return () => {
  876. const len = readU32() + 260;
  877. for (let i = 0; i < len; i++) {
  878. result.push(null);
  879. }
  880. };
  881. case BOOLEANS_HEADER:
  882. return () => {
  883. const innerHeader = readU8();
  884. if ((innerHeader & 0xf0) === 0) {
  885. readBits(innerHeader, 3);
  886. } else if ((innerHeader & 0xe0) === 0) {
  887. readBits(innerHeader, 4);
  888. } else if ((innerHeader & 0xc0) === 0) {
  889. readBits(innerHeader, 5);
  890. } else if ((innerHeader & 0x80) === 0) {
  891. readBits(innerHeader, 6);
  892. } else if (innerHeader !== 0xff) {
  893. let count = (innerHeader & 0x7f) + 7;
  894. while (count > 8) {
  895. readBits(readU8(), 8);
  896. count -= 8;
  897. }
  898. readBits(readU8(), count);
  899. } else {
  900. let count = readU32();
  901. while (count > 8) {
  902. readBits(readU8(), 8);
  903. count -= 8;
  904. }
  905. readBits(readU8(), count);
  906. }
  907. };
  908. case STRING_HEADER:
  909. return () => {
  910. const len = readU32();
  911. if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) {
  912. result.push(
  913. /** @type {Buffer} */
  914. (currentBuffer).toString(
  915. undefined,
  916. currentPosition,
  917. currentPosition + len
  918. )
  919. );
  920. currentPosition += len;
  921. checkOverflow();
  922. } else {
  923. result.push(read(len).toString());
  924. }
  925. };
  926. case SHORT_STRING_HEADER:
  927. return () => result.push("");
  928. case SHORT_STRING_HEADER | 1:
  929. return () => {
  930. if (currentIsBuffer && currentPosition < 0x7ffffffe) {
  931. result.push(
  932. /** @type {Buffer} */
  933. (currentBuffer).toString(
  934. "latin1",
  935. currentPosition,
  936. currentPosition + 1
  937. )
  938. );
  939. currentPosition++;
  940. checkOverflow();
  941. } else {
  942. result.push(read(1).toString("latin1"));
  943. }
  944. };
  945. case I8_HEADER:
  946. return () => {
  947. if (currentIsBuffer) {
  948. result.push(
  949. /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
  950. );
  951. currentPosition++;
  952. checkOverflow();
  953. } else {
  954. result.push(read(1).readInt8(0));
  955. }
  956. };
  957. case BIGINT_I8_HEADER: {
  958. const len = 1;
  959. return () => {
  960. const need = I8_SIZE * len;
  961. if (isInCurrentBuffer(need)) {
  962. for (let i = 0; i < len; i++) {
  963. const value =
  964. /** @type {Buffer} */
  965. (currentBuffer).readInt8(currentPosition);
  966. result.push(BigInt(value));
  967. currentPosition += I8_SIZE;
  968. }
  969. checkOverflow();
  970. } else {
  971. const buf = read(need);
  972. for (let i = 0; i < len; i++) {
  973. const value = buf.readInt8(i * I8_SIZE);
  974. result.push(BigInt(value));
  975. }
  976. }
  977. };
  978. }
  979. case BIGINT_I32_HEADER: {
  980. const len = 1;
  981. return () => {
  982. const need = I32_SIZE * len;
  983. if (isInCurrentBuffer(need)) {
  984. for (let i = 0; i < len; i++) {
  985. const value = /** @type {Buffer} */ (currentBuffer).readInt32LE(
  986. currentPosition
  987. );
  988. result.push(BigInt(value));
  989. currentPosition += I32_SIZE;
  990. }
  991. checkOverflow();
  992. } else {
  993. const buf = read(need);
  994. for (let i = 0; i < len; i++) {
  995. const value = buf.readInt32LE(i * I32_SIZE);
  996. result.push(BigInt(value));
  997. }
  998. }
  999. };
  1000. }
  1001. case BIGINT_HEADER: {
  1002. return () => {
  1003. const len = readU32();
  1004. if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) {
  1005. const value =
  1006. /** @type {Buffer} */
  1007. (currentBuffer).toString(
  1008. undefined,
  1009. currentPosition,
  1010. currentPosition + len
  1011. );
  1012. result.push(BigInt(value));
  1013. currentPosition += len;
  1014. checkOverflow();
  1015. } else {
  1016. const value = read(len).toString();
  1017. result.push(BigInt(value));
  1018. }
  1019. };
  1020. }
  1021. default:
  1022. if (header <= 10) {
  1023. return () => result.push(header);
  1024. } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) {
  1025. const len = header & SHORT_STRING_LENGTH_MASK;
  1026. return () => {
  1027. if (
  1028. isInCurrentBuffer(len) &&
  1029. currentPosition + len < 0x7fffffff
  1030. ) {
  1031. result.push(
  1032. /** @type {Buffer} */
  1033. (currentBuffer).toString(
  1034. "latin1",
  1035. currentPosition,
  1036. currentPosition + len
  1037. )
  1038. );
  1039. currentPosition += len;
  1040. checkOverflow();
  1041. } else {
  1042. result.push(read(len).toString("latin1"));
  1043. }
  1044. };
  1045. } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) {
  1046. const len = (header & NUMBERS_COUNT_MASK) + 1;
  1047. return () => {
  1048. const need = F64_SIZE * len;
  1049. if (isInCurrentBuffer(need)) {
  1050. for (let i = 0; i < len; i++) {
  1051. result.push(
  1052. /** @type {Buffer} */ (currentBuffer).readDoubleLE(
  1053. currentPosition
  1054. )
  1055. );
  1056. currentPosition += F64_SIZE;
  1057. }
  1058. checkOverflow();
  1059. } else {
  1060. const buf = read(need);
  1061. for (let i = 0; i < len; i++) {
  1062. result.push(buf.readDoubleLE(i * F64_SIZE));
  1063. }
  1064. }
  1065. };
  1066. } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) {
  1067. const len = (header & NUMBERS_COUNT_MASK) + 1;
  1068. return () => {
  1069. const need = I32_SIZE * len;
  1070. if (isInCurrentBuffer(need)) {
  1071. for (let i = 0; i < len; i++) {
  1072. result.push(
  1073. /** @type {Buffer} */ (currentBuffer).readInt32LE(
  1074. currentPosition
  1075. )
  1076. );
  1077. currentPosition += I32_SIZE;
  1078. }
  1079. checkOverflow();
  1080. } else {
  1081. const buf = read(need);
  1082. for (let i = 0; i < len; i++) {
  1083. result.push(buf.readInt32LE(i * I32_SIZE));
  1084. }
  1085. }
  1086. };
  1087. } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) {
  1088. const len = (header & NUMBERS_COUNT_MASK) + 1;
  1089. return () => {
  1090. const need = I8_SIZE * len;
  1091. if (isInCurrentBuffer(need)) {
  1092. for (let i = 0; i < len; i++) {
  1093. result.push(
  1094. /** @type {Buffer} */ (currentBuffer).readInt8(
  1095. currentPosition
  1096. )
  1097. );
  1098. currentPosition += I8_SIZE;
  1099. }
  1100. checkOverflow();
  1101. } else {
  1102. const buf = read(need);
  1103. for (let i = 0; i < len; i++) {
  1104. result.push(buf.readInt8(i * I8_SIZE));
  1105. }
  1106. }
  1107. };
  1108. }
  1109. return () => {
  1110. throw new Error(`Unexpected header byte 0x${header.toString(16)}`);
  1111. };
  1112. }
  1113. });
  1114. /** @type {DeserializedType} */
  1115. let result = [];
  1116. while (currentBuffer !== null) {
  1117. if (typeof currentBuffer === "function") {
  1118. result.push(this._deserializeLazy(currentBuffer, context));
  1119. currentDataItem++;
  1120. currentBuffer =
  1121. currentDataItem < data.length ? data[currentDataItem] : null;
  1122. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  1123. } else {
  1124. const header = readU8();
  1125. dispatchTable[header]();
  1126. }
  1127. }
  1128. // avoid leaking memory in context
  1129. // eslint-disable-next-line prefer-const
  1130. let _result = result;
  1131. result = /** @type {EXPECTED_ANY} */ (undefined);
  1132. return _result;
  1133. }
  1134. }
  1135. module.exports = BinaryMiddleware;
  1136. module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION;
  1137. module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION;