utils.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. "use strict";
  2. // Returns "Type(value) is Object" in ES terminology.
  3. function isObject(value) {
  4. return typeof value === "object" && value !== null || typeof value === "function";
  5. }
  6. function getReferenceToBytes(bufferSource) {
  7. // Node.js' Buffer does not allow subclassing for now, so we can get away with a prototype object check for perf.
  8. if (Object.getPrototypeOf(bufferSource) === Buffer.prototype) {
  9. return bufferSource;
  10. }
  11. if (bufferSource instanceof ArrayBuffer) {
  12. return Buffer.from(bufferSource);
  13. }
  14. return Buffer.from(bufferSource.buffer, bufferSource.byteOffset, bufferSource.byteLength);
  15. }
  16. function getCopyToBytes(bufferSource) {
  17. return Buffer.from(getReferenceToBytes(bufferSource));
  18. }
  19. function mixin(target, source) {
  20. const keys = Object.getOwnPropertyNames(source);
  21. for (let i = 0; i < keys.length; ++i) {
  22. if (keys[i] in target) {
  23. continue;
  24. }
  25. Object.defineProperty(target, keys[i], Object.getOwnPropertyDescriptor(source, keys[i]));
  26. }
  27. }
  28. const wrapperSymbol = Symbol("wrapper");
  29. const implSymbol = Symbol("impl");
  30. const sameObjectCaches = Symbol("SameObject caches");
  31. function getSameObject(wrapper, prop, creator) {
  32. if (!wrapper[sameObjectCaches]) {
  33. wrapper[sameObjectCaches] = Object.create(null);
  34. }
  35. if (prop in wrapper[sameObjectCaches]) {
  36. return wrapper[sameObjectCaches][prop];
  37. }
  38. wrapper[sameObjectCaches][prop] = creator();
  39. return wrapper[sameObjectCaches][prop];
  40. }
  41. function wrapperForImpl(impl) {
  42. return impl ? impl[wrapperSymbol] : null;
  43. }
  44. function implForWrapper(wrapper) {
  45. return wrapper ? wrapper[implSymbol] : null;
  46. }
  47. function tryWrapperForImpl(impl) {
  48. const wrapper = wrapperForImpl(impl);
  49. return wrapper ? wrapper : impl;
  50. }
  51. function tryImplForWrapper(wrapper) {
  52. const impl = implForWrapper(wrapper);
  53. return impl ? impl : wrapper;
  54. }
  55. const iterInternalSymbol = Symbol("internal");
  56. const IteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()));
  57. module.exports = exports = {
  58. isObject,
  59. getReferenceToBytes,
  60. getCopyToBytes,
  61. mixin,
  62. wrapperSymbol,
  63. implSymbol,
  64. getSameObject,
  65. wrapperForImpl,
  66. implForWrapper,
  67. tryWrapperForImpl,
  68. tryImplForWrapper,
  69. iterInternalSymbol,
  70. IteratorPrototype
  71. };