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 <string> 9 10 #include "absl/strings/string_view.h" 11 #include "platform/base/error.h" 12 13 namespace openscreen { 14 15 // SimpleFraction is used to represent simple (or "common") fractions, composed 16 // of a rational number written a/b where a and b are both integers. 17 18 // Note: Since SimpleFraction is a trivial type, it comes with a 19 // default constructor and is copyable, as well as allowing static 20 // initialization. 21 22 // Some helpful notes on SimpleFraction assumptions/limitations: 23 // 1. SimpleFraction does not perform reductions. 2/4 != 1/2, and -1/-1 != 1/1. 24 // 2. denominator = 0 is considered undefined. 25 // 3. numerator = saturates range to int min or int max 26 // 4. A SimpleFraction is "positive" if and only if it is defined and at least 27 // equal to zero. Since reductions are not performed, -1/-1 is negative. 28 struct SimpleFraction { 29 static ErrorOr<SimpleFraction> FromString(absl::string_view value); 30 std::string ToString() const; 31 32 bool operator==(const SimpleFraction& other) const; 33 bool operator!=(const SimpleFraction& other) const; 34 35 bool is_defined() const; 36 bool is_positive() const; 37 explicit operator double() const; 38 39 int numerator = 0; 40 int denominator = 0; 41 }; 42 43 } // namespace openscreen 44 45 #endif // UTIL_SIMPLE_FRACTION_H_ 46