1 /* This Source Code Form is subject to the terms of the Mozilla Public
2  * License, v. 2.0. If a copy of the MPL was not distributed with this
3  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4 
5 #include "js/Symbol.h"
6 #include "jsapi-tests/tests.h"
7 
BEGIN_TEST(testSymbol_New)8 BEGIN_TEST(testSymbol_New) {
9   using namespace JS;
10 
11   RootedString desc(cx, nullptr);
12   RootedSymbol sym1(cx);
13   CHECK(sym1 = NewSymbol(cx, desc));
14   CHECK_NULL(GetSymbolDescription(sym1));
15   RootedValue v(cx, SymbolValue(sym1));
16   CHECK_EQUAL(JS_TypeOfValue(cx, v), JSTYPE_SYMBOL);
17 
18   RootedSymbol sym2(cx);
19   CHECK(sym2 = NewSymbol(cx, desc));
20   CHECK(sym1 != sym2);
21 
22   CHECK(desc = JS_NewStringCopyZ(cx, "ponies"));
23   CHECK(sym2 = NewSymbol(cx, desc));
24   CHECK_SAME(StringValue(GetSymbolDescription(sym2)), StringValue(desc));
25 
26   return true;
27 }
28 END_TEST(testSymbol_New)
29 
BEGIN_TEST(testSymbol_GetSymbolFor)30 BEGIN_TEST(testSymbol_GetSymbolFor) {
31   using namespace JS;
32 
33   RootedString desc(cx, JS_NewStringCopyZ(cx, "ponies"));
34   CHECK(desc);
35   RootedSymbol sym1(cx);
36   CHECK(sym1 = GetSymbolFor(cx, desc));
37   CHECK_SAME(StringValue(GetSymbolDescription(sym1)), StringValue(desc));
38 
39   // Calling JS::GetSymbolFor again with the same arguments produces the
40   // same Symbol.
41   RootedSymbol sym2(cx);
42   CHECK(sym2 = GetSymbolFor(cx, desc));
43   CHECK_EQUAL(sym1, sym2);
44 
45   // Passing a new but equal string also produces the same Symbol.
46   CHECK(desc = JS_NewStringCopyZ(cx, "ponies"));
47   CHECK(sym2 = GetSymbolFor(cx, desc));
48   CHECK_EQUAL(sym1, sym2);
49 
50   // But SymbolNew always produces a new distinct Symbol.
51   CHECK(sym2 = NewSymbol(cx, desc));
52   CHECK(sym2 != sym1);
53 
54   return true;
55 }
56 END_TEST(testSymbol_GetSymbolFor)
57 
BEGIN_TEST(testSymbol_GetWellKnownSymbol)58 BEGIN_TEST(testSymbol_GetWellKnownSymbol) {
59   using namespace JS;
60 
61   Rooted<Symbol*> sym1(cx);
62   CHECK(sym1 = GetWellKnownSymbol(cx, SymbolCode::iterator));
63   RootedValue v(cx);
64   EVAL("Symbol.iterator", &v);
65   CHECK_SAME(v, SymbolValue(sym1));
66 
67   // The description of a well-known symbol is as specified.
68   RootedString desc(cx);
69   CHECK(desc = JS_NewStringCopyZ(cx, "Symbol.iterator"));
70   CHECK_SAME(StringValue(GetSymbolDescription(sym1)), StringValue(desc));
71 
72   // GetSymbolFor never returns a well-known symbol.
73   Rooted<Symbol*> sym2(cx);
74   CHECK(sym2 = GetSymbolFor(cx, desc));
75   CHECK(sym2 != sym1);
76 
77   return true;
78 }
79 END_TEST(testSymbol_GetWellKnownSymbol)
80