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_VERSION_H
16 #define META_BASE_VERSION_H
17 
18 #include <base/containers/string.h>
19 #include <base/util/uid_util.h>
20 
21 #include <meta/base/namespace.h>
22 
META_BEGIN_NAMESPACE()23 META_BEGIN_NAMESPACE()
24 
25 class Version {
26 public:
27     constexpr Version(uint16_t major = 0, uint16_t minor = 0) : major_(major), minor_(minor) {}
28 
29     constexpr explicit Version(BASE_NS::string_view str)
30     {
31         size_t pos = ParseInt(str, major_);
32         if (pos != 0 && pos + 1 < str.size()) {
33             ParseInt(str.substr(pos + 1), minor_);
34         }
35     }
36 
37     constexpr uint16_t Major() const
38     {
39         return major_;
40     }
41     constexpr uint16_t Minor() const
42     {
43         return minor_;
44     }
45 
46     BASE_NS::string ToString() const
47     {
48         return BASE_NS::string(BASE_NS::to_string(major_)) + "." + BASE_NS::string(BASE_NS::to_string(minor_));
49     }
50 
51 private:
52     constexpr size_t ParseInt(BASE_NS::string_view str, uint16_t& out)
53     {
54         size_t i = 0;
55         while (i < str.size() && str[i] >= '0' && str[i] <= '9') {
56             if (i) {
57                 out *= 10;
58             }
59             out += str[i++] - '0';
60         }
61         return i;
62     }
63 
64 private:
65     uint16_t major_ {};
66     uint16_t minor_ {};
67 };
68 
69 constexpr inline bool operator==(const Version& l, const Version& r)
70 {
71     return l.Major() == r.Major() && l.Minor() == r.Minor();
72 }
73 
74 constexpr inline bool operator!=(const Version& l, const Version& r)
75 {
76     return !(l == r);
77 }
78 
79 constexpr inline bool operator<(const Version& l, const Version& r)
80 {
81     return l.Major() < r.Major() || (l.Major() == r.Major() && l.Minor() < r.Minor());
82 }
83 
84 constexpr inline bool operator<=(const Version& l, const Version& r)
85 {
86     return l == r || l < r;
87 }
88 
89 constexpr inline bool operator>(const Version& l, const Version& r)
90 {
91     return r < l;
92 }
93 
94 constexpr inline bool operator>=(const Version& l, const Version& r)
95 {
96     return r <= l;
97 }
98 
99 META_END_NAMESPACE()
100 
101 #endif
102