BinaryMiddleware.js 32 KB

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