arraybuffer.js 2.59 KB
Newer Older
1
// Copyright 2013 the V8 project authors. All rights reserved.
2 3
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
4 5 6 7 8 9 10

"use strict";

var $ArrayBuffer = global.ArrayBuffer;

// -------------------------------------------------------------------

11
function ArrayBufferConstructor(length) { // length = 1
12
  if (%_IsConstructCall()) {
13 14
    var byteLength = ToPositiveInteger(length, 'invalid_array_buffer_length');
    %ArrayBufferInitialize(this, byteLength);
15
  } else {
16
    throw MakeTypeError('constructor_not_function', ["ArrayBuffer"]);
17 18 19
  }
}

20
function ArrayBufferGetByteLen() {
21 22 23 24
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.byteLength', this]);
  }
25
  return %_ArrayBufferGetByteLength(this);
26 27 28 29 30 31 32 33 34 35
}

// ES6 Draft 15.13.5.5.3
function ArrayBufferSlice(start, end) {
  if (!IS_ARRAYBUFFER(this)) {
    throw MakeTypeError('incompatible_method_receiver',
                        ['ArrayBuffer.prototype.slice', this]);
  }

  var relativeStart = TO_INTEGER(start);
36 37 38
  if (!IS_UNDEFINED(end)) {
    end = TO_INTEGER(end);
  }
39
  var first;
40
  var byte_length = %_ArrayBufferGetByteLength(this);
41
  if (relativeStart < 0) {
42
    first = MathMax(byte_length + relativeStart, 0);
43
  } else {
44
    first = MathMin(relativeStart, byte_length);
45
  }
46
  var relativeEnd = IS_UNDEFINED(end) ? byte_length : end;
47 48
  var fin;
  if (relativeEnd < 0) {
49
    fin = MathMax(byte_length + relativeEnd, 0);
50
  } else {
51
    fin = MathMin(relativeEnd, byte_length);
52 53
  }

54 55 56
  if (fin < first) {
    fin = first;
  }
57 58 59 60 61 62 63 64
  var newLen = fin - first;
  // TODO(dslomov): implement inheritance
  var result = new $ArrayBuffer(newLen);

  %ArrayBufferSliceImpl(this, result, first);
  return result;
}

65
function ArrayBufferIsViewJS(obj) {
66 67 68
  return %ArrayBufferIsView(obj);
}

69 70 71 72 73 74 75 76
function SetUpArrayBuffer() {
  %CheckIsBootstrapping();

  // Set up the ArrayBuffer constructor function.
  %SetCode($ArrayBuffer, ArrayBufferConstructor);
  %FunctionSetPrototype($ArrayBuffer, new $Object());

  // Set up the constructor property on the ArrayBuffer prototype object.
77 78
  %AddNamedProperty(
      $ArrayBuffer.prototype, "constructor", $ArrayBuffer, DONT_ENUM);
79

80 81 82
  %AddNamedProperty($ArrayBuffer.prototype,
      symbolToStringTag, "ArrayBuffer", DONT_ENUM | READ_ONLY);

83
  InstallGetter($ArrayBuffer.prototype, "byteLength", ArrayBufferGetByteLen);
84

85
  InstallFunctions($ArrayBuffer, DONT_ENUM, $Array(
86
      "isView", ArrayBufferIsViewJS
87 88
  ));

89 90 91 92 93 94
  InstallFunctions($ArrayBuffer.prototype, DONT_ENUM, $Array(
      "slice", ArrayBufferSlice
  ));
}

SetUpArrayBuffer();