BinaryMiddleware.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950
  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. StringSection |
  19. BufferSection |
  20. NopSection
  21. NullsSection ->
  22. NullHeaderByte | Null2HeaderByte | Null3HeaderByte |
  23. Nulls8HeaderByte 0xnn (n:count - 4) |
  24. Nulls32HeaderByte n:ui32 (n:count - 260) |
  25. BooleansSection -> TrueHeaderByte | FalseHeaderByte | BooleansSectionHeaderByte BooleansCountAndBitsByte
  26. F64NumbersSection -> F64NumbersSectionHeaderByte f64*
  27. I32NumbersSection -> I32NumbersSectionHeaderByte i32*
  28. I8NumbersSection -> I8NumbersSectionHeaderByte i8*
  29. ShortStringSection -> ShortStringSectionHeaderByte ascii-byte*
  30. StringSection -> StringSectionHeaderByte i32:length utf8-byte*
  31. BufferSection -> BufferSectionHeaderByte i32:length byte*
  32. NopSection --> NopSectionHeaderByte
  33. ShortStringSectionHeaderByte -> 0b1nnn_nnnn (n:length)
  34. F64NumbersSectionHeaderByte -> 0b001n_nnnn (n:count - 1)
  35. I32NumbersSectionHeaderByte -> 0b010n_nnnn (n:count - 1)
  36. I8NumbersSectionHeaderByte -> 0b011n_nnnn (n:count - 1)
  37. NullsSectionHeaderByte -> 0b0001_nnnn (n:count - 1)
  38. BooleansCountAndBitsByte ->
  39. 0b0000_1xxx (count = 3) |
  40. 0b0001_xxxx (count = 4) |
  41. 0b001x_xxxx (count = 5) |
  42. 0b01xx_xxxx (count = 6) |
  43. 0b1nnn_nnnn (n:count - 7, 7 <= count <= 133)
  44. 0xff n:ui32 (n:count, 134 <= count < 2^32)
  45. StringSectionHeaderByte -> 0b0000_1110
  46. BufferSectionHeaderByte -> 0b0000_1111
  47. NopSectionHeaderByte -> 0b0000_1011
  48. FalseHeaderByte -> 0b0000_1100
  49. TrueHeaderByte -> 0b0000_1101
  50. RawNumber -> n (n <= 10)
  51. */
  52. const LAZY_HEADER = 0x0b;
  53. const TRUE_HEADER = 0x0c;
  54. const FALSE_HEADER = 0x0d;
  55. const BOOLEANS_HEADER = 0x0e;
  56. const NULL_HEADER = 0x10;
  57. const NULL2_HEADER = 0x11;
  58. const NULL3_HEADER = 0x12;
  59. const NULLS8_HEADER = 0x13;
  60. const NULLS32_HEADER = 0x14;
  61. const NULL_AND_I8_HEADER = 0x15;
  62. const NULL_AND_I32_HEADER = 0x16;
  63. const NULL_AND_TRUE_HEADER = 0x17;
  64. const NULL_AND_FALSE_HEADER = 0x18;
  65. const STRING_HEADER = 0x1e;
  66. const BUFFER_HEADER = 0x1f;
  67. const I8_HEADER = 0x60;
  68. const I32_HEADER = 0x40;
  69. const F64_HEADER = 0x20;
  70. const SHORT_STRING_HEADER = 0x80;
  71. /** Uplift high-order bits */
  72. const NUMBERS_HEADER_MASK = 0xe0;
  73. const NUMBERS_COUNT_MASK = 0x1f; // 0b0001_1111
  74. const SHORT_STRING_LENGTH_MASK = 0x7f; // 0b0111_1111
  75. const HEADER_SIZE = 1;
  76. const I8_SIZE = 1;
  77. const I32_SIZE = 4;
  78. const F64_SIZE = 8;
  79. const MEASURE_START_OPERATION = Symbol("MEASURE_START_OPERATION");
  80. const MEASURE_END_OPERATION = Symbol("MEASURE_END_OPERATION");
  81. /** @typedef {typeof MEASURE_START_OPERATION} MEASURE_START_OPERATION_TYPE */
  82. /** @typedef {typeof MEASURE_END_OPERATION} MEASURE_END_OPERATION_TYPE */
  83. const identifyNumber = n => {
  84. if (n === (n | 0)) {
  85. if (n <= 127 && n >= -128) return 0;
  86. if (n <= 2147483647 && n >= -2147483648) return 1;
  87. }
  88. return 2;
  89. };
  90. /**
  91. * @typedef {PrimitiveSerializableType[]} DeserializedType
  92. * @typedef {BufferSerializableType[]} SerializedType
  93. * @extends {SerializerMiddleware<DeserializedType, SerializedType>}
  94. */
  95. class BinaryMiddleware extends SerializerMiddleware {
  96. /**
  97. * @param {DeserializedType} data data
  98. * @param {Object} context context object
  99. * @returns {SerializedType|Promise<SerializedType>} serialized data
  100. */
  101. serialize(data, context) {
  102. return this._serialize(data, context);
  103. }
  104. _serializeLazy(fn, context) {
  105. return SerializerMiddleware.serializeLazy(fn, data =>
  106. this._serialize(data, context)
  107. );
  108. }
  109. /**
  110. * @param {DeserializedType} data data
  111. * @param {Object} context context object
  112. * @param {{ leftOverBuffer: Buffer | null, allocationSize: number, increaseCounter: number }} allocationScope allocation scope
  113. * @returns {SerializedType} serialized data
  114. */
  115. _serialize(
  116. data,
  117. context,
  118. allocationScope = {
  119. allocationSize: 1024,
  120. increaseCounter: 0,
  121. leftOverBuffer: null
  122. }
  123. ) {
  124. /** @type {Buffer} */
  125. let leftOverBuffer = null;
  126. /** @type {BufferSerializableType[]} */
  127. let buffers = [];
  128. /** @type {Buffer} */
  129. let currentBuffer = allocationScope ? allocationScope.leftOverBuffer : null;
  130. allocationScope.leftOverBuffer = null;
  131. let currentPosition = 0;
  132. if (currentBuffer === null) {
  133. currentBuffer = Buffer.allocUnsafe(allocationScope.allocationSize);
  134. }
  135. const allocate = bytesNeeded => {
  136. if (currentBuffer !== null) {
  137. if (currentBuffer.length - currentPosition >= bytesNeeded) return;
  138. flush();
  139. }
  140. if (leftOverBuffer && leftOverBuffer.length >= bytesNeeded) {
  141. currentBuffer = leftOverBuffer;
  142. leftOverBuffer = null;
  143. } else {
  144. currentBuffer = Buffer.allocUnsafe(
  145. Math.max(bytesNeeded, allocationScope.allocationSize)
  146. );
  147. if (
  148. !(allocationScope.increaseCounter =
  149. (allocationScope.increaseCounter + 1) % 4) &&
  150. allocationScope.allocationSize < 16777216
  151. ) {
  152. allocationScope.allocationSize = allocationScope.allocationSize << 1;
  153. }
  154. }
  155. };
  156. const flush = () => {
  157. if (currentBuffer !== null) {
  158. if (currentPosition > 0) {
  159. buffers.push(
  160. Buffer.from(
  161. currentBuffer.buffer,
  162. currentBuffer.byteOffset,
  163. currentPosition
  164. )
  165. );
  166. }
  167. if (
  168. !leftOverBuffer ||
  169. leftOverBuffer.length < currentBuffer.length - currentPosition
  170. ) {
  171. leftOverBuffer = Buffer.from(
  172. currentBuffer.buffer,
  173. currentBuffer.byteOffset + currentPosition,
  174. currentBuffer.byteLength - currentPosition
  175. );
  176. }
  177. currentBuffer = null;
  178. currentPosition = 0;
  179. }
  180. };
  181. const writeU8 = byte => {
  182. currentBuffer.writeUInt8(byte, currentPosition++);
  183. };
  184. const writeU32 = ui32 => {
  185. currentBuffer.writeUInt32LE(ui32, currentPosition);
  186. currentPosition += 4;
  187. };
  188. const measureStack = [];
  189. const measureStart = () => {
  190. measureStack.push(buffers.length, currentPosition);
  191. };
  192. const measureEnd = () => {
  193. const oldPos = measureStack.pop();
  194. const buffersIndex = measureStack.pop();
  195. let size = currentPosition - oldPos;
  196. for (let i = buffersIndex; i < buffers.length; i++) {
  197. size += buffers[i].length;
  198. }
  199. return size;
  200. };
  201. for (let i = 0; i < data.length; i++) {
  202. const thing = data[i];
  203. switch (typeof thing) {
  204. case "function": {
  205. if (!SerializerMiddleware.isLazy(thing))
  206. throw new Error("Unexpected function " + thing);
  207. /** @type {SerializedType | (() => SerializedType)} */
  208. let serializedData =
  209. SerializerMiddleware.getLazySerializedValue(thing);
  210. if (serializedData === undefined) {
  211. if (SerializerMiddleware.isLazy(thing, this)) {
  212. flush();
  213. allocationScope.leftOverBuffer = leftOverBuffer;
  214. const result =
  215. /** @type {(Exclude<PrimitiveSerializableType, Promise<PrimitiveSerializableType>>)[]} */ (
  216. thing()
  217. );
  218. const data = this._serialize(result, context, allocationScope);
  219. leftOverBuffer = allocationScope.leftOverBuffer;
  220. allocationScope.leftOverBuffer = null;
  221. SerializerMiddleware.setLazySerializedValue(thing, data);
  222. serializedData = data;
  223. } else {
  224. serializedData = this._serializeLazy(thing, context);
  225. flush();
  226. buffers.push(serializedData);
  227. break;
  228. }
  229. } else {
  230. if (typeof serializedData === "function") {
  231. flush();
  232. buffers.push(serializedData);
  233. break;
  234. }
  235. }
  236. const lengths = [];
  237. for (const item of serializedData) {
  238. let last;
  239. if (typeof item === "function") {
  240. lengths.push(0);
  241. } else if (item.length === 0) {
  242. // ignore
  243. } else if (
  244. lengths.length > 0 &&
  245. (last = lengths[lengths.length - 1]) !== 0
  246. ) {
  247. const remaining = 0xffffffff - last;
  248. if (remaining >= item.length) {
  249. lengths[lengths.length - 1] += item.length;
  250. } else {
  251. lengths.push(item.length - remaining);
  252. lengths[lengths.length - 2] = 0xffffffff;
  253. }
  254. } else {
  255. lengths.push(item.length);
  256. }
  257. }
  258. allocate(5 + lengths.length * 4);
  259. writeU8(LAZY_HEADER);
  260. writeU32(lengths.length);
  261. for (const l of lengths) {
  262. writeU32(l);
  263. }
  264. flush();
  265. for (const item of serializedData) {
  266. buffers.push(item);
  267. }
  268. break;
  269. }
  270. case "string": {
  271. const len = Buffer.byteLength(thing);
  272. if (len >= 128 || len !== thing.length) {
  273. allocate(len + HEADER_SIZE + I32_SIZE);
  274. writeU8(STRING_HEADER);
  275. writeU32(len);
  276. currentBuffer.write(thing, currentPosition);
  277. currentPosition += len;
  278. } else if (len >= 70) {
  279. allocate(len + HEADER_SIZE);
  280. writeU8(SHORT_STRING_HEADER | len);
  281. currentBuffer.write(thing, currentPosition, "latin1");
  282. currentPosition += len;
  283. } else {
  284. allocate(len + HEADER_SIZE);
  285. writeU8(SHORT_STRING_HEADER | len);
  286. for (let i = 0; i < len; i++) {
  287. currentBuffer[currentPosition++] = thing.charCodeAt(i);
  288. }
  289. }
  290. break;
  291. }
  292. case "number": {
  293. const type = identifyNumber(thing);
  294. if (type === 0 && thing >= 0 && thing <= 10) {
  295. // shortcut for very small numbers
  296. allocate(I8_SIZE);
  297. writeU8(thing);
  298. break;
  299. }
  300. /**
  301. * amount of numbers to write
  302. * @type {number}
  303. */
  304. let n = 1;
  305. for (; n < 32 && i + n < data.length; n++) {
  306. const item = data[i + n];
  307. if (typeof item !== "number") break;
  308. if (identifyNumber(item) !== type) break;
  309. }
  310. switch (type) {
  311. case 0:
  312. allocate(HEADER_SIZE + I8_SIZE * n);
  313. writeU8(I8_HEADER | (n - 1));
  314. while (n > 0) {
  315. currentBuffer.writeInt8(
  316. /** @type {number} */ (data[i]),
  317. currentPosition
  318. );
  319. currentPosition += I8_SIZE;
  320. n--;
  321. i++;
  322. }
  323. break;
  324. case 1:
  325. allocate(HEADER_SIZE + I32_SIZE * n);
  326. writeU8(I32_HEADER | (n - 1));
  327. while (n > 0) {
  328. currentBuffer.writeInt32LE(
  329. /** @type {number} */ (data[i]),
  330. currentPosition
  331. );
  332. currentPosition += I32_SIZE;
  333. n--;
  334. i++;
  335. }
  336. break;
  337. case 2:
  338. allocate(HEADER_SIZE + F64_SIZE * n);
  339. writeU8(F64_HEADER | (n - 1));
  340. while (n > 0) {
  341. currentBuffer.writeDoubleLE(
  342. /** @type {number} */ (data[i]),
  343. currentPosition
  344. );
  345. currentPosition += F64_SIZE;
  346. n--;
  347. i++;
  348. }
  349. break;
  350. }
  351. i--;
  352. break;
  353. }
  354. case "boolean": {
  355. let lastByte = thing === true ? 1 : 0;
  356. const bytes = [];
  357. let count = 1;
  358. let n;
  359. for (n = 1; n < 0xffffffff && i + n < data.length; n++) {
  360. const item = data[i + n];
  361. if (typeof item !== "boolean") break;
  362. const pos = count & 0x7;
  363. if (pos === 0) {
  364. bytes.push(lastByte);
  365. lastByte = item === true ? 1 : 0;
  366. } else if (item === true) {
  367. lastByte |= 1 << pos;
  368. }
  369. count++;
  370. }
  371. i += count - 1;
  372. if (count === 1) {
  373. allocate(HEADER_SIZE);
  374. writeU8(lastByte === 1 ? TRUE_HEADER : FALSE_HEADER);
  375. } else if (count === 2) {
  376. allocate(HEADER_SIZE * 2);
  377. writeU8(lastByte & 1 ? TRUE_HEADER : FALSE_HEADER);
  378. writeU8(lastByte & 2 ? TRUE_HEADER : FALSE_HEADER);
  379. } else if (count <= 6) {
  380. allocate(HEADER_SIZE + I8_SIZE);
  381. writeU8(BOOLEANS_HEADER);
  382. writeU8((1 << count) | lastByte);
  383. } else if (count <= 133) {
  384. allocate(HEADER_SIZE + I8_SIZE + I8_SIZE * bytes.length + I8_SIZE);
  385. writeU8(BOOLEANS_HEADER);
  386. writeU8(0x80 | (count - 7));
  387. for (const byte of bytes) writeU8(byte);
  388. writeU8(lastByte);
  389. } else {
  390. allocate(
  391. HEADER_SIZE +
  392. I8_SIZE +
  393. I32_SIZE +
  394. I8_SIZE * bytes.length +
  395. I8_SIZE
  396. );
  397. writeU8(BOOLEANS_HEADER);
  398. writeU8(0xff);
  399. writeU32(count);
  400. for (const byte of bytes) writeU8(byte);
  401. writeU8(lastByte);
  402. }
  403. break;
  404. }
  405. case "object": {
  406. if (thing === null) {
  407. let n;
  408. for (n = 1; n < 0x100000104 && i + n < data.length; n++) {
  409. const item = data[i + n];
  410. if (item !== null) break;
  411. }
  412. i += n - 1;
  413. if (n === 1) {
  414. if (i + 1 < data.length) {
  415. const next = data[i + 1];
  416. if (next === true) {
  417. allocate(HEADER_SIZE);
  418. writeU8(NULL_AND_TRUE_HEADER);
  419. i++;
  420. } else if (next === false) {
  421. allocate(HEADER_SIZE);
  422. writeU8(NULL_AND_FALSE_HEADER);
  423. i++;
  424. } else if (typeof next === "number") {
  425. const type = identifyNumber(next);
  426. if (type === 0) {
  427. allocate(HEADER_SIZE + I8_SIZE);
  428. writeU8(NULL_AND_I8_HEADER);
  429. currentBuffer.writeInt8(next, currentPosition);
  430. currentPosition += I8_SIZE;
  431. i++;
  432. } else if (type === 1) {
  433. allocate(HEADER_SIZE + I32_SIZE);
  434. writeU8(NULL_AND_I32_HEADER);
  435. currentBuffer.writeInt32LE(next, currentPosition);
  436. currentPosition += I32_SIZE;
  437. i++;
  438. } else {
  439. allocate(HEADER_SIZE);
  440. writeU8(NULL_HEADER);
  441. }
  442. } else {
  443. allocate(HEADER_SIZE);
  444. writeU8(NULL_HEADER);
  445. }
  446. } else {
  447. allocate(HEADER_SIZE);
  448. writeU8(NULL_HEADER);
  449. }
  450. } else if (n === 2) {
  451. allocate(HEADER_SIZE);
  452. writeU8(NULL2_HEADER);
  453. } else if (n === 3) {
  454. allocate(HEADER_SIZE);
  455. writeU8(NULL3_HEADER);
  456. } else if (n < 260) {
  457. allocate(HEADER_SIZE + I8_SIZE);
  458. writeU8(NULLS8_HEADER);
  459. writeU8(n - 4);
  460. } else {
  461. allocate(HEADER_SIZE + I32_SIZE);
  462. writeU8(NULLS32_HEADER);
  463. writeU32(n - 260);
  464. }
  465. } else if (Buffer.isBuffer(thing)) {
  466. if (thing.length < 8192) {
  467. allocate(HEADER_SIZE + I32_SIZE + thing.length);
  468. writeU8(BUFFER_HEADER);
  469. writeU32(thing.length);
  470. thing.copy(currentBuffer, currentPosition);
  471. currentPosition += thing.length;
  472. } else {
  473. allocate(HEADER_SIZE + I32_SIZE);
  474. writeU8(BUFFER_HEADER);
  475. writeU32(thing.length);
  476. flush();
  477. buffers.push(thing);
  478. }
  479. }
  480. break;
  481. }
  482. case "symbol": {
  483. if (thing === MEASURE_START_OPERATION) {
  484. measureStart();
  485. } else if (thing === MEASURE_END_OPERATION) {
  486. const size = measureEnd();
  487. allocate(HEADER_SIZE + I32_SIZE);
  488. writeU8(I32_HEADER);
  489. currentBuffer.writeInt32LE(size, currentPosition);
  490. currentPosition += I32_SIZE;
  491. }
  492. break;
  493. }
  494. }
  495. }
  496. flush();
  497. allocationScope.leftOverBuffer = leftOverBuffer;
  498. // avoid leaking memory
  499. currentBuffer = null;
  500. leftOverBuffer = null;
  501. allocationScope = undefined;
  502. const _buffers = buffers;
  503. buffers = undefined;
  504. return _buffers;
  505. }
  506. /**
  507. * @param {SerializedType} data data
  508. * @param {Object} context context object
  509. * @returns {DeserializedType|Promise<DeserializedType>} deserialized data
  510. */
  511. deserialize(data, context) {
  512. return this._deserialize(data, context);
  513. }
  514. _createLazyDeserialized(content, context) {
  515. return SerializerMiddleware.createLazy(
  516. memoize(() => this._deserialize(content, context)),
  517. this,
  518. undefined,
  519. content
  520. );
  521. }
  522. _deserializeLazy(fn, context) {
  523. return SerializerMiddleware.deserializeLazy(fn, data =>
  524. this._deserialize(data, context)
  525. );
  526. }
  527. /**
  528. * @param {SerializedType} data data
  529. * @param {Object} context context object
  530. * @returns {DeserializedType} deserialized data
  531. */
  532. _deserialize(data, context) {
  533. let currentDataItem = 0;
  534. let currentBuffer = data[0];
  535. let currentIsBuffer = Buffer.isBuffer(currentBuffer);
  536. let currentPosition = 0;
  537. const retainedBuffer = context.retainedBuffer || (x => x);
  538. const checkOverflow = () => {
  539. if (currentPosition >= currentBuffer.length) {
  540. currentPosition = 0;
  541. currentDataItem++;
  542. currentBuffer =
  543. currentDataItem < data.length ? data[currentDataItem] : null;
  544. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  545. }
  546. };
  547. const isInCurrentBuffer = n => {
  548. return currentIsBuffer && n + currentPosition <= currentBuffer.length;
  549. };
  550. const ensureBuffer = () => {
  551. if (!currentIsBuffer) {
  552. throw new Error(
  553. currentBuffer === null
  554. ? "Unexpected end of stream"
  555. : "Unexpected lazy element in stream"
  556. );
  557. }
  558. };
  559. /**
  560. * Reads n bytes
  561. * @param {number} n amount of bytes to read
  562. * @returns {Buffer} buffer with bytes
  563. */
  564. const read = n => {
  565. ensureBuffer();
  566. const rem = currentBuffer.length - currentPosition;
  567. if (rem < n) {
  568. const buffers = [read(rem)];
  569. n -= rem;
  570. ensureBuffer();
  571. while (currentBuffer.length < n) {
  572. const b = /** @type {Buffer} */ (currentBuffer);
  573. buffers.push(b);
  574. n -= b.length;
  575. currentDataItem++;
  576. currentBuffer =
  577. currentDataItem < data.length ? data[currentDataItem] : null;
  578. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  579. ensureBuffer();
  580. }
  581. buffers.push(read(n));
  582. return Buffer.concat(buffers);
  583. }
  584. const b = /** @type {Buffer} */ (currentBuffer);
  585. const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
  586. currentPosition += n;
  587. checkOverflow();
  588. return res;
  589. };
  590. /**
  591. * Reads up to n bytes
  592. * @param {number} n amount of bytes to read
  593. * @returns {Buffer} buffer with bytes
  594. */
  595. const readUpTo = n => {
  596. ensureBuffer();
  597. const rem = currentBuffer.length - currentPosition;
  598. if (rem < n) {
  599. n = rem;
  600. }
  601. const b = /** @type {Buffer} */ (currentBuffer);
  602. const res = Buffer.from(b.buffer, b.byteOffset + currentPosition, n);
  603. currentPosition += n;
  604. checkOverflow();
  605. return res;
  606. };
  607. const readU8 = () => {
  608. ensureBuffer();
  609. /**
  610. * There is no need to check remaining buffer size here
  611. * since {@link checkOverflow} guarantees at least one byte remaining
  612. */
  613. const byte = /** @type {Buffer} */ (currentBuffer).readUInt8(
  614. currentPosition
  615. );
  616. currentPosition += I8_SIZE;
  617. checkOverflow();
  618. return byte;
  619. };
  620. const readU32 = () => {
  621. return read(I32_SIZE).readUInt32LE(0);
  622. };
  623. const readBits = (data, n) => {
  624. let mask = 1;
  625. while (n !== 0) {
  626. result.push((data & mask) !== 0);
  627. mask = mask << 1;
  628. n--;
  629. }
  630. };
  631. const dispatchTable = Array.from({ length: 256 }).map((_, header) => {
  632. switch (header) {
  633. case LAZY_HEADER:
  634. return () => {
  635. const count = readU32();
  636. const lengths = Array.from({ length: count }).map(() => readU32());
  637. const content = [];
  638. for (let l of lengths) {
  639. if (l === 0) {
  640. if (typeof currentBuffer !== "function") {
  641. throw new Error("Unexpected non-lazy element in stream");
  642. }
  643. content.push(currentBuffer);
  644. currentDataItem++;
  645. currentBuffer =
  646. currentDataItem < data.length ? data[currentDataItem] : null;
  647. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  648. } else {
  649. do {
  650. const buf = readUpTo(l);
  651. l -= buf.length;
  652. content.push(retainedBuffer(buf));
  653. } while (l > 0);
  654. }
  655. }
  656. result.push(this._createLazyDeserialized(content, context));
  657. };
  658. case BUFFER_HEADER:
  659. return () => {
  660. const len = readU32();
  661. result.push(retainedBuffer(read(len)));
  662. };
  663. case TRUE_HEADER:
  664. return () => result.push(true);
  665. case FALSE_HEADER:
  666. return () => result.push(false);
  667. case NULL3_HEADER:
  668. return () => result.push(null, null, null);
  669. case NULL2_HEADER:
  670. return () => result.push(null, null);
  671. case NULL_HEADER:
  672. return () => result.push(null);
  673. case NULL_AND_TRUE_HEADER:
  674. return () => result.push(null, true);
  675. case NULL_AND_FALSE_HEADER:
  676. return () => result.push(null, false);
  677. case NULL_AND_I8_HEADER:
  678. return () => {
  679. if (currentIsBuffer) {
  680. result.push(
  681. null,
  682. /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
  683. );
  684. currentPosition += I8_SIZE;
  685. checkOverflow();
  686. } else {
  687. result.push(null, read(I8_SIZE).readInt8(0));
  688. }
  689. };
  690. case NULL_AND_I32_HEADER:
  691. return () => {
  692. result.push(null);
  693. if (isInCurrentBuffer(I32_SIZE)) {
  694. result.push(
  695. /** @type {Buffer} */ (currentBuffer).readInt32LE(
  696. currentPosition
  697. )
  698. );
  699. currentPosition += I32_SIZE;
  700. checkOverflow();
  701. } else {
  702. result.push(read(I32_SIZE).readInt32LE(0));
  703. }
  704. };
  705. case NULLS8_HEADER:
  706. return () => {
  707. const len = readU8() + 4;
  708. for (let i = 0; i < len; i++) {
  709. result.push(null);
  710. }
  711. };
  712. case NULLS32_HEADER:
  713. return () => {
  714. const len = readU32() + 260;
  715. for (let i = 0; i < len; i++) {
  716. result.push(null);
  717. }
  718. };
  719. case BOOLEANS_HEADER:
  720. return () => {
  721. const innerHeader = readU8();
  722. if ((innerHeader & 0xf0) === 0) {
  723. readBits(innerHeader, 3);
  724. } else if ((innerHeader & 0xe0) === 0) {
  725. readBits(innerHeader, 4);
  726. } else if ((innerHeader & 0xc0) === 0) {
  727. readBits(innerHeader, 5);
  728. } else if ((innerHeader & 0x80) === 0) {
  729. readBits(innerHeader, 6);
  730. } else if (innerHeader !== 0xff) {
  731. let count = (innerHeader & 0x7f) + 7;
  732. while (count > 8) {
  733. readBits(readU8(), 8);
  734. count -= 8;
  735. }
  736. readBits(readU8(), count);
  737. } else {
  738. let count = readU32();
  739. while (count > 8) {
  740. readBits(readU8(), 8);
  741. count -= 8;
  742. }
  743. readBits(readU8(), count);
  744. }
  745. };
  746. case STRING_HEADER:
  747. return () => {
  748. const len = readU32();
  749. if (isInCurrentBuffer(len) && currentPosition + len < 0x7fffffff) {
  750. result.push(
  751. currentBuffer.toString(
  752. undefined,
  753. currentPosition,
  754. currentPosition + len
  755. )
  756. );
  757. currentPosition += len;
  758. checkOverflow();
  759. } else {
  760. result.push(read(len).toString());
  761. }
  762. };
  763. case SHORT_STRING_HEADER:
  764. return () => result.push("");
  765. case SHORT_STRING_HEADER | 1:
  766. return () => {
  767. if (currentIsBuffer && currentPosition < 0x7ffffffe) {
  768. result.push(
  769. currentBuffer.toString(
  770. "latin1",
  771. currentPosition,
  772. currentPosition + 1
  773. )
  774. );
  775. currentPosition++;
  776. checkOverflow();
  777. } else {
  778. result.push(read(1).toString("latin1"));
  779. }
  780. };
  781. case I8_HEADER:
  782. return () => {
  783. if (currentIsBuffer) {
  784. result.push(
  785. /** @type {Buffer} */ (currentBuffer).readInt8(currentPosition)
  786. );
  787. currentPosition++;
  788. checkOverflow();
  789. } else {
  790. result.push(read(1).readInt8(0));
  791. }
  792. };
  793. default:
  794. if (header <= 10) {
  795. return () => result.push(header);
  796. } else if ((header & SHORT_STRING_HEADER) === SHORT_STRING_HEADER) {
  797. const len = header & SHORT_STRING_LENGTH_MASK;
  798. return () => {
  799. if (
  800. isInCurrentBuffer(len) &&
  801. currentPosition + len < 0x7fffffff
  802. ) {
  803. result.push(
  804. currentBuffer.toString(
  805. "latin1",
  806. currentPosition,
  807. currentPosition + len
  808. )
  809. );
  810. currentPosition += len;
  811. checkOverflow();
  812. } else {
  813. result.push(read(len).toString("latin1"));
  814. }
  815. };
  816. } else if ((header & NUMBERS_HEADER_MASK) === F64_HEADER) {
  817. const len = (header & NUMBERS_COUNT_MASK) + 1;
  818. return () => {
  819. const need = F64_SIZE * len;
  820. if (isInCurrentBuffer(need)) {
  821. for (let i = 0; i < len; i++) {
  822. result.push(
  823. /** @type {Buffer} */ (currentBuffer).readDoubleLE(
  824. currentPosition
  825. )
  826. );
  827. currentPosition += F64_SIZE;
  828. }
  829. checkOverflow();
  830. } else {
  831. const buf = read(need);
  832. for (let i = 0; i < len; i++) {
  833. result.push(buf.readDoubleLE(i * F64_SIZE));
  834. }
  835. }
  836. };
  837. } else if ((header & NUMBERS_HEADER_MASK) === I32_HEADER) {
  838. const len = (header & NUMBERS_COUNT_MASK) + 1;
  839. return () => {
  840. const need = I32_SIZE * len;
  841. if (isInCurrentBuffer(need)) {
  842. for (let i = 0; i < len; i++) {
  843. result.push(
  844. /** @type {Buffer} */ (currentBuffer).readInt32LE(
  845. currentPosition
  846. )
  847. );
  848. currentPosition += I32_SIZE;
  849. }
  850. checkOverflow();
  851. } else {
  852. const buf = read(need);
  853. for (let i = 0; i < len; i++) {
  854. result.push(buf.readInt32LE(i * I32_SIZE));
  855. }
  856. }
  857. };
  858. } else if ((header & NUMBERS_HEADER_MASK) === I8_HEADER) {
  859. const len = (header & NUMBERS_COUNT_MASK) + 1;
  860. return () => {
  861. const need = I8_SIZE * len;
  862. if (isInCurrentBuffer(need)) {
  863. for (let i = 0; i < len; i++) {
  864. result.push(
  865. /** @type {Buffer} */ (currentBuffer).readInt8(
  866. currentPosition
  867. )
  868. );
  869. currentPosition += I8_SIZE;
  870. }
  871. checkOverflow();
  872. } else {
  873. const buf = read(need);
  874. for (let i = 0; i < len; i++) {
  875. result.push(buf.readInt8(i * I8_SIZE));
  876. }
  877. }
  878. };
  879. } else {
  880. return () => {
  881. throw new Error(
  882. `Unexpected header byte 0x${header.toString(16)}`
  883. );
  884. };
  885. }
  886. }
  887. });
  888. /** @type {DeserializedType} */
  889. let result = [];
  890. while (currentBuffer !== null) {
  891. if (typeof currentBuffer === "function") {
  892. result.push(this._deserializeLazy(currentBuffer, context));
  893. currentDataItem++;
  894. currentBuffer =
  895. currentDataItem < data.length ? data[currentDataItem] : null;
  896. currentIsBuffer = Buffer.isBuffer(currentBuffer);
  897. } else {
  898. const header = readU8();
  899. dispatchTable[header]();
  900. }
  901. }
  902. // avoid leaking memory in context
  903. let _result = result;
  904. result = undefined;
  905. return _result;
  906. }
  907. }
  908. module.exports = BinaryMiddleware;
  909. module.exports.MEASURE_START_OPERATION = MEASURE_START_OPERATION;
  910. module.exports.MEASURE_END_OPERATION = MEASURE_END_OPERATION;