• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2018 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include 'src/builtins/builtins-regexp-gen.h'
6
7namespace string {
8// https://tc39.github.io/ecma262/#sec-string.prototype.startswith
9transitioning javascript builtin StringPrototypeStartsWith(
10    js-implicit context: NativeContext,
11    receiver: JSAny)(...arguments): Boolean {
12  const searchString: JSAny = arguments[0];
13  const position: JSAny = arguments[1];
14  const kBuiltinName: constexpr string = 'String.prototype.startsWith';
15
16  // 1. Let O be ? RequireObjectCoercible(this value).
17  // 2. Let S be ? ToString(O).
18  const string: String = ToThisString(receiver, kBuiltinName);
19
20  // 3. Let isRegExp be ? IsRegExp(searchString).
21  // 4. If isRegExp is true, throw a TypeError exception.
22  if (regexp::IsRegExp(searchString)) {
23    ThrowTypeError(MessageTemplate::kFirstArgumentNotRegExp, kBuiltinName);
24  }
25
26  // 5. Let searchStr be ? ToString(searchString).
27  const searchStr: String = ToString_Inline(searchString);
28
29  // 8. Let len be the length of S.
30  const len: uintptr = string.length_uintptr;
31
32  // 6. Let pos be ? ToInteger(position).
33  // 7. Assert: If position is undefined, then pos is 0.
34  // 9. Let start be min(max(pos, 0), len).
35  const start: uintptr =
36      (position != Undefined) ? ClampToIndexRange(position, len) : 0;
37
38  // 10. Let searchLength be the length of searchStr.
39  const searchLength: uintptr = searchStr.length_uintptr;
40
41  // 11. If searchLength + start is greater than len, return false.
42  // The comparison is rephrased to be overflow-friendly with unsigned
43  // indices.
44  if (searchLength > len - start) return False;
45
46  // 12. If the sequence of code units of S starting at start of length
47  // searchLength is the same as the full code unit sequence of searchStr,
48  // return true.
49  // 13. Otherwise, return false.
50  return Convert<Boolean>(IsSubstringAt(string, searchStr, Signed(start)));
51}
52}
53