1 //
2 // Copyright (C) 2020 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 #include <inttypes.h>
18 
19 #include <android-base/stringprintf.h>
20 #include <kver/kmi_version.h>
21 
22 namespace android::kver {
23 
24 #define KMI_VERSION_PRINT_FORMAT "%" PRIu64 ".%" PRIu64 "-android%" PRIu64 "-%" PRIu64
25 #define KMI_VERSION_SCAN_FORMAT KMI_VERSION_PRINT_FORMAT "%n"
26 
27 // Not taking a string_view because sscanf requires null-termination.
28 std::optional<KmiVersion> KmiVersion::Parse(const std::string& s) {
29   if (s.size() > std::numeric_limits<int>::max()) return std::nullopt;
30   int nchars = -1;
31   KmiVersion ret;
32   auto scan_res = sscanf(s.c_str(), KMI_VERSION_SCAN_FORMAT, &ret.version_, &ret.patch_level_,
33                          &ret.release_, &ret.gen_, &nchars);
34   if (scan_res != 4) return std::nullopt;
35   if (nchars < 0) return std::nullopt;
36   // Ensure the whole string is consumed.
37   if (nchars != s.size()) return std::nullopt;
38   return ret;
39 }
40 
41 std::string KmiVersion::string() const {
42   return android::base::StringPrintf(KMI_VERSION_PRINT_FORMAT, version(), patch_level(),
43                                      android_release(), generation());
44 }
45 
46 std::tuple<uint64_t, uint64_t, uint64_t, uint64_t> KmiVersion::tuple() const {
47   return std::make_tuple(version(), patch_level(), android_release(), generation());
48 }
49 
50 }  // namespace android::kver
51