1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef MINIKIN_LOCALE_LIST_CACHE_H
18 #define MINIKIN_LOCALE_LIST_CACHE_H
19 
20 #include <mutex>
21 #include <unordered_map>
22 
23 #include "minikin/Macros.h"
24 
25 #include "Locale.h"
26 
27 namespace minikin {
28 
29 class LocaleListCache {
30 public:
31     // A special ID for the empty locale list.
32     // This value must be 0 since the empty locale list is inserted into mLocaleLists by
33     // default.
34     const static uint32_t kEmptyListId = 0;
35 
36     // A special ID for the invalid locale list.
37     const static uint32_t kInvalidListId = (uint32_t)(-1);
38 
39     // Returns the locale list ID for the given string representation of LocaleList.
40     // Caller should acquire a lock before calling the method.
getId(const std::string & locales)41     static inline uint32_t getId(const std::string& locales) {
42         return getInstance().getIdInternal(locales);
43     }
44 
45     // Caller should acquire a lock before calling the method.
getById(uint32_t id)46     static inline const LocaleList& getById(uint32_t id) {
47         return getInstance().getByIdInternal(id);
48     }
49 
50 private:
51     LocaleListCache();  // Singleton
~LocaleListCache()52     ~LocaleListCache() {}
53 
54     uint32_t getIdInternal(const std::string& locales);
55     const LocaleList& getByIdInternal(uint32_t id);
56 
57     // Caller should acquire a lock before calling the method.
getInstance()58     static LocaleListCache& getInstance() {
59         static LocaleListCache instance;
60         return instance;
61     }
62 
63     std::vector<LocaleList> mLocaleLists GUARDED_BY(mMutex);
64 
65     // A map from the string representation of the font locale list to the ID.
66     std::unordered_map<std::string, uint32_t> mLocaleListLookupTable GUARDED_BY(mMutex);
67 
68     std::mutex mMutex;
69 };
70 
71 }  // namespace minikin
72 
73 #endif  // MINIKIN_LOCALE_LIST_CACHE_H
74