1 // Copyright (c) 2009 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 <vector> 6 7 #include "base/string_util.h" 8 #include "base/version.h" 9 10 // static GetVersionFromString(const std::wstring & version_str)11Version* Version::GetVersionFromString(const std::wstring& version_str) { 12 if (!IsStringASCII(version_str)) 13 return NULL; 14 return GetVersionFromString(WideToASCII(version_str)); 15 } 16 17 // static GetVersionFromString(const std::string & version_str)18Version* Version::GetVersionFromString(const std::string& version_str) { 19 Version* vers = new Version(); 20 if (vers->InitFromString(version_str)) 21 return vers; 22 delete vers; 23 return NULL; 24 } 25 Equals(const Version & that) const26bool Version::Equals(const Version& that) const { 27 return CompareTo(that) == 0; 28 } 29 CompareTo(const Version & other) const30int Version::CompareTo(const Version& other) const { 31 std::vector<uint16> other_components = other.components(); 32 size_t count = std::min(components_.size(), other_components.size()); 33 for (size_t i = 0; i < count; ++i) { 34 if (components_[i] > other_components[i]) 35 return 1; 36 if (components_[i] < other_components[i]) 37 return -1; 38 } 39 if (components_.size() > other_components.size()) { 40 for (size_t i = count; i < components_.size(); ++i) 41 if (components_[i] > 0) 42 return 1; 43 } else if (components_.size() < other_components.size()) { 44 for (size_t i = count; i < other_components.size(); ++i) 45 if (other_components[i] > 0) 46 return -1; 47 } 48 return 0; 49 } 50 GetString() const51const std::string Version::GetString() const { 52 std::string version_str; 53 int count = components_.size(); 54 for (int i = 0; i < count - 1; ++i) { 55 version_str.append(IntToString(components_[i])); 56 version_str.append("."); 57 } 58 version_str.append(IntToString(components_[count - 1])); 59 return version_str; 60 } 61 InitFromString(const std::string & version_str)62bool Version::InitFromString(const std::string& version_str) { 63 std::vector<std::string> numbers; 64 SplitString(version_str, '.', &numbers); 65 for (std::vector<std::string>::iterator i = numbers.begin(); 66 i != numbers.end(); ++i) { 67 int num; 68 if (!StringToInt(*i, &num)) 69 return false; 70 if (num < 0) 71 return false; 72 const uint16 max = 0xFFFF; 73 if (num > max) 74 return false; 75 // This throws out things like +3, or 032. 76 if (IntToString(num) != *i) 77 return false; 78 uint16 component = static_cast<uint16>(num); 79 components_.push_back(component); 80 } 81 return true; 82 } 83