| 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 if (den_ == that.den_) {
30 return num_ < that.num_;
31 } else if ((num_ >= 0) != (that.num_ >= 0)) {
32 return num_ < that.num_;
33 } else {
34 return AbsToUnsigned(num_) * that.den_ < AbsToUnsigned(that.num_) * den_;
35 }
36 }
37
38 uint64_t Rational::GetHash() const {
39 if (num_ == 0) {
40 return 0;
41 }
42 uint64_t gcd = std::gcd(num_, den_);
43 return ((num_ / gcd) << 32) | (den_ / gcd);
44 }
45
46 Rational Rational::Invert() const {
47 if (num_ >= 0) {
48 return Rational(den_, num_);
49 } else {
50 return Rational(-1 * static_cast<int32_t>(den_), std::abs(num_));
51 }
52 }
53
54 } // namespace impeller
impeller::Rational
Definition: rational.h:13
impeller::Rational::Invert
Rational Invert() const
Definition: rational.cc:46
impeller::Rational::Rational
constexpr Rational(int32_t num)
Definition: rational.h:15
impeller::Rational::operator<
bool operator<(const Rational &that) const
Definition: rational.cc:28
impeller::Rational::GetHash
uint64_t GetHash() const
Definition: rational.cc:38
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