packet.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. 'use strict';
  2. const ErrorCodeToName = require('../constants/errors.js');
  3. const NativeBuffer = require('buffer').Buffer;
  4. const Long = require('long');
  5. const StringParser = require('../parsers/string.js');
  6. const INVALID_DATE = new Date(NaN);
  7. // this is nearly duplicate of previous function so generated code is not slower
  8. // due to "if (dateStrings)" branching
  9. const pad = '000000000000';
  10. function leftPad(num, value) {
  11. const s = value.toString();
  12. // if we don't need to pad
  13. if (s.length >= num) {
  14. return s;
  15. }
  16. return (pad + s).slice(-num);
  17. }
  18. // The whole reason parse* function below exist
  19. // is because String creation is relatively expensive (at least with V8), and if we have
  20. // a buffer with "12345" content ideally we would like to bypass intermediate
  21. // "12345" string creation and directly build 12345 number out of
  22. // <Buffer 31 32 33 34 35> data.
  23. // In my benchmarks the difference is ~25M 8-digit numbers per second vs
  24. // 4.5 M using Number(packet.readLengthCodedString())
  25. // not used when size is close to max precision as series of *10 accumulate error
  26. // and approximate result mihgt be diffreent from (approximate as well) Number(bigNumStringValue))
  27. // In the futire node version if speed difference is smaller parse* functions might be removed
  28. // don't consider them as Packet public API
  29. const minus = '-'.charCodeAt(0);
  30. const plus = '+'.charCodeAt(0);
  31. // TODO: handle E notation
  32. const dot = '.'.charCodeAt(0);
  33. const exponent = 'e'.charCodeAt(0);
  34. const exponentCapital = 'E'.charCodeAt(0);
  35. class Packet {
  36. constructor(id, buffer, start, end) {
  37. // hot path, enable checks when testing only
  38. // if (!Buffer.isBuffer(buffer) || typeof start == 'undefined' || typeof end == 'undefined')
  39. // throw new Error('invalid packet');
  40. this.sequenceId = id;
  41. this.numPackets = 1;
  42. this.buffer = buffer;
  43. this.start = start;
  44. this.offset = start + 4;
  45. this.end = end;
  46. }
  47. // ==============================
  48. // readers
  49. // ==============================
  50. reset() {
  51. this.offset = this.start + 4;
  52. }
  53. length() {
  54. return this.end - this.start;
  55. }
  56. slice() {
  57. return this.buffer.slice(this.start, this.end);
  58. }
  59. dump() {
  60. // eslint-disable-next-line no-console
  61. console.log(
  62. [this.buffer.asciiSlice(this.start, this.end)],
  63. this.buffer.slice(this.start, this.end),
  64. this.length(),
  65. this.sequenceId
  66. );
  67. }
  68. haveMoreData() {
  69. return this.end > this.offset;
  70. }
  71. skip(num) {
  72. this.offset += num;
  73. }
  74. readInt8() {
  75. return this.buffer[this.offset++];
  76. }
  77. readInt16() {
  78. this.offset += 2;
  79. return this.buffer.readUInt16LE(this.offset - 2);
  80. }
  81. readInt24() {
  82. return this.readInt16() + (this.readInt8() << 16);
  83. }
  84. readInt32() {
  85. this.offset += 4;
  86. return this.buffer.readUInt32LE(this.offset - 4);
  87. }
  88. readSInt8() {
  89. return this.buffer.readInt8(this.offset++);
  90. }
  91. readSInt16() {
  92. this.offset += 2;
  93. return this.buffer.readInt16LE(this.offset - 2);
  94. }
  95. readSInt32() {
  96. this.offset += 4;
  97. return this.buffer.readInt32LE(this.offset - 4);
  98. }
  99. readInt64JSNumber() {
  100. const word0 = this.readInt32();
  101. const word1 = this.readInt32();
  102. const l = new Long(word0, word1, true);
  103. return l.toNumber();
  104. }
  105. readSInt64JSNumber() {
  106. const word0 = this.readInt32();
  107. const word1 = this.readInt32();
  108. if (!(word1 & 0x80000000)) {
  109. return word0 + 0x100000000 * word1;
  110. }
  111. const l = new Long(word0, word1, false);
  112. return l.toNumber();
  113. }
  114. readInt64String() {
  115. const word0 = this.readInt32();
  116. const word1 = this.readInt32();
  117. const res = new Long(word0, word1, true);
  118. return res.toString();
  119. }
  120. readSInt64String() {
  121. const word0 = this.readInt32();
  122. const word1 = this.readInt32();
  123. const res = new Long(word0, word1, false);
  124. return res.toString();
  125. }
  126. readInt64() {
  127. const word0 = this.readInt32();
  128. const word1 = this.readInt32();
  129. let res = new Long(word0, word1, true);
  130. const resNumber = res.toNumber();
  131. const resString = res.toString();
  132. res = resNumber.toString() === resString ? resNumber : resString;
  133. return res;
  134. }
  135. readSInt64() {
  136. const word0 = this.readInt32();
  137. const word1 = this.readInt32();
  138. let res = new Long(word0, word1, false);
  139. const resNumber = res.toNumber();
  140. const resString = res.toString();
  141. res = resNumber.toString() === resString ? resNumber : resString;
  142. return res;
  143. }
  144. isEOF() {
  145. return this.buffer[this.offset] === 0xfe && this.length() < 13;
  146. }
  147. eofStatusFlags() {
  148. return this.buffer.readInt16LE(this.offset + 3);
  149. }
  150. eofWarningCount() {
  151. return this.buffer.readInt16LE(this.offset + 1);
  152. }
  153. readLengthCodedNumber(bigNumberStrings, signed) {
  154. const byte1 = this.buffer[this.offset++];
  155. if (byte1 < 251) {
  156. return byte1;
  157. }
  158. return this.readLengthCodedNumberExt(byte1, bigNumberStrings, signed);
  159. }
  160. readLengthCodedNumberSigned(bigNumberStrings) {
  161. return this.readLengthCodedNumber(bigNumberStrings, true);
  162. }
  163. readLengthCodedNumberExt(tag, bigNumberStrings, signed) {
  164. let word0, word1;
  165. let res;
  166. if (tag === 0xfb) {
  167. return null;
  168. }
  169. if (tag === 0xfc) {
  170. return this.readInt8() + (this.readInt8() << 8);
  171. }
  172. if (tag === 0xfd) {
  173. return this.readInt8() + (this.readInt8() << 8) + (this.readInt8() << 16);
  174. }
  175. if (tag === 0xfe) {
  176. // TODO: check version
  177. // Up to MySQL 3.22, 0xfe was followed by a 4-byte integer.
  178. word0 = this.readInt32();
  179. word1 = this.readInt32();
  180. if (word1 === 0) {
  181. return word0; // don't convert to float if possible
  182. }
  183. if (word1 < 2097152) {
  184. // max exact float point int, 2^52 / 2^32
  185. return word1 * 0x100000000 + word0;
  186. }
  187. res = new Long(word0, word1, !signed); // Long need unsigned
  188. const resNumber = res.toNumber();
  189. const resString = res.toString();
  190. res = resNumber.toString() === resString ? resNumber : resString;
  191. return bigNumberStrings ? resString : res;
  192. }
  193. // eslint-disable-next-line no-console
  194. console.trace();
  195. throw new Error(`Should not reach here: ${tag}`);
  196. }
  197. readFloat() {
  198. const res = this.buffer.readFloatLE(this.offset);
  199. this.offset += 4;
  200. return res;
  201. }
  202. readDouble() {
  203. const res = this.buffer.readDoubleLE(this.offset);
  204. this.offset += 8;
  205. return res;
  206. }
  207. readBuffer(len) {
  208. if (typeof len === 'undefined') {
  209. len = this.end - this.offset;
  210. }
  211. this.offset += len;
  212. return this.buffer.slice(this.offset - len, this.offset);
  213. }
  214. // DATE, DATETIME and TIMESTAMP
  215. readDateTime(timezone) {
  216. if (!timezone || timezone === 'Z' || timezone === 'local') {
  217. const length = this.readInt8();
  218. if (length === 0xfb) {
  219. return null;
  220. }
  221. let y = 0;
  222. let m = 0;
  223. let d = 0;
  224. let H = 0;
  225. let M = 0;
  226. let S = 0;
  227. let ms = 0;
  228. if (length > 3) {
  229. y = this.readInt16();
  230. m = this.readInt8();
  231. d = this.readInt8();
  232. }
  233. if (length > 6) {
  234. H = this.readInt8();
  235. M = this.readInt8();
  236. S = this.readInt8();
  237. }
  238. if (length > 10) {
  239. ms = this.readInt32() / 1000;
  240. }
  241. if (y + m + d + H + M + S + ms === 0) {
  242. return INVALID_DATE;
  243. }
  244. if (timezone === 'Z') {
  245. return new Date(Date.UTC(y, m - 1, d, H, M, S, ms));
  246. }
  247. return new Date(y, m - 1, d, H, M, S, ms);
  248. }
  249. let str = this.readDateTimeString(6, 'T');
  250. if (str.length === 10) {
  251. str += 'T00:00:00';
  252. }
  253. return new Date(str + timezone);
  254. }
  255. readDateTimeString(decimals, timeSep) {
  256. const length = this.readInt8();
  257. let y = 0;
  258. let m = 0;
  259. let d = 0;
  260. let H = 0;
  261. let M = 0;
  262. let S = 0;
  263. let ms = 0;
  264. let str;
  265. if (length > 3) {
  266. y = this.readInt16();
  267. m = this.readInt8();
  268. d = this.readInt8();
  269. str = [leftPad(4, y), leftPad(2, m), leftPad(2, d)].join('-');
  270. }
  271. if (length > 6) {
  272. H = this.readInt8();
  273. M = this.readInt8();
  274. S = this.readInt8();
  275. str += `${timeSep || ' '}${[
  276. leftPad(2, H),
  277. leftPad(2, M),
  278. leftPad(2, S)
  279. ].join(':')}`;
  280. }
  281. if (length > 10) {
  282. ms = this.readInt32();
  283. str += '.';
  284. if (decimals) {
  285. ms = leftPad(6, ms);
  286. if (ms.length > decimals) {
  287. ms = ms.substring(0, decimals); // rounding is done at the MySQL side, only 0 are here
  288. }
  289. }
  290. str += ms;
  291. }
  292. return str;
  293. }
  294. // TIME - value as a string, Can be negative
  295. readTimeString(convertTtoMs) {
  296. const length = this.readInt8();
  297. if (length === 0) {
  298. return '00:00:00';
  299. }
  300. const sign = this.readInt8() ? -1 : 1; // 'isNegative' flag byte
  301. let d = 0;
  302. let H = 0;
  303. let M = 0;
  304. let S = 0;
  305. let ms = 0;
  306. if (length > 6) {
  307. d = this.readInt32();
  308. H = this.readInt8();
  309. M = this.readInt8();
  310. S = this.readInt8();
  311. }
  312. if (length > 10) {
  313. ms = this.readInt32();
  314. }
  315. if (convertTtoMs) {
  316. H += d * 24;
  317. M += H * 60;
  318. S += M * 60;
  319. ms += S * 1000;
  320. ms *= sign;
  321. return ms;
  322. }
  323. return (
  324. (sign === -1 ? '-' : '') +
  325. [d ? d * 24 + H : H, leftPad(2, M), leftPad(2, S)].join(':') +
  326. (ms ? `.${ms}` : '')
  327. );
  328. }
  329. readLengthCodedString(encoding) {
  330. const len = this.readLengthCodedNumber();
  331. // TODO: check manually first byte here to avoid polymorphic return type?
  332. if (len === null) {
  333. return null;
  334. }
  335. this.offset += len;
  336. // TODO: Use characterSetCode to get proper encoding
  337. // https://github.com/sidorares/node-mysql2/pull/374
  338. return StringParser.decode(
  339. this.buffer.slice(this.offset - len, this.offset),
  340. encoding
  341. );
  342. }
  343. readLengthCodedBuffer() {
  344. const len = this.readLengthCodedNumber();
  345. if (len === null) {
  346. return null;
  347. }
  348. return this.readBuffer(len);
  349. }
  350. readNullTerminatedString(encoding) {
  351. const start = this.offset;
  352. let end = this.offset;
  353. while (this.buffer[end]) {
  354. end = end + 1; // TODO: handle OOB check
  355. }
  356. this.offset = end + 1;
  357. return StringParser.decode(this.buffer.slice(start, end), encoding);
  358. }
  359. // TODO reuse?
  360. readString(len, encoding) {
  361. if ((typeof len === 'string') && (typeof encoding === 'undefined')) {
  362. encoding = len
  363. len = undefined
  364. }
  365. if (typeof len === 'undefined') {
  366. len = this.end - this.offset;
  367. }
  368. this.offset += len;
  369. return StringParser.decode(
  370. this.buffer.slice(this.offset - len, this.offset),
  371. encoding
  372. );
  373. }
  374. parseInt(len, supportBigNumbers) {
  375. if (len === null) {
  376. return null;
  377. }
  378. if (len >= 14 && !supportBigNumbers) {
  379. const s = this.buffer.toString('ascii', this.offset, this.offset + len);
  380. this.offset += len;
  381. return Number(s);
  382. }
  383. let result = 0;
  384. const start = this.offset;
  385. const end = this.offset + len;
  386. let sign = 1;
  387. if (len === 0) {
  388. return 0; // TODO: assert? exception?
  389. }
  390. if (this.buffer[this.offset] === minus) {
  391. this.offset++;
  392. sign = -1;
  393. }
  394. // max precise int is 9007199254740992
  395. let str;
  396. const numDigits = end - this.offset;
  397. if (supportBigNumbers) {
  398. if (numDigits >= 15) {
  399. str = this.readString(end - this.offset, 'binary');
  400. result = parseInt(str, 10);
  401. if (result.toString() === str) {
  402. return sign * result;
  403. }
  404. return sign === -1 ? `-${str}` : str;
  405. }
  406. if (numDigits > 16) {
  407. str = this.readString(end - this.offset);
  408. return sign === -1 ? `-${str}` : str;
  409. }
  410. }
  411. if (this.buffer[this.offset] === plus) {
  412. this.offset++; // just ignore
  413. }
  414. while (this.offset < end) {
  415. result *= 10;
  416. result += this.buffer[this.offset] - 48;
  417. this.offset++;
  418. }
  419. const num = result * sign;
  420. if (!supportBigNumbers) {
  421. return num;
  422. }
  423. str = this.buffer.toString('ascii', start, end);
  424. if (num.toString() === str) {
  425. return num;
  426. }
  427. return str;
  428. }
  429. // note that if value of inputNumberAsString is bigger than MAX_SAFE_INTEGER
  430. // ( or smaller than MIN_SAFE_INTEGER ) the parseIntNoBigCheck result might be
  431. // different from what you would get from Number(inputNumberAsString)
  432. // String(parseIntNoBigCheck) <> String(Number(inputNumberAsString)) <> inputNumberAsString
  433. parseIntNoBigCheck(len) {
  434. if (len === null) {
  435. return null;
  436. }
  437. let result = 0;
  438. const end = this.offset + len;
  439. let sign = 1;
  440. if (len === 0) {
  441. return 0; // TODO: assert? exception?
  442. }
  443. if (this.buffer[this.offset] === minus) {
  444. this.offset++;
  445. sign = -1;
  446. }
  447. if (this.buffer[this.offset] === plus) {
  448. this.offset++; // just ignore
  449. }
  450. while (this.offset < end) {
  451. result *= 10;
  452. result += this.buffer[this.offset] - 48;
  453. this.offset++;
  454. }
  455. return result * sign;
  456. }
  457. // copy-paste from https://github.com/mysqljs/mysql/blob/master/lib/protocol/Parser.js
  458. parseGeometryValue() {
  459. const buffer = this.readLengthCodedBuffer();
  460. let offset = 4;
  461. if (buffer === null || !buffer.length) {
  462. return null;
  463. }
  464. function parseGeometry() {
  465. let x, y, i, j, numPoints, line;
  466. let result = null;
  467. const byteOrder = buffer.readUInt8(offset);
  468. offset += 1;
  469. const wkbType = byteOrder
  470. ? buffer.readUInt32LE(offset)
  471. : buffer.readUInt32BE(offset);
  472. offset += 4;
  473. switch (wkbType) {
  474. case 1: // WKBPoint
  475. x = byteOrder
  476. ? buffer.readDoubleLE(offset)
  477. : buffer.readDoubleBE(offset);
  478. offset += 8;
  479. y = byteOrder
  480. ? buffer.readDoubleLE(offset)
  481. : buffer.readDoubleBE(offset);
  482. offset += 8;
  483. result = { x: x, y: y };
  484. break;
  485. case 2: // WKBLineString
  486. numPoints = byteOrder
  487. ? buffer.readUInt32LE(offset)
  488. : buffer.readUInt32BE(offset);
  489. offset += 4;
  490. result = [];
  491. for (i = numPoints; i > 0; i--) {
  492. x = byteOrder
  493. ? buffer.readDoubleLE(offset)
  494. : buffer.readDoubleBE(offset);
  495. offset += 8;
  496. y = byteOrder
  497. ? buffer.readDoubleLE(offset)
  498. : buffer.readDoubleBE(offset);
  499. offset += 8;
  500. result.push({ x: x, y: y });
  501. }
  502. break;
  503. case 3: // WKBPolygon
  504. // eslint-disable-next-line no-case-declarations
  505. const numRings = byteOrder
  506. ? buffer.readUInt32LE(offset)
  507. : buffer.readUInt32BE(offset);
  508. offset += 4;
  509. result = [];
  510. for (i = numRings; i > 0; i--) {
  511. numPoints = byteOrder
  512. ? buffer.readUInt32LE(offset)
  513. : buffer.readUInt32BE(offset);
  514. offset += 4;
  515. line = [];
  516. for (j = numPoints; j > 0; j--) {
  517. x = byteOrder
  518. ? buffer.readDoubleLE(offset)
  519. : buffer.readDoubleBE(offset);
  520. offset += 8;
  521. y = byteOrder
  522. ? buffer.readDoubleLE(offset)
  523. : buffer.readDoubleBE(offset);
  524. offset += 8;
  525. line.push({ x: x, y: y });
  526. }
  527. result.push(line);
  528. }
  529. break;
  530. case 4: // WKBMultiPoint
  531. case 5: // WKBMultiLineString
  532. case 6: // WKBMultiPolygon
  533. case 7: // WKBGeometryCollection
  534. // eslint-disable-next-line no-case-declarations
  535. const num = byteOrder
  536. ? buffer.readUInt32LE(offset)
  537. : buffer.readUInt32BE(offset);
  538. offset += 4;
  539. result = [];
  540. for (i = num; i > 0; i--) {
  541. result.push(parseGeometry());
  542. }
  543. break;
  544. }
  545. return result;
  546. }
  547. return parseGeometry();
  548. }
  549. parseDate(timezone) {
  550. const strLen = this.readLengthCodedNumber();
  551. if (strLen === null) {
  552. return null;
  553. }
  554. if (strLen !== 10) {
  555. // we expect only YYYY-MM-DD here.
  556. // if for some reason it's not the case return invalid date
  557. return new Date(NaN);
  558. }
  559. const y = this.parseInt(4);
  560. this.offset++; // -
  561. const m = this.parseInt(2);
  562. this.offset++; // -
  563. const d = this.parseInt(2);
  564. if (!timezone || timezone === 'local') {
  565. return new Date(y, m - 1, d);
  566. }
  567. if (timezone === 'Z') {
  568. return new Date(Date.UTC(y, m - 1, d));
  569. }
  570. return new Date(
  571. `${leftPad(4, y)}-${leftPad(2, m)}-${leftPad(2, d)}T00:00:00${timezone}`
  572. );
  573. }
  574. parseDateTime(timezone) {
  575. const str = this.readLengthCodedString('binary');
  576. if (str === null) {
  577. return null;
  578. }
  579. if (!timezone || timezone === 'local') {
  580. return new Date(str);
  581. }
  582. return new Date(`${str}${timezone}`);
  583. }
  584. parseFloat(len) {
  585. if (len === null) {
  586. return null;
  587. }
  588. let result = 0;
  589. const end = this.offset + len;
  590. let factor = 1;
  591. let pastDot = false;
  592. let charCode = 0;
  593. if (len === 0) {
  594. return 0; // TODO: assert? exception?
  595. }
  596. if (this.buffer[this.offset] === minus) {
  597. this.offset++;
  598. factor = -1;
  599. }
  600. if (this.buffer[this.offset] === plus) {
  601. this.offset++; // just ignore
  602. }
  603. while (this.offset < end) {
  604. charCode = this.buffer[this.offset];
  605. if (charCode === dot) {
  606. pastDot = true;
  607. this.offset++;
  608. } else if (charCode === exponent || charCode === exponentCapital) {
  609. this.offset++;
  610. const exponentValue = this.parseInt(end - this.offset);
  611. return (result / factor) * Math.pow(10, exponentValue);
  612. } else {
  613. result *= 10;
  614. result += this.buffer[this.offset] - 48;
  615. this.offset++;
  616. if (pastDot) {
  617. factor = factor * 10;
  618. }
  619. }
  620. }
  621. return result / factor;
  622. }
  623. parseLengthCodedIntNoBigCheck() {
  624. return this.parseIntNoBigCheck(this.readLengthCodedNumber());
  625. }
  626. parseLengthCodedInt(supportBigNumbers) {
  627. return this.parseInt(this.readLengthCodedNumber(), supportBigNumbers);
  628. }
  629. parseLengthCodedIntString() {
  630. return this.readLengthCodedString('binary');
  631. }
  632. parseLengthCodedFloat() {
  633. return this.parseFloat(this.readLengthCodedNumber());
  634. }
  635. peekByte() {
  636. return this.buffer[this.offset];
  637. }
  638. // OxFE is often used as "Alt" flag - not ok, not error.
  639. // For example, it's first byte of AuthSwitchRequest
  640. isAlt() {
  641. return this.peekByte() === 0xfe;
  642. }
  643. isError() {
  644. return this.peekByte() === 0xff;
  645. }
  646. asError(encoding) {
  647. this.reset();
  648. this.readInt8(); // fieldCount
  649. const errorCode = this.readInt16();
  650. let sqlState = '';
  651. if (this.buffer[this.offset] === 0x23) {
  652. this.skip(1);
  653. sqlState = this.readBuffer(5).toString();
  654. }
  655. const message = this.readString(undefined, encoding);
  656. const err = new Error(message);
  657. err.code = ErrorCodeToName[errorCode];
  658. err.errno = errorCode;
  659. err.sqlState = sqlState;
  660. err.sqlMessage = message;
  661. return err;
  662. }
  663. writeInt32(n) {
  664. this.buffer.writeUInt32LE(n, this.offset);
  665. this.offset += 4;
  666. }
  667. writeInt24(n) {
  668. this.writeInt8(n & 0xff);
  669. this.writeInt16(n >> 8);
  670. }
  671. writeInt16(n) {
  672. this.buffer.writeUInt16LE(n, this.offset);
  673. this.offset += 2;
  674. }
  675. writeInt8(n) {
  676. this.buffer.writeUInt8(n, this.offset);
  677. this.offset++;
  678. }
  679. writeDouble(n) {
  680. this.buffer.writeDoubleLE(n, this.offset);
  681. this.offset += 8;
  682. }
  683. writeBuffer(b) {
  684. b.copy(this.buffer, this.offset);
  685. this.offset += b.length;
  686. }
  687. writeNull() {
  688. this.buffer[this.offset] = 0xfb;
  689. this.offset++;
  690. }
  691. // TODO: refactor following three?
  692. writeNullTerminatedString(s, encoding) {
  693. const buf = StringParser.encode(s, encoding);
  694. this.buffer.length && buf.copy(this.buffer, this.offset);
  695. this.offset += buf.length;
  696. this.writeInt8(0);
  697. }
  698. writeString(s, encoding) {
  699. if (s === null) {
  700. this.writeInt8(0xfb);
  701. return;
  702. }
  703. if (s.length === 0) {
  704. return;
  705. }
  706. // const bytes = Buffer.byteLength(s, 'utf8');
  707. // this.buffer.write(s, this.offset, bytes, 'utf8');
  708. // this.offset += bytes;
  709. const buf = StringParser.encode(s, encoding);
  710. this.buffer.length && buf.copy(this.buffer, this.offset);
  711. this.offset += buf.length;
  712. }
  713. writeLengthCodedString(s, encoding) {
  714. const buf = StringParser.encode(s, encoding);
  715. this.writeLengthCodedNumber(buf.length);
  716. this.buffer.length && buf.copy(this.buffer, this.offset);
  717. this.offset += buf.length;
  718. }
  719. writeLengthCodedBuffer(b) {
  720. this.writeLengthCodedNumber(b.length);
  721. b.copy(this.buffer, this.offset);
  722. this.offset += b.length;
  723. }
  724. writeLengthCodedNumber(n) {
  725. if (n < 0xfb) {
  726. return this.writeInt8(n);
  727. }
  728. if (n < 0xffff) {
  729. this.writeInt8(0xfc);
  730. return this.writeInt16(n);
  731. }
  732. if (n < 0xffffff) {
  733. this.writeInt8(0xfd);
  734. return this.writeInt24(n);
  735. }
  736. if (n === null) {
  737. return this.writeInt8(0xfb);
  738. }
  739. // TODO: check that n is out of int precision
  740. this.writeInt8(0xfe);
  741. this.buffer.writeUInt32LE(n, this.offset);
  742. this.offset += 4;
  743. this.buffer.writeUInt32LE(n >> 32, this.offset);
  744. this.offset += 4;
  745. return this.offset;
  746. }
  747. writeDate(d, timezone) {
  748. this.buffer.writeUInt8(11, this.offset);
  749. if (!timezone || timezone === 'local') {
  750. this.buffer.writeUInt16LE(d.getFullYear(), this.offset + 1);
  751. this.buffer.writeUInt8(d.getMonth() + 1, this.offset + 3);
  752. this.buffer.writeUInt8(d.getDate(), this.offset + 4);
  753. this.buffer.writeUInt8(d.getHours(), this.offset + 5);
  754. this.buffer.writeUInt8(d.getMinutes(), this.offset + 6);
  755. this.buffer.writeUInt8(d.getSeconds(), this.offset + 7);
  756. this.buffer.writeUInt32LE(d.getMilliseconds() * 1000, this.offset + 8);
  757. } else {
  758. if (timezone !== 'Z') {
  759. const offset =
  760. (timezone[0] === '-' ? -1 : 1) *
  761. (parseInt(timezone.substring(1, 3), 10) * 60 +
  762. parseInt(timezone.substring(4), 10));
  763. if (offset !== 0) {
  764. d = new Date(d.getTime() + 60000 * offset);
  765. }
  766. }
  767. this.buffer.writeUInt16LE(d.getUTCFullYear(), this.offset + 1);
  768. this.buffer.writeUInt8(d.getUTCMonth() + 1, this.offset + 3);
  769. this.buffer.writeUInt8(d.getUTCDate(), this.offset + 4);
  770. this.buffer.writeUInt8(d.getUTCHours(), this.offset + 5);
  771. this.buffer.writeUInt8(d.getUTCMinutes(), this.offset + 6);
  772. this.buffer.writeUInt8(d.getUTCSeconds(), this.offset + 7);
  773. this.buffer.writeUInt32LE(d.getUTCMilliseconds() * 1000, this.offset + 8);
  774. }
  775. this.offset += 12;
  776. }
  777. writeHeader(sequenceId) {
  778. const offset = this.offset;
  779. this.offset = 0;
  780. this.writeInt24(this.buffer.length - 4);
  781. this.writeInt8(sequenceId);
  782. this.offset = offset;
  783. }
  784. clone() {
  785. return new Packet(this.sequenceId, this.buffer, this.start, this.end);
  786. }
  787. type() {
  788. if (this.isEOF()) {
  789. return 'EOF';
  790. }
  791. if (this.isError()) {
  792. return 'Error';
  793. }
  794. if (this.buffer[this.offset] === 0) {
  795. return 'maybeOK'; // could be other packet types as well
  796. }
  797. return '';
  798. }
  799. static lengthCodedNumberLength(n) {
  800. if (n < 0xfb) {
  801. return 1;
  802. }
  803. if (n < 0xffff) {
  804. return 3;
  805. }
  806. if (n < 0xffffff) {
  807. return 5;
  808. }
  809. return 9;
  810. }
  811. static lengthCodedStringLength(str, encoding) {
  812. const buf = StringParser.encode(str, encoding);
  813. const slen = buf.length;
  814. return Packet.lengthCodedNumberLength(slen) + slen;
  815. }
  816. static MockBuffer() {
  817. const noop = function() {};
  818. const res = Buffer.alloc(0);
  819. for (const op in NativeBuffer.prototype) {
  820. if (typeof res[op] === 'function') {
  821. res[op] = noop;
  822. }
  823. }
  824. return res;
  825. }
  826. }
  827. module.exports = Packet;