testSharedImmutableStringsCache.cpp (2130B)
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/. */ 6 7 #include "mozilla/IntegerRange.h" 8 9 #include "js/Vector.h" 10 #include "jsapi-tests/tests.h" 11 #include "threading/Thread.h" 12 #include "util/Text.h" 13 #include "vm/SharedImmutableStringsCache.h" 14 15 const int NUM_THREADS = 256; 16 const int NUM_ITERATIONS = 256; 17 18 const int NUM_STRINGS = 4; 19 const char16_t* const STRINGS[NUM_STRINGS] = {u"uno", u"dos", u"tres", 20 u"quattro"}; 21 22 struct CacheAndIndex { 23 js::SharedImmutableStringsCache* cache; 24 int index; 25 26 CacheAndIndex(js::SharedImmutableStringsCache* cache, int index) 27 : cache(cache), index(index) {} 28 }; 29 30 static void getString(CacheAndIndex* cacheAndIndex) { 31 for (int i = 0; i < NUM_ITERATIONS; i++) { 32 auto str = STRINGS[cacheAndIndex->index % NUM_STRINGS]; 33 34 auto dupe = js::DuplicateString(str); 35 MOZ_RELEASE_ASSERT(dupe); 36 37 auto deduped = 38 cacheAndIndex->cache->getOrCreate(std::move(dupe), js_strlen(str)); 39 MOZ_RELEASE_ASSERT(deduped); 40 MOZ_RELEASE_ASSERT( 41 js::EqualChars(str, deduped.chars(), js_strlen(str) + 1)); 42 43 { 44 auto cloned = deduped.clone(); 45 // We should be de-duplicating and giving back the same string. 46 MOZ_RELEASE_ASSERT(deduped.chars() == cloned.chars()); 47 } 48 } 49 50 js_delete(cacheAndIndex); 51 } 52 53 BEGIN_TEST(testSharedImmutableStringsCache) { 54 auto& cache = js::SharedImmutableStringsCache::getSingleton(); 55 56 js::Vector<js::Thread> threads(cx); 57 CHECK(threads.reserve(NUM_THREADS)); 58 59 for (auto i : mozilla::IntegerRange(NUM_THREADS)) { 60 auto cacheAndIndex = js_new<CacheAndIndex>(&cache, i); 61 CHECK(cacheAndIndex); 62 threads.infallibleEmplaceBack(); 63 CHECK(threads.back().init(getString, cacheAndIndex)); 64 } 65 66 for (auto& thread : threads) { 67 thread.join(); 68 } 69 70 return true; 71 } 72 END_TEST(testSharedImmutableStringsCache)