• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2020 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include "gn/version.h"
6 #include <iostream>
7 #include <string_view>
8 #include <tuple>
9 
10 #include "base/strings/string_number_conversions.h"
11 
12 using namespace std::literals;
13 
14 constexpr std::string_view kDot = "."sv;
15 
Version(int major,int minor,int patch)16 Version::Version(int major, int minor, int patch)
17     : major_(major), minor_(minor), patch_(patch) {}
18 
19 // static
FromString(std::string s)20 std::optional<Version> Version::FromString(std::string s) {
21   int major = 0, minor = 0, patch = 0;
22   // First, parse the major version.
23   size_t major_begin = 0;
24   if (size_t major_end = s.find(kDot, major_begin);
25       major_end != std::string::npos) {
26     if (!base::StringToInt(s.substr(major_begin, major_end - major_begin),
27                            &major))
28       return {};
29     // Then, parse the minor version.
30     size_t minor_begin = major_end + kDot.size();
31     if (size_t minor_end = s.find(kDot, minor_begin);
32         minor_end != std::string::npos) {
33       if (!base::StringToInt(s.substr(minor_begin, minor_end - minor_begin),
34                              &minor))
35         return {};
36       // Finally, parse the patch version.
37       size_t patch_begin = minor_end + kDot.size();
38       if (!base::StringToInt(s.substr(patch_begin, std::string::npos), &patch))
39         return {};
40       return Version(major, minor, patch);
41     }
42   }
43   return {};
44 }
45 
operator ==(const Version & other) const46 bool Version::operator==(const Version& other) const {
47   return other.major_ == major_ && other.minor_ == minor_ &&
48          other.patch_ == patch_;
49 }
50 
operator <(const Version & other) const51 bool Version::operator<(const Version& other) const {
52   return std::tie(major_, minor_, patch_) <
53          std::tie(other.major_, other.minor_, other.patch_);
54 }
55 
operator !=(const Version & other) const56 bool Version::operator!=(const Version& other) const {
57   return !(*this == other);
58 }
59 
operator >=(const Version & other) const60 bool Version::operator>=(const Version& other) const {
61   return !(*this < other);
62 }
63 
operator >(const Version & other) const64 bool Version::operator>(const Version& other) const {
65   return other < *this;
66 }
67 
operator <=(const Version & other) const68 bool Version::operator<=(const Version& other) const {
69   return !(*this > other);
70 }
71 
Describe() const72 std::string Version::Describe() const {
73   std::string ret;
74   ret += base::IntToString(major_);
75   ret += kDot;
76   ret += base::IntToString(minor_);
77   ret += kDot;
78   ret += base::IntToString(patch_);
79   return ret;
80 }
81