byte-helpers.js 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271
  1. import window from 'global/window'; // const log2 = Math.log2 ? Math.log2 : (x) => (Math.log(x) / Math.log(2));
  2. var repeat = function repeat(str, len) {
  3. var acc = '';
  4. while (len--) {
  5. acc += str;
  6. }
  7. return acc;
  8. }; // count the number of bits it would take to represent a number
  9. // we used to do this with log2 but BigInt does not support builtin math
  10. // Math.ceil(log2(x));
  11. export var countBits = function countBits(x) {
  12. return x.toString(2).length;
  13. }; // count the number of whole bytes it would take to represent a number
  14. export var countBytes = function countBytes(x) {
  15. return Math.ceil(countBits(x) / 8);
  16. };
  17. export var padStart = function padStart(b, len, str) {
  18. if (str === void 0) {
  19. str = ' ';
  20. }
  21. return (repeat(str, len) + b.toString()).slice(-len);
  22. };
  23. export var isArrayBufferView = function isArrayBufferView(obj) {
  24. if (ArrayBuffer.isView === 'function') {
  25. return ArrayBuffer.isView(obj);
  26. }
  27. return obj && obj.buffer instanceof ArrayBuffer;
  28. };
  29. export var isTypedArray = function isTypedArray(obj) {
  30. return isArrayBufferView(obj);
  31. };
  32. export var toUint8 = function toUint8(bytes) {
  33. if (bytes instanceof Uint8Array) {
  34. return bytes;
  35. }
  36. if (!Array.isArray(bytes) && !isTypedArray(bytes) && !(bytes instanceof ArrayBuffer)) {
  37. // any non-number or NaN leads to empty uint8array
  38. // eslint-disable-next-line
  39. if (typeof bytes !== 'number' || typeof bytes === 'number' && bytes !== bytes) {
  40. bytes = 0;
  41. } else {
  42. bytes = [bytes];
  43. }
  44. }
  45. return new Uint8Array(bytes && bytes.buffer || bytes, bytes && bytes.byteOffset || 0, bytes && bytes.byteLength || 0);
  46. };
  47. export var toHexString = function toHexString(bytes) {
  48. bytes = toUint8(bytes);
  49. var str = '';
  50. for (var i = 0; i < bytes.length; i++) {
  51. str += padStart(bytes[i].toString(16), 2, '0');
  52. }
  53. return str;
  54. };
  55. export var toBinaryString = function toBinaryString(bytes) {
  56. bytes = toUint8(bytes);
  57. var str = '';
  58. for (var i = 0; i < bytes.length; i++) {
  59. str += padStart(bytes[i].toString(2), 8, '0');
  60. }
  61. return str;
  62. };
  63. var BigInt = window.BigInt || Number;
  64. var BYTE_TABLE = [BigInt('0x1'), BigInt('0x100'), BigInt('0x10000'), BigInt('0x1000000'), BigInt('0x100000000'), BigInt('0x10000000000'), BigInt('0x1000000000000'), BigInt('0x100000000000000'), BigInt('0x10000000000000000')];
  65. export var ENDIANNESS = function () {
  66. var a = new Uint16Array([0xFFCC]);
  67. var b = new Uint8Array(a.buffer, a.byteOffset, a.byteLength);
  68. if (b[0] === 0xFF) {
  69. return 'big';
  70. }
  71. if (b[0] === 0xCC) {
  72. return 'little';
  73. }
  74. return 'unknown';
  75. }();
  76. export var IS_BIG_ENDIAN = ENDIANNESS === 'big';
  77. export var IS_LITTLE_ENDIAN = ENDIANNESS === 'little';
  78. export var bytesToNumber = function bytesToNumber(bytes, _temp) {
  79. var _ref = _temp === void 0 ? {} : _temp,
  80. _ref$signed = _ref.signed,
  81. signed = _ref$signed === void 0 ? false : _ref$signed,
  82. _ref$le = _ref.le,
  83. le = _ref$le === void 0 ? false : _ref$le;
  84. bytes = toUint8(bytes);
  85. var fn = le ? 'reduce' : 'reduceRight';
  86. var obj = bytes[fn] ? bytes[fn] : Array.prototype[fn];
  87. var number = obj.call(bytes, function (total, byte, i) {
  88. var exponent = le ? i : Math.abs(i + 1 - bytes.length);
  89. return total + BigInt(byte) * BYTE_TABLE[exponent];
  90. }, BigInt(0));
  91. if (signed) {
  92. var max = BYTE_TABLE[bytes.length] / BigInt(2) - BigInt(1);
  93. number = BigInt(number);
  94. if (number > max) {
  95. number -= max;
  96. number -= max;
  97. number -= BigInt(2);
  98. }
  99. }
  100. return Number(number);
  101. };
  102. export var numberToBytes = function numberToBytes(number, _temp2) {
  103. var _ref2 = _temp2 === void 0 ? {} : _temp2,
  104. _ref2$le = _ref2.le,
  105. le = _ref2$le === void 0 ? false : _ref2$le;
  106. // eslint-disable-next-line
  107. if (typeof number !== 'bigint' && typeof number !== 'number' || typeof number === 'number' && number !== number) {
  108. number = 0;
  109. }
  110. number = BigInt(number);
  111. var byteCount = countBytes(number);
  112. var bytes = new Uint8Array(new ArrayBuffer(byteCount));
  113. for (var i = 0; i < byteCount; i++) {
  114. var byteIndex = le ? i : Math.abs(i + 1 - bytes.length);
  115. bytes[byteIndex] = Number(number / BYTE_TABLE[i] & BigInt(0xFF));
  116. if (number < 0) {
  117. bytes[byteIndex] = Math.abs(~bytes[byteIndex]);
  118. bytes[byteIndex] -= i === 0 ? 1 : 2;
  119. }
  120. }
  121. return bytes;
  122. };
  123. export var bytesToString = function bytesToString(bytes) {
  124. if (!bytes) {
  125. return '';
  126. } // TODO: should toUint8 handle cases where we only have 8 bytes
  127. // but report more since this is a Uint16+ Array?
  128. bytes = Array.prototype.slice.call(bytes);
  129. var string = String.fromCharCode.apply(null, toUint8(bytes));
  130. try {
  131. return decodeURIComponent(escape(string));
  132. } catch (e) {// if decodeURIComponent/escape fails, we are dealing with partial
  133. // or full non string data. Just return the potentially garbled string.
  134. }
  135. return string;
  136. };
  137. export var stringToBytes = function stringToBytes(string, stringIsBytes) {
  138. if (typeof string !== 'string' && string && typeof string.toString === 'function') {
  139. string = string.toString();
  140. }
  141. if (typeof string !== 'string') {
  142. return new Uint8Array();
  143. } // If the string already is bytes, we don't have to do this
  144. // otherwise we do this so that we split multi length characters
  145. // into individual bytes
  146. if (!stringIsBytes) {
  147. string = unescape(encodeURIComponent(string));
  148. }
  149. var view = new Uint8Array(string.length);
  150. for (var i = 0; i < string.length; i++) {
  151. view[i] = string.charCodeAt(i);
  152. }
  153. return view;
  154. };
  155. export var concatTypedArrays = function concatTypedArrays() {
  156. for (var _len = arguments.length, buffers = new Array(_len), _key = 0; _key < _len; _key++) {
  157. buffers[_key] = arguments[_key];
  158. }
  159. buffers = buffers.filter(function (b) {
  160. return b && (b.byteLength || b.length) && typeof b !== 'string';
  161. });
  162. if (buffers.length <= 1) {
  163. // for 0 length we will return empty uint8
  164. // for 1 length we return the first uint8
  165. return toUint8(buffers[0]);
  166. }
  167. var totalLen = buffers.reduce(function (total, buf, i) {
  168. return total + (buf.byteLength || buf.length);
  169. }, 0);
  170. var tempBuffer = new Uint8Array(totalLen);
  171. var offset = 0;
  172. buffers.forEach(function (buf) {
  173. buf = toUint8(buf);
  174. tempBuffer.set(buf, offset);
  175. offset += buf.byteLength;
  176. });
  177. return tempBuffer;
  178. };
  179. /**
  180. * Check if the bytes "b" are contained within bytes "a".
  181. *
  182. * @param {Uint8Array|Array} a
  183. * Bytes to check in
  184. *
  185. * @param {Uint8Array|Array} b
  186. * Bytes to check for
  187. *
  188. * @param {Object} options
  189. * options
  190. *
  191. * @param {Array|Uint8Array} [offset=0]
  192. * offset to use when looking at bytes in a
  193. *
  194. * @param {Array|Uint8Array} [mask=[]]
  195. * mask to use on bytes before comparison.
  196. *
  197. * @return {boolean}
  198. * If all bytes in b are inside of a, taking into account
  199. * bit masks.
  200. */
  201. export var bytesMatch = function bytesMatch(a, b, _temp3) {
  202. var _ref3 = _temp3 === void 0 ? {} : _temp3,
  203. _ref3$offset = _ref3.offset,
  204. offset = _ref3$offset === void 0 ? 0 : _ref3$offset,
  205. _ref3$mask = _ref3.mask,
  206. mask = _ref3$mask === void 0 ? [] : _ref3$mask;
  207. a = toUint8(a);
  208. b = toUint8(b); // ie 11 does not support uint8 every
  209. var fn = b.every ? b.every : Array.prototype.every;
  210. return b.length && a.length - offset >= b.length && // ie 11 doesn't support every on uin8
  211. fn.call(b, function (bByte, i) {
  212. var aByte = mask[i] ? mask[i] & a[offset + i] : a[offset + i];
  213. return bByte === aByte;
  214. });
  215. };
  216. export var sliceBytes = function sliceBytes(src, start, end) {
  217. if (Uint8Array.prototype.slice) {
  218. return Uint8Array.prototype.slice.call(src, start, end);
  219. }
  220. return new Uint8Array(Array.prototype.slice.call(src, start, end));
  221. };
  222. export var reverseBytes = function reverseBytes(src) {
  223. if (src.reverse) {
  224. return src.reverse();
  225. }
  226. return Array.prototype.reverse.call(src);
  227. };