string-indexof.tq 1.31 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
// Copyright 2021 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-string-gen.h'

namespace string {

// https://tc39.es/ecma262/#sec-string.prototype.indexof
transitioning javascript builtin
StringPrototypeIndexOf(
    js-implicit context: NativeContext, receiver: JSAny)(...arguments): Smi {
  const methodName: constexpr string = 'String.prototype.indexOf';
  const searchString: JSAny = arguments[0];
  const position: JSAny = arguments[1];

  // 1. Let O be ? RequireObjectCoercible(this value).
  // 2. Let S be ? ToString(O).
  const s = ToThisString(receiver, methodName);

  // 3. Let searchStr be ? ToString(searchString).
  const searchStr = ToString_Inline(searchString);

  // 4. Let pos be ? ToIntegerOrInfinity(position).
  // 5. Assert: If position is undefined, then pos is 0.
  let start: Smi = 0;
  if (position != Undefined) {
    // 6. Let len be the length of S.
    const len = s.length_uintptr;

    // 7. Let start be the result of clamping pos between 0 and len.
    StaticAssertStringLengthFitsSmi();
    start = Convert<Smi>(Signed(ClampToIndexRange(position, len)));
  }

  // 8. Let index be ! StringIndexOf(S, searchStr, start).
  return StringIndexOf(s, searchStr, start);
}
}