es.array-buffer.slice.js 1.5 KB

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