BinaryMiddleware.js 30 KB

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