1 
2 /**
3  *    Copyright (C) 2018-present MongoDB, Inc.
4  *
5  *    This program is free software: you can redistribute it and/or modify
6  *    it under the terms of the Server Side Public License, version 1,
7  *    as published by MongoDB, Inc.
8  *
9  *    This program is distributed in the hope that it will be useful,
10  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *    Server Side Public License for more details.
13  *
14  *    You should have received a copy of the Server Side Public License
15  *    along with this program. If not, see
16  *    <http://www.mongodb.com/licensing/server-side-public-license>.
17  *
18  *    As a special exception, the copyright holders give permission to link the
19  *    code of portions of this program with the OpenSSL library under certain
20  *    conditions as described in each individual source file and distribute
21  *    linked combinations including the program with the OpenSSL library. You
22  *    must comply with the Server Side Public License in all respects for
23  *    all of the code used other than as permitted herein. If you modify file(s)
24  *    with this exception, you may extend this exception to your version of the
25  *    file(s), but you are not obligated to do so. If you do not wish to do so,
26  *    delete this exception statement from your version. If you delete this
27  *    exception statement from all source files in the program, then also delete
28  *    it in the license file.
29  */
30 
31 #pragma once
32 
33 #include <cmath>
34 
35 #include "mongo/platform/decimal128.h"
36 #include "mongo/util/assert_util.h"
37 
38 namespace mongo {
39 
40 /**
41  * These functions compare numbers using the same rules as BSON. Care is taken to always give
42  * numerically correct results when comparing different types. Returns are always -1, 0, or 1 to
43  * ensure it is safe to negate the result to invert the direction of the comparison.
44  *
45  * lhs > rhs returns 1
46  * lhs < rhs returns -1
47  * lhs == rhs returns 0
48  *
49  */
50 
compareInts(int lhs,int rhs)51 inline int compareInts(int lhs, int rhs) {
52     return lhs == rhs ? 0 : lhs < rhs ? -1 : 1;
53 }
54 
compareLongs(long long lhs,long long rhs)55 inline int compareLongs(long long lhs, long long rhs) {
56     return lhs == rhs ? 0 : lhs < rhs ? -1 : 1;
57 }
58 
compareDoubles(double lhs,double rhs)59 inline int compareDoubles(double lhs, double rhs) {
60     if (lhs == rhs)
61         return 0;
62     if (lhs < rhs)
63         return -1;
64     if (lhs > rhs)
65         return 1;
66 
67     // If none of the above cases returned, lhs or rhs must be NaN.
68     if (std::isnan(lhs))
69         return std::isnan(rhs) ? 0 : -1;
70     dassert(std::isnan(rhs));
71     return 1;
72 }
73 
74 // This is the tricky one. Needs to support the following cases:
75 // * Doubles with a fractional component.
76 // * Longs that can't be precisely represented as a double.
77 // * Doubles outside of the range of Longs (including +/- Inf).
78 // * NaN (defined by us as less than all Longs)
79 // * Return value is always -1, 0, or 1 to ensure it is safe to negate.
compareLongToDouble(long long lhs,double rhs)80 inline int compareLongToDouble(long long lhs, double rhs) {
81     // All Longs are > NaN
82     if (std::isnan(rhs))
83         return 1;
84 
85     // Ints with magnitude <= 2**53 can be precisely represented as doubles.
86     // Additionally, doubles outside of this range can't have a fractional component.
87     static const long long kEndOfPreciseDoubles = 1ll << 53;
88     if (lhs <= kEndOfPreciseDoubles && lhs >= -kEndOfPreciseDoubles) {
89         return compareDoubles(lhs, rhs);
90     }
91 
92     // Large magnitude doubles (including +/- Inf) are strictly > or < all Longs.
93     static const double kBoundOfLongRange = -static_cast<double>(LLONG_MIN);  // positive 2**63
94     if (rhs >= kBoundOfLongRange)
95         return -1;  // Can't be represented in a Long.
96     if (rhs < -kBoundOfLongRange)
97         return 1;  // Can be represented in a Long.
98 
99     // Remaining Doubles can have their integer component precisely represented as long longs.
100     // If they have a fractional component, they must be strictly > or < lhs even after
101     // truncation of the fractional component since low-magnitude lhs were handled above.
102     return compareLongs(lhs, rhs);
103 }
104 
compareDoubleToLong(double lhs,long long rhs)105 inline int compareDoubleToLong(double lhs, long long rhs) {
106     // Only implement the real logic once.
107     return -compareLongToDouble(rhs, lhs);
108 }
109 
110 /** Decimal type comparisons
111  * These following cases need support:
112  * 1. decimal and decimal: directly compare (enforce ordering: NaN < -Inf < N < +Inf)
113  * 2. decimal and int: convert int to decimal and compare
114  * 3. decimal and long: convert long to decimal and compare
115  * 4. decimal to double: convert decimal to double with round toward negative.
116  *    Check for exact conversion and determine ordering based on result.
117  */
118 
119 // Case 1: Compare two decimal values, but enforce MongoDB's total ordering convention
compareDecimals(Decimal128 lhs,Decimal128 rhs)120 inline int compareDecimals(Decimal128 lhs, Decimal128 rhs) {
121     // When we're comparing, lhs is always a decimal, which means more often than not
122     // the rhs will be less than the lhs (decimal type has the largest capacity)
123     if (lhs.isGreater(rhs))
124         return 1;
125     if (lhs.isLess(rhs))
126         return -1;
127     if (lhs.isNaN())
128         return (rhs.isNaN() ? 0 : -1);
129     if (rhs.isNaN())
130         return 1;
131     else  // lhs is necessarily equal to rhs
132         return 0;
133 }
134 
135 // Compare decimal and int
compareDecimalToInt(Decimal128 lhs,int rhs)136 inline int compareDecimalToInt(Decimal128 lhs, int rhs) {
137     return compareDecimals(lhs, Decimal128(rhs));
138 }
139 
compareIntToDecimal(int lhs,Decimal128 rhs)140 inline int compareIntToDecimal(int lhs, Decimal128 rhs) {
141     return -compareDecimalToInt(rhs, lhs);
142 }
143 
144 // Compare decimal and long
compareDecimalToLong(Decimal128 lhs,long long rhs)145 inline int compareDecimalToLong(Decimal128 lhs, long long rhs) {
146     return compareDecimals(lhs, Decimal128(static_cast<int64_t>(rhs)));
147 }
148 
compareLongToDecimal(long long lhs,Decimal128 rhs)149 inline int compareLongToDecimal(long long lhs, Decimal128 rhs) {
150     return -compareDecimalToLong(rhs, lhs);
151 }
152 
153 // Compare decimal and double
compareDecimalToDouble(Decimal128 lhs,double rhs)154 inline int compareDecimalToDouble(Decimal128 lhs, double rhs) {
155     uint32_t sigFlags = Decimal128::SignalingFlag::kNoFlag;
156     double decToDouble = lhs.toDouble(&sigFlags, Decimal128::RoundingMode::kRoundTowardNegative);
157 
158     if (decToDouble == rhs) {
159         // If our conversion was not exact, lhs was necessarily greater than rhs
160         // otherwise, they are equal
161         if (Decimal128::hasFlag(sigFlags, Decimal128::SignalingFlag::kInexact)) {
162             return 1;
163         } else {
164             return 0;
165         }
166     } else if (decToDouble < rhs) {
167         return -1;
168     } else if (decToDouble > rhs) {
169         return 1;
170     }
171 
172     if (lhs.isNaN())
173         return (std::isnan(rhs) ? 0 : -1);
174     invariant(std::isnan(rhs));
175     return 1;
176 }
177 
compareDoubleToDecimal(double lhs,Decimal128 rhs)178 inline int compareDoubleToDecimal(double lhs, Decimal128 rhs) {
179     return -compareDecimalToDouble(rhs, lhs);
180 }
181 
182 }  // namespace mongo
183