core.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. 'use strict'
  2. const length = (a, b) => {
  3. if (a.byteLength === b.byteLength) return a.byteLength
  4. else if (a.byteLength > b.byteLength) return a.byteLength
  5. return b.byteLength
  6. }
  7. const bytes = (_from, encoding) => bytes.from(_from, encoding)
  8. bytes.sorter = (a, b) => {
  9. a = bytes(a)
  10. b = bytes(b)
  11. const len = length(a, b)
  12. let i = 0
  13. while (i < (len - 1)) {
  14. if (i >= a.byteLength) return 1
  15. else if (i >= b.byteLength) return -1
  16. if (a.getUint8(i) < b.getUint8(i)) return -1
  17. else if (a.getUint8(i) > b.getUint8(i)) return 1
  18. i++
  19. }
  20. return 0
  21. }
  22. bytes.compare = (a, b) => !bytes.sorter(a, b)
  23. bytes.memcopy = (_from, encoding) => {
  24. const b = bytes(_from, encoding)
  25. return b.buffer.slice(b.byteOffset, b.byteOffset + b.byteLength)
  26. }
  27. bytes.arrayBuffer = (_from, encoding) => {
  28. _from = bytes(_from, encoding)
  29. if (_from.buffer.byteLength === _from.byteLength) return _from.buffer
  30. return _from.buffer.slice(_from.byteOffset, _from.byteOffset + _from.byteLength)
  31. }
  32. const sliceOptions = (_from, start = 0, end = null) => {
  33. _from = bytes(_from)
  34. end = (end === null ? _from.byteLength : end) - start
  35. return [_from.buffer, _from.byteOffset + start, end]
  36. }
  37. bytes.slice = (_from, start, end) => new DataView(...sliceOptions(_from, start, end))
  38. bytes.memcopySlice = (_from, start, end) => {
  39. const [buffer, offset, length] = sliceOptions(_from, start, end)
  40. return buffer.slice(offset, length + offset)
  41. }
  42. bytes.typedArray = (_from, _Class = Uint8Array) => {
  43. _from = bytes(_from)
  44. return new _Class(_from.buffer, _from.byteOffset, _from.byteLength / _Class.BYTES_PER_ELEMENT)
  45. }
  46. bytes.concat = (_from) => {
  47. _from = Array.from(_from)
  48. _from = _from.map(b => bytes(b))
  49. const length = _from.reduce((x, y) => x + y.byteLength, 0)
  50. const ret = new Uint8Array(length)
  51. let i = 0
  52. for (const part of _from) {
  53. const view = bytes.typedArray(part)
  54. ret.set(view, i)
  55. i += view.byteLength
  56. }
  57. return ret.buffer
  58. }
  59. const maxEntropy = 65536
  60. bytes.random = length => {
  61. const ab = new ArrayBuffer(length)
  62. if (length > maxEntropy) {
  63. let i = 0
  64. while (i < ab.byteLength) {
  65. let len
  66. if (i + maxEntropy > ab.byteLength) len = ab.byteLength - i
  67. else len = maxEntropy
  68. const view = new Uint8Array(ab, i, len)
  69. i += maxEntropy
  70. bytes._randomFill(view)
  71. }
  72. } else {
  73. const view = new Uint8Array(ab)
  74. bytes._randomFill(view)
  75. }
  76. return ab
  77. }
  78. module.exports = bytes