• 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 #ifndef UTIL_SIMPLE_FRACTION_H_
6 #define UTIL_SIMPLE_FRACTION_H_
7 
8 #include <cmath>
9 #include <limits>
10 #include <string>
11 
12 #include "absl/strings/string_view.h"
13 #include "platform/base/error.h"
14 
15 namespace openscreen {
16 
17 // SimpleFraction is used to represent simple (or "common") fractions, composed
18 // of a rational number written a/b where a and b are both integers.
19 // Some helpful notes on SimpleFraction assumptions/limitations:
20 // 1. SimpleFraction does not perform reductions. 2/4 != 1/2, and -1/-1 != 1/1.
21 // 2. denominator = 0 is considered undefined.
22 // 3. numerator = saturates range to int min or int max
23 // 4. A SimpleFraction is "positive" if and only if it is defined and at least
24 //    equal to zero. Since reductions are not performed, -1/-1 is negative.
25 class SimpleFraction {
26  public:
27   static ErrorOr<SimpleFraction> FromString(absl::string_view value);
28   std::string ToString() const;
29 
30   constexpr SimpleFraction() = default;
SimpleFraction(int numerator)31   constexpr SimpleFraction(int numerator)  // NOLINT
32       : numerator_(numerator) {}
SimpleFraction(int numerator,int denominator)33   constexpr SimpleFraction(int numerator, int denominator)
34       : numerator_(numerator), denominator_(denominator) {}
35 
36   constexpr SimpleFraction(const SimpleFraction&) = default;
37   constexpr SimpleFraction(SimpleFraction&&) noexcept = default;
38   constexpr SimpleFraction& operator=(const SimpleFraction&) = default;
39   constexpr SimpleFraction& operator=(SimpleFraction&&) = default;
40   ~SimpleFraction() = default;
41 
42   constexpr bool operator==(const SimpleFraction& other) const {
43     return numerator_ == other.numerator_ && denominator_ == other.denominator_;
44   }
45 
46   constexpr bool operator!=(const SimpleFraction& other) const {
47     return !(*this == other);
48   }
49 
is_defined()50   constexpr bool is_defined() const { return denominator_ != 0; }
51 
is_positive()52   constexpr bool is_positive() const {
53     return (numerator_ >= 0) && (denominator_ > 0);
54   }
55 
56   constexpr explicit operator double() const {
57     if (denominator_ == 0) {
58       return nan("");
59     }
60     return static_cast<double>(numerator_) / static_cast<double>(denominator_);
61   }
62 
numerator()63   constexpr int numerator() const { return numerator_; }
denominator()64   constexpr int denominator() const { return denominator_; }
65 
66  private:
67   int numerator_ = 0;
68   int denominator_ = 1;
69 };
70 
71 }  // namespace openscreen
72 
73 #endif  // UTIL_SIMPLE_FRACTION_H_
74