1 /*
2 * Copyright (c) 2021 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LINEAR_MAP_H
17 #define FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LINEAR_MAP_H
18
19 #include <algorithm>
20 #include <cstring>
21
22 namespace OHOS::Ace {
23 template<typename T>
24 struct LinearMapNode {
25 const char* key;
26 T value;
27 };
28
29 // the key type K must can be compared.
30 template<typename K, typename V>
31 struct LinearEnumMapNode {
32 K key;
33 V value;
34 };
35
36 // these binary search functions in linear map, so the map must be sorted by key.
37 template<typename T>
BinarySearchFindIndex(const LinearMapNode<T> * vec,size_t length,const char * key)38 int64_t BinarySearchFindIndex(const LinearMapNode<T>* vec, size_t length, const char* key)
39 {
40 auto it = std::lower_bound(
41 vec, vec + length, key, [](LinearMapNode<T> lhs, const char* key) { return strcmp(lhs.key, key) < 0; });
42 if (it == vec + length || strcmp(it->key, key) != 0) {
43 return -1;
44 } else {
45 return it - vec;
46 }
47 }
48
49 template<typename K, typename V>
BinarySearchFindIndex(const LinearEnumMapNode<K,V> * vec,size_t length,K key)50 int64_t BinarySearchFindIndex(const LinearEnumMapNode<K, V>* vec, size_t length, K key)
51 {
52 auto it =
53 std::lower_bound(vec, vec + length, key, [](LinearEnumMapNode<K, V> lhs, K key) { return lhs.key < key; });
54 if (it == vec + length || it->key != key) {
55 return -1;
56 } else {
57 return it - vec;
58 }
59 }
60 } // namespace OHOS::Ace
61
62 #endif // FOUNDATION_ACE_FRAMEWORKS_BASE_UTILS_LINEAR_MAP_H
63