BinaryMiddleware.js 32 KB

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