1 /*
2  * Copyright (c) 2024 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 #ifndef META_BASE_IDS_H
16 #define META_BASE_IDS_H
17 
18 #include <base/containers/string.h>
19 #include <base/util/uid_util.h>
20 
21 #include <meta/base/meta_types.h>
22 #include <meta/base/namespace.h>
23 
META_BEGIN_NAMESPACE()24 META_BEGIN_NAMESPACE()
25 
26 template<typename>
27 class IdBase {
28 public:
29     constexpr IdBase(const BASE_NS::Uid& id = {}) noexcept : id_(id) {}
30 
31     explicit constexpr IdBase(const char (&str)[37]) noexcept : id_(str) {}
32 
33     BASE_NS::string ToString() const noexcept
34     {
35         return BASE_NS::string(BASE_NS::to_string(id_));
36     }
37 
38     constexpr BASE_NS::Uid ToUid() const noexcept
39     {
40         return id_;
41     }
42 
43     constexpr bool IsValid() const noexcept
44     {
45         return id_.data[0] && id_.data[1];
46     }
47 
48     constexpr bool operator==(const IdBase& r) const noexcept
49     {
50         return id_ == r.id_;
51     }
52     constexpr bool operator!=(const IdBase& r) const noexcept
53     {
54         return id_ != r.id_;
55     }
56     constexpr bool operator<(const IdBase& r) const noexcept
57     {
58         return id_ < r.id_;
59     }
60     constexpr int Compare(const IdBase& r) const noexcept
61     {
62         return id_.compare(r.id_);
63     }
64 
65 protected:
66     BASE_NS::Uid id_;
67 };
68 
69 class TypeId : public IdBase<TypeId> {
70 public:
71     using IdBase<TypeId>::IdBase;
72 };
73 
74 class ObjectId : public IdBase<ObjectId> {
75 public:
76     using IdBase<ObjectId>::IdBase;
77 };
78 
79 class InstanceId : public IdBase<InstanceId> {
80 public:
81     using IdBase<InstanceId>::IdBase;
82 };
83 
84 META_TYPE(TypeId);
85 META_TYPE(ObjectId);
86 META_TYPE(InstanceId);
87 
88 META_END_NAMESPACE()
89 
BASE_BEGIN_NAMESPACE()90 BASE_BEGIN_NAMESPACE()
91 template<>
92 inline uint64_t hash(const META_NS::TypeId& value)
93 {
94     return hash(value.ToUid());
95 }
96 template<>
hash(const META_NS::ObjectId & value)97 inline uint64_t hash(const META_NS::ObjectId& value)
98 {
99     return hash(value.ToUid());
100 }
101 template<>
hash(const META_NS::InstanceId & value)102 inline uint64_t hash(const META_NS::InstanceId& value)
103 {
104     return hash(value.ToUid());
105 }
106 BASE_END_NAMESPACE()
107 
108 #endif
109