typed-array-foreach.tq 2.39 KB
Newer Older
1 2 3 4 5 6
// Copyright 2019 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include 'src/builtins/builtins-typed-array-gen.h'

7
namespace typed_array {
8
const kBuiltinNameForEach: constexpr string = '%TypedArray%.prototype.forEach';
9

10 11 12 13 14
transitioning macro ForEachAllElements(implicit context: Context)(
    array: typed_array::AttachedJSTypedArray, callbackfn: Callable,
    thisArg: JSAny): Undefined {
  let witness = typed_array::NewAttachedJSTypedArrayWitness(array);
  const length: uintptr = witness.Get().length;
15 16

  // 6. Repeat, while k < len
17
  for (let k: uintptr = 0; k < length; k++) {
18 19 20 21 22 23 24 25 26 27 28 29 30 31
    // 6a. Let Pk be ! ToString(𝔽(k)).
    // There is no need to cast ToString to load elements.

    // 6b. Let kValue be ! Get(O, Pk).
    // kValue must be undefined when the buffer is detached.
    let value: JSAny;
    try {
      witness.Recheck() otherwise goto IsDetached;
      value = witness.Load(k);
    } label IsDetached deferred {
      value = Undefined;
    }

    // 6c. Perform ? Call(callbackfn, thisArg, « kValue, 𝔽(k), O »).
32 33 34 35 36
    // TODO(v8:4153): Consider versioning this loop for Smi and non-Smi
    // indices to optimize Convert<Number>(k) for the most common case.
    Call(
        context, callbackfn, thisArg, value, Convert<Number>(k),
        witness.GetStable());
37 38

    // 6d. Set k to k + 1. (done by the loop).
39
  }
40 41

  // 7. Return undefined.
42 43
  return Undefined;
}
44

45 46 47 48 49 50
// https://tc39.github.io/ecma262/#sec-%typedarray%.prototype.every
transitioning javascript builtin
TypedArrayPrototypeForEach(js-implicit context: NativeContext, receiver: JSAny)(
    ...arguments): Undefined {
  // arguments[0] = callback
  // arguments[1] = this_arg.
51

52 53 54 55
  try {
    const array: JSTypedArray = Cast<JSTypedArray>(receiver)
        otherwise NotTypedArray;
    const uarray = typed_array::EnsureAttached(array) otherwise IsDetached;
56

57 58 59 60 61 62 63 64 65
    const callbackfn = Cast<Callable>(arguments[0]) otherwise NotCallable;
    const thisArg = arguments[1];
    return ForEachAllElements(uarray, callbackfn, thisArg);
  } label NotCallable deferred {
    ThrowTypeError(MessageTemplate::kCalledNonCallable, arguments[0]);
  } label NotTypedArray deferred {
    ThrowTypeError(MessageTemplate::kNotTypedArray, kBuiltinNameForEach);
  } label IsDetached deferred {
    ThrowTypeError(MessageTemplate::kDetachedOperation, kBuiltinNameForEach);
66 67
  }
}
68
}