Debian Codegraph @

common/types/overflow.go

raw
1 // Copyright 2021 Google LLC
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package types
16
17 import (
18 "math"
19 "time"
20 )
21
22 var (
23 doubleTwoTo64 = math.Ldexp(1.0, 64)
24 )
25
26 // addInt64Checked performs addition with overflow detection of two int64 values.
27 //
28 // If the operation fails the error return value will be non-nil.
29 func addInt64Checked(x, y int64) (int64, error) {
30 if (y > 0 && x > math.MaxInt64-y) || (y < 0 && x < math.MinInt64-y) {
31 return 0, errIntOverflow
32 }
33 return x + y, nil
34 }
35
36 // subtractInt64Checked performs subtraction with overflow detection of two int64 values.
37 //
38 // If the operation fails the error return value will be non-nil.
39 func subtractInt64Checked(x, y int64) (int64, error) {
40 if (y < 0 && x > math.MaxInt64+y) || (y > 0 && x < math.MinInt64+y) {
41 return 0, errIntOverflow
42 }
43 return x - y, nil
44 }
45
46 // negateInt64Checked performs negation with overflow detection of an int64.
47 //
48 // If the operation fails the error return value will be non-nil.
49 func negateInt64Checked(x int64) (int64, error) {
50 // In twos complement, negating MinInt64 would result in a valid of MaxInt64+1.
51 if x == math.MinInt64 {
52 return 0, errIntOverflow
53 }
54 return -x, nil
55 }
56
57 // multiplyInt64Checked performs multiplication with overflow detection of two int64 value.
58 //
59 // If the operation fails the error return value will be non-nil.
60 func multiplyInt64Checked(x, y int64) (int64, error) {
61 // Detecting multiplication overflow is more complicated than the others. The first two detect
62 // attempting to negate MinInt64, which would result in MaxInt64+1. The other four detect normal
63 // overflow conditions.
64 if (x == -1 && y == math.MinInt64) || (y == -1 && x == math.MinInt64) ||
65 // x is positive, y is positive
66 (x > 0 && y > 0 && x > math.MaxInt64/y) ||
67 // x is positive, y is negative
68 (x > 0 && y < 0 && y < math.MinInt64/x) ||
69 // x is negative, y is positive
70 (x < 0 && y > 0 && x < math.MinInt64/y) ||
71 // x is negative, y is negative
72 (x < 0 && y < 0 && y < math.MaxInt64/x) {
73 return 0, errIntOverflow
74 }
75 return x * y, nil
76 }
77
78 // divideInt64Checked performs division with overflow detection of two int64 values,
79 // as well as a division by zero check.
80 //
81 // If the operation fails the error return value will be non-nil.
82 func divideInt64Checked(x, y int64) (int64, error) {
83 // Division by zero.
84 if y == 0 {
85 return 0, errDivideByZero
86 }
87 // In twos complement, negating MinInt64 would result in a valid of MaxInt64+1.
88 if x == math.MinInt64 && y == -1 {
89 return 0, errIntOverflow
90 }
91 return x / y, nil
92 }
93
94 // moduloInt64Checked performs modulo with overflow detection of two int64 values
95 // as well as a modulus by zero check.
96 //
97 // If the operation fails the error return value will be non-nil.
98 func moduloInt64Checked(x, y int64) (int64, error) {
99 // Modulus by zero.
100 if y == 0 {
101 return 0, errModulusByZero
102 }
103 // In twos complement, negating MinInt64 would result in a valid of MaxInt64+1.
104 if x == math.MinInt64 && y == -1 {
105 return 0, errIntOverflow
106 }
107 return x % y, nil
108 }
109
110 // addUint64Checked performs addition with overflow detection of two uint64 values.
111 //
112 // If the operation fails due to overflow the error return value will be non-nil.
113 func addUint64Checked(x, y uint64) (uint64, error) {
114 if y > 0 && x > math.MaxUint64-y {
115 return 0, errUintOverflow
116 }
117 return x + y, nil
118 }
119
120 // subtractUint64Checked performs subtraction with overflow detection of two uint64 values.
121 //
122 // If the operation fails due to overflow the error return value will be non-nil.
123 func subtractUint64Checked(x, y uint64) (uint64, error) {
124 if y > x {
125 return 0, errUintOverflow
126 }
127 return x - y, nil
128 }
129
130 // multiplyUint64Checked performs multiplication with overflow detection of two uint64 values.
131 //
132 // If the operation fails due to overflow the error return value will be non-nil.
133 func multiplyUint64Checked(x, y uint64) (uint64, error) {
134 if y != 0 && x > math.MaxUint64/y {
135 return 0, errUintOverflow
136 }
137 return x * y, nil
138 }
139
140 // divideUint64Checked performs division with a test for division by zero.
141 //
142 // If the operation fails the error return value will be non-nil.
143 func divideUint64Checked(x, y uint64) (uint64, error) {
144 if y == 0 {
145 return 0, errDivideByZero
146 }
147 return x / y, nil
148 }
149
150 // moduloUint64Checked performs modulo with a test for modulus by zero.
151 //
152 // If the operation fails the error return value will be non-nil.
153 func moduloUint64Checked(x, y uint64) (uint64, error) {
154 if y == 0 {
155 return 0, errModulusByZero
156 }
157 return x % y, nil
158 }
159
160 // addDurationChecked performs addition with overflow detection of two time.Durations.
161 //
162 // If the operation fails due to overflow the error return value will be non-nil.
163 func addDurationChecked(x, y time.Duration) (time.Duration, error) {
164 val, err := addInt64Checked(int64(x), int64(y))
165 if err != nil {
166 return time.Duration(0), err
167 }
168 return time.Duration(val), nil
169 }
170
171 // subtractDurationChecked performs subtraction with overflow detection of two time.Durations.
172 //
173 // If the operation fails due to overflow the error return value will be non-nil.
174 func subtractDurationChecked(x, y time.Duration) (time.Duration, error) {
175 val, err := subtractInt64Checked(int64(x), int64(y))
176 if err != nil {
177 return time.Duration(0), err
178 }
179 return time.Duration(val), nil
180 }
181
182 // negateDurationChecked performs negation with overflow detection of a time.Duration.
183 //
184 // If the operation fails due to overflow the error return value will be non-nil.
185 func negateDurationChecked(x time.Duration) (time.Duration, error) {
186 val, err := negateInt64Checked(int64(x))
187 if err != nil {
188 return time.Duration(0), err
189 }
190 return time.Duration(val), nil
191 }
192
193 // addDurationChecked performs addition with overflow detection of a time.Time and time.Duration.
194 //
195 // If the operation fails due to overflow the error return value will be non-nil.
196 func addTimeDurationChecked(x time.Time, y time.Duration) (time.Time, error) {
197 // This is tricky. A time is represented as (int64, int32) where the first is seconds and second
198 // is nanoseconds. A duration is int64 representing nanoseconds. We cannot normalize time to int64
199 // as it could potentially overflow. The only way to proceed is to break time and duration into
200 // second and nanosecond components.
201
202 // First we break time into its components by truncating and subtracting.
203 sec1 := x.Truncate(time.Second).Unix() // Truncate to seconds.
204 nsec1 := x.Sub(x.Truncate(time.Second)).Nanoseconds() // Get nanoseconds by truncating and subtracting.
205
206 // Second we break duration into its components by dividing and modulo.
207 sec2 := int64(y) / int64(time.Second) // Truncate to seconds.
208 nsec2 := int64(y) % int64(time.Second) // Get remainder.
209
210 // Add seconds first, detecting any overflow.
211 sec, err := addInt64Checked(sec1, sec2)
212 if err != nil {
213 return time.Time{}, err
214 }
215 // Nanoseconds cannot overflow as time.Time normalizes them to [0, 999999999].
216 nsec := nsec1 + nsec2
217
218 // We need to normalize nanoseconds to be positive and carry extra nanoseconds to seconds.
219 // Adapted from time.Unix(int64, int64).
220 if nsec < 0 || nsec >= int64(time.Second) {
221 // Add seconds.
222 sec, err = addInt64Checked(sec, nsec/int64(time.Second))
223 if err != nil {
224 return time.Time{}, err
225 }
226
227 nsec -= (nsec / int64(time.Second)) * int64(time.Second)
228 if nsec < 0 {
229 // Subtract an extra second
230 sec, err = addInt64Checked(sec, -1)
231 if err != nil {
232 return time.Time{}, err
233 }
234 nsec += int64(time.Second)
235 }
236 }
237
238 // Check if the the number of seconds from Unix epoch is within our acceptable range.
239 if sec < minUnixTime || sec > maxUnixTime {
240 return time.Time{}, errTimestampOverflow
241 }
242
243 // Return resulting time and propagate time zone.
244 return time.Unix(sec, nsec).In(x.Location()), nil
245 }
246
247 // subtractTimeChecked performs subtraction with overflow detection of two time.Time.
248 //
249 // If the operation fails due to overflow the error return value will be non-nil.
250 func subtractTimeChecked(x, y time.Time) (time.Duration, error) {
251 // Similar to addTimeDurationOverflow() above.
252
253 // First we break time into its components by truncating and subtracting.
254 sec1 := x.Truncate(time.Second).Unix() // Truncate to seconds.
255 nsec1 := x.Sub(x.Truncate(time.Second)).Nanoseconds() // Get nanoseconds by truncating and subtracting.
256
257 // Second we break duration into its components by truncating and subtracting.
258 sec2 := y.Truncate(time.Second).Unix() // Truncate to seconds.
259 nsec2 := y.Sub(y.Truncate(time.Second)).Nanoseconds() // Get nanoseconds by truncating and subtracting.
260
261 // Subtract seconds first, detecting any overflow.
262 sec, err := subtractInt64Checked(sec1, sec2)
263 if err != nil {
264 return time.Duration(0), err
265 }
266
267 // Nanoseconds cannot overflow as time.Time normalizes them to [0, 999999999].
268 nsec := nsec1 - nsec2
269
270 // Scale seconds to nanoseconds detecting overflow.
271 tsec, err := multiplyInt64Checked(sec, int64(time.Second))
272 if err != nil {
273 return time.Duration(0), err
274 }
275
276 // Lastly we need to add the two nanoseconds together.
277 val, err := addInt64Checked(tsec, nsec)
278 if err != nil {
279 return time.Duration(0), err
280 }
281
282 return time.Duration(val), nil
283 }
284
285 // subtractTimeDurationChecked performs subtraction with overflow detection of a time.Time and
286 // time.Duration.
287 //
288 // If the operation fails due to overflow the error return value will be non-nil.
289 func subtractTimeDurationChecked(x time.Time, y time.Duration) (time.Time, error) {
290 // The easiest way to implement this is to negate y and add them.
291 // x - y = x + -y
292 val, err := negateDurationChecked(y)
293 if err != nil {
294 return time.Time{}, err
295 }
296 return addTimeDurationChecked(x, val)
297 }
298
299 // doubleToInt64Checked converts a double to an int64 value.
300 //
301 // If the conversion fails due to overflow the error return value will be non-nil.
302 func doubleToInt64Checked(v float64) (int64, error) {
303 if math.IsInf(v, 0) || math.IsNaN(v) || v <= float64(math.MinInt64) || v >= float64(math.MaxInt64) {
304 return 0, errIntOverflow
305 }
306 return int64(v), nil
307 }
308
309 // doubleToInt64Checked converts a double to a uint64 value.
310 //
311 // If the conversion fails due to overflow the error return value will be non-nil.
312 func doubleToUint64Checked(v float64) (uint64, error) {
313 if math.IsInf(v, 0) || math.IsNaN(v) || v < 0 || v >= doubleTwoTo64 {
314 return 0, errUintOverflow
315 }
316 return uint64(v), nil
317 }
318
319 // int64ToUint64Checked converts an int64 to a uint64 value.
320 //
321 // If the conversion fails due to overflow the error return value will be non-nil.
322 func int64ToUint64Checked(v int64) (uint64, error) {
323 if v < 0 {
324 return 0, errUintOverflow
325 }
326 return uint64(v), nil
327 }
328
329 // int64ToInt8Checked converts an int64 to an int8 value.
330 //
331 // If the conversion fails due to overflow the error return value will be non-nil.
332 func int64ToInt8Checked(v int64) (int8, error) {
333 if v < math.MinInt8 || v > math.MaxInt8 {
334 return 0, errIntOverflow
335 }
336 return int8(v), nil
337 }
338
339 // int64ToInt16Checked converts an int64 to an int16 value.
340 //
341 // If the conversion fails due to overflow the error return value will be non-nil.
342 func int64ToInt16Checked(v int64) (int16, error) {
343 if v < math.MinInt16 || v > math.MaxInt16 {
344 return 0, errIntOverflow
345 }
346 return int16(v), nil
347 }
348
349 // int64ToInt32Checked converts an int64 to an int32 value.
350 //
351 // If the conversion fails due to overflow the error return value will be non-nil.
352 func int64ToInt32Checked(v int64) (int32, error) {
353 if v < math.MinInt32 || v > math.MaxInt32 {
354 return 0, errIntOverflow
355 }
356 return int32(v), nil
357 }
358
359 // uint64ToUint8Checked converts a uint64 to a uint8 value.
360 //
361 // If the conversion fails due to overflow the error return value will be non-nil.
362 func uint64ToUint8Checked(v uint64) (uint8, error) {
363 if v > math.MaxUint8 {
364 return 0, errUintOverflow
365 }
366 return uint8(v), nil
367 }
368
369 // uint64ToUint16Checked converts a uint64 to a uint16 value.
370 //
371 // If the conversion fails due to overflow the error return value will be non-nil.
372 func uint64ToUint16Checked(v uint64) (uint16, error) {
373 if v > math.MaxUint16 {
374 return 0, errUintOverflow
375 }
376 return uint16(v), nil
377 }
378
379 // uint64ToUint32Checked converts a uint64 to a uint32 value.
380 //
381 // If the conversion fails due to overflow the error return value will be non-nil.
382 func uint64ToUint32Checked(v uint64) (uint32, error) {
383 if v > math.MaxUint32 {
384 return 0, errUintOverflow
385 }
386 return uint32(v), nil
387 }
388
389 // uint64ToInt64Checked converts a uint64 to an int64 value.
390 //
391 // If the conversion fails due to overflow the error return value will be non-nil.
392 func uint64ToInt64Checked(v uint64) (int64, error) {
393 if v > math.MaxInt64 {
394 return 0, errIntOverflow
395 }
396 return int64(v), nil
397 }
398
399 func doubleToUint64Lossless(v float64) (uint64, bool) {
400 u, err := doubleToUint64Checked(v)
401 if err != nil {
402 return 0, false
403 }
404 if float64(u) != v {
405 return 0, false
406 }
407 return u, true
408 }
409
410 func doubleToInt64Lossless(v float64) (int64, bool) {
411 i, err := doubleToInt64Checked(v)
412 if err != nil {
413 return 0, false
414 }
415 if float64(i) != v {
416 return 0, false
417 }
418 return i, true
419 }
420
421 func int64ToUint64Lossless(v int64) (uint64, bool) {
422 u, err := int64ToUint64Checked(v)
423 return u, err == nil
424 }
425
426 func uint64ToInt64Lossless(v uint64) (int64, bool) {
427 i, err := uint64ToInt64Checked(v)
428 return i, err == nil
429 }