es.array-buffer.slice.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. 'use strict';
  2. var $ = require('../internals/export');
  3. var uncurryThis = require('../internals/function-uncurry-this');
  4. var fails = require('../internals/fails');
  5. var ArrayBufferModule = require('../internals/array-buffer');
  6. var anObject = require('../internals/an-object');
  7. var toAbsoluteIndex = require('../internals/to-absolute-index');
  8. var toLength = require('../internals/to-length');
  9. var speciesConstructor = require('../internals/species-constructor');
  10. var ArrayBuffer = ArrayBufferModule.ArrayBuffer;
  11. var DataView = ArrayBufferModule.DataView;
  12. var DataViewPrototype = DataView.prototype;
  13. var un$ArrayBufferSlice = uncurryThis(ArrayBuffer.prototype.slice);
  14. var getUint8 = uncurryThis(DataViewPrototype.getUint8);
  15. var setUint8 = uncurryThis(DataViewPrototype.setUint8);
  16. var INCORRECT_SLICE = fails(function () {
  17. return !new ArrayBuffer(2).slice(1, undefined).byteLength;
  18. });
  19. // `ArrayBuffer.prototype.slice` method
  20. // https://tc39.es/ecma262/#sec-arraybuffer.prototype.slice
  21. $({ target: 'ArrayBuffer', proto: true, unsafe: true, forced: INCORRECT_SLICE }, {
  22. slice: function slice(start, end) {
  23. if (un$ArrayBufferSlice && end === undefined) {
  24. return un$ArrayBufferSlice(anObject(this), start); // FF fix
  25. }
  26. var length = anObject(this).byteLength;
  27. var first = toAbsoluteIndex(start, length);
  28. var fin = toAbsoluteIndex(end === undefined ? length : end, length);
  29. var result = new (speciesConstructor(this, ArrayBuffer))(toLength(fin - first));
  30. var viewSource = new DataView(this);
  31. var viewTarget = new DataView(result);
  32. var index = 0;
  33. while (first < fin) {
  34. setUint8(viewTarget, index++, getUint8(viewSource, first++));
  35. } return result;
  36. }
  37. });