Bug 1885337 - Part 1: Implement to/from hex methods. r=dminor
[gecko.git] / js / src / vm / StaticStrings.cpp
blobc88e02fa39ab876552bd4a53c3397c891195881a
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "vm/StaticStrings.h"
9 #include "mozilla/HashFunctions.h" // mozilla::HashString
11 #include <stddef.h> // size_t
12 #include <stdint.h> // uint32_t
14 #include "js/HashTable.h" // js::HashNumber
15 #include "js/TypeDecls.h" // Latin1Char
16 #include "vm/Realm.h" // AutoAllocInAtomsZone
17 #include "vm/StringType.h" // JSString, JSLinearString
19 #include "vm/Realm-inl.h" // AutoAllocInAtomsZone
20 #include "vm/StringType-inl.h" // NewInlineAtom
22 using namespace js;
24 constexpr StaticStrings::SmallCharTable StaticStrings::createSmallCharTable() {
25 SmallCharTable array{};
26 for (size_t i = 0; i < SMALL_CHAR_TABLE_SIZE; i++) {
27 array[i] = toSmallChar(i);
29 return array;
32 const StaticStrings::SmallCharTable StaticStrings::toSmallCharTable =
33 createSmallCharTable();
35 bool StaticStrings::init(JSContext* cx) {
36 AutoAllocInAtomsZone az(cx);
38 static_assert(UNIT_STATIC_LIMIT - 1 <= JSString::MAX_LATIN1_CHAR,
39 "Unit strings must fit in Latin1Char.");
41 for (uint32_t i = 0; i < UNIT_STATIC_LIMIT; i++) {
42 Latin1Char ch = Latin1Char(i);
43 HashNumber hash = mozilla::HashString(&ch, 1);
44 JSAtom* a = NewInlineAtom(cx, &ch, 1, hash);
45 if (!a) {
46 return false;
48 a->makePermanent();
49 unitStaticTable[i] = a;
52 for (uint32_t i = 0; i < NUM_LENGTH2_ENTRIES; i++) {
53 Latin1Char buffer[] = {firstCharOfLength2(i), secondCharOfLength2(i)};
54 HashNumber hash = mozilla::HashString(buffer, 2);
55 JSAtom* a = NewInlineAtom(cx, buffer, 2, hash);
56 if (!a) {
57 return false;
59 a->makePermanent();
60 length2StaticTable[i] = a;
63 for (uint32_t i = 0; i < INT_STATIC_LIMIT; i++) {
64 if (i < 10) {
65 intStaticTable[i] = unitStaticTable[i + '0'];
66 } else if (i < 100) {
67 auto index =
68 getLength2IndexStatic(char(i / 10) + '0', char(i % 10) + '0');
69 intStaticTable[i] = length2StaticTable[index];
70 } else {
71 Latin1Char buffer[] = {Latin1Char(firstCharOfLength3(i)),
72 Latin1Char(secondCharOfLength3(i)),
73 Latin1Char(thirdCharOfLength3(i))};
74 HashNumber hash = mozilla::HashString(buffer, 3);
75 JSAtom* a = NewInlineAtom(cx, buffer, 3, hash);
76 if (!a) {
77 return false;
79 a->makePermanent();
80 intStaticTable[i] = a;
83 // Static string initialization can not race, so allow even without the
84 // lock.
85 intStaticTable[i]->setIsIndex(i);
88 return true;