| Flutter Impeller |

rational.cc
Go to the documentation of this file.
1 // Copyright 2013 The Flutter 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 "flutter/impeller/geometry/rational.h"
6
7 #include <cmath>
8 #include <cstdlib>
9 #include <numeric>
10
11 namespace impeller {
12 namespace {
13 uint32_t AbsToUnsigned(int32_t x) {
14 return static_cast<uint32_t>(std::abs(x));
15 }
16 } // namespace
17
18 bool Rational::operator==(const Rational& that) const {
19 if (den_ == that.den_) {
20 return num_ == that.num_;
21 } else if ((num_ >= 0) != (that.num_ >= 0)) {
22 return false;
23 } else {
24 return AbsToUnsigned(num_) * that.den_ == AbsToUnsigned(that.num_) * den_;
25 }
26 }
27
28 bool Rational::operator!=(const Rational& that) const {
29 return !(*this == that);
30 }
31
32 bool Rational::operator<(const Rational& that) const {
33 if (den_ == that.den_) {
34 return num_ < that.num_;
35 } else if ((num_ >= 0) != (that.num_ >= 0)) {
36 return num_ < that.num_;
37 } else {
38 return AbsToUnsigned(num_) * that.den_ < AbsToUnsigned(that.num_) * den_;
39 }
40 }
41
42 uint64_t Rational::GetHash() const {
43 if (num_ == 0) {
44 return 0;
45 }
46 uint64_t gcd = std::gcd(num_, den_);
47 return ((num_ / gcd) << 32) | (den_ / gcd);
48 }
49
50 Rational Rational::Invert() const {
51 if (num_ >= 0) {
52 return Rational(den_, num_);
53 } else {
54 return Rational(-1 * static_cast<int32_t>(den_), std::abs(num_));
55 }
56 }
57
58 } // namespace impeller
impeller::Rational
Definition: rational.h:13
impeller::Rational::operator!=
bool operator!=(const Rational &that) const
Definition: rational.cc:28
impeller::Rational::Invert
Rational Invert() const
Definition: rational.cc:50
impeller::Rational::Rational
constexpr Rational(int32_t num)
Definition: rational.h:15
impeller::Rational::operator<
bool operator<(const Rational &that) const
Definition: rational.cc:32
impeller::Rational::GetHash
uint64_t GetHash() const
Definition: rational.cc:42
impeller::Rational::operator==
bool operator==(const Rational &that) const
Definition: rational.cc:18
x
int32_t x
Definition: dl_golden_unittests.cc:458
impeller
Definition: allocation.cc:12
rational.h