• 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 "util/simple_fraction.h"
6 
7 #include <cmath>
8 #include <limits>
9 #include <vector>
10 
11 #include "absl/strings/str_cat.h"
12 #include "absl/strings/str_split.h"
13 #include "util/osp_logging.h"
14 
15 namespace openscreen {
16 
17 // static
FromString(absl::string_view value)18 ErrorOr<SimpleFraction> SimpleFraction::FromString(absl::string_view value) {
19   std::vector<absl::string_view> fields = absl::StrSplit(value, '/');
20   if (fields.size() != 1 && fields.size() != 2) {
21     return Error::Code::kParameterInvalid;
22   }
23 
24   int numerator;
25   int denominator = 1;
26   if (!absl::SimpleAtoi(fields[0], &numerator)) {
27     return Error::Code::kParameterInvalid;
28   }
29 
30   if (fields.size() == 2) {
31     if (!absl::SimpleAtoi(fields[1], &denominator)) {
32       return Error::Code::kParameterInvalid;
33     }
34   }
35 
36   return SimpleFraction{numerator, denominator};
37 }
38 
ToString() const39 std::string SimpleFraction::ToString() const {
40   if (denominator == 1) {
41     return std::to_string(numerator);
42   }
43   return absl::StrCat(numerator, "/", denominator);
44 }
45 
operator ==(const SimpleFraction & other) const46 bool SimpleFraction::operator==(const SimpleFraction& other) const {
47   return numerator == other.numerator && denominator == other.denominator;
48 }
49 
operator !=(const SimpleFraction & other) const50 bool SimpleFraction::operator!=(const SimpleFraction& other) const {
51   return !(*this == other);
52 }
53 
is_defined() const54 bool SimpleFraction::is_defined() const {
55   return denominator != 0;
56 }
57 
is_positive() const58 bool SimpleFraction::is_positive() const {
59   return is_defined() && (numerator >= 0) && (denominator > 0);
60 }
61 
operator double() const62 SimpleFraction::operator double() const {
63   if (denominator == 0) {
64     return nan("");
65   }
66   return static_cast<double>(numerator) / static_cast<double>(denominator);
67 }
68 
69 }  // namespace openscreen
70