1/*
2 * Copyright (C) 2011 Apple Inc. All rights reserved.
3 *
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions
6 * are met:
7 * 1. Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * 2. Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 *
13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26#ifndef CheckedArithmetic_h
27#define CheckedArithmetic_h
28
29#include <wtf/Assertions.h>
30
31#include <limits>
32#include <stdint.h>
33#include <type_traits>
34
35/* Checked<T>
36 *
37 * This class provides a mechanism to perform overflow-safe integer arithmetic
38 * without having to manually ensure that you have all the required bounds checks
39 * directly in your code.
40 *
41 * There are two modes of operation:
42 * - The default is Checked<T, CrashOnOverflow>, and crashes at the point
43 * and overflow has occurred.
44 * - The alternative is Checked<T, RecordOverflow>, which uses an additional
45 * byte of storage to track whether an overflow has occurred, subsequent
46 * unchecked operations will crash if an overflow has occured
47 *
48 * It is possible to provide a custom overflow handler, in which case you need
49 * to support these functions:
50 * - void overflowed();
51 * This function is called when an operation has produced an overflow.
52 * - bool hasOverflowed();
53 * This function must return true if overflowed() has been called on an
54 * instance and false if it has not.
55 * - void clearOverflow();
56 * Used to reset overflow tracking when a value is being overwritten with
57 * a new value.
58 *
59 * Checked<T> works for all integer types, with the following caveats:
60 * - Mixing signedness of operands is only supported for types narrower than
61 * 64bits.
62 * - It does have a performance impact, so tight loops may want to be careful
63 * when using it.
64 *
65 */
66
67namespace WTF {
68
69enum class CheckedState {
70 DidOverflow,
71 DidNotOverflow
72};
73
74class CrashOnOverflow {
75public:
76 static NO_RETURN_DUE_TO_CRASH void overflowed()
77 {
78 crash();
79 }
80
81 void clearOverflow() { }
82
83 static NO_RETURN_DUE_TO_CRASH void crash()
84 {
85 CRASH();
86 }
87
88public:
89 bool hasOverflowed() const { return false; }
90};
91
92class RecordOverflow {
93protected:
94 RecordOverflow()
95 : m_overflowed(false)
96 {
97 }
98
99 void overflowed()
100 {
101 m_overflowed = true;
102 }
103
104 void clearOverflow()
105 {
106 m_overflowed = false;
107 }
108
109 static NO_RETURN_DUE_TO_CRASH void crash()
110 {
111 CRASH();
112 }
113
114public:
115 bool hasOverflowed() const { return m_overflowed; }
116
117private:
118 unsigned char m_overflowed;
119};
120
121template <typename T, class OverflowHandler = CrashOnOverflow> class Checked;
122template <typename T> struct RemoveChecked;
123template <typename T> struct RemoveChecked<Checked<T>>;
124
125template <typename Target, typename Source, bool isTargetBigger = sizeof(Target) >= sizeof(Source), bool targetSigned = std::numeric_limits<Target>::is_signed, bool sourceSigned = std::numeric_limits<Source>::is_signed> struct BoundsChecker;
126template <typename Target, typename Source> struct BoundsChecker<Target, Source, false, false, false> {
127 static bool inBounds(Source value)
128 {
129 // Same signedness so implicit type conversion will always increase precision to widest type.
130 return value <= std::numeric_limits<Target>::max();
131 }
132};
133template <typename Target, typename Source> struct BoundsChecker<Target, Source, false, true, true> {
134 static bool inBounds(Source value)
135 {
136 // Same signedness so implicit type conversion will always increase precision to widest type.
137 return std::numeric_limits<Target>::min() <= value && value <= std::numeric_limits<Target>::max();
138 }
139};
140
141template <typename Target, typename Source> struct BoundsChecker<Target, Source, false, false, true> {
142 static bool inBounds(Source value)
143 {
144 // When converting value to unsigned Source, value will become a big value if value is negative.
145 // Casted value will become bigger than Target::max as Source is bigger than Target.
146 return static_cast<typename std::make_unsigned<Source>::type>(value) <= std::numeric_limits<Target>::max();
147 }
148};
149
150template <typename Target, typename Source> struct BoundsChecker<Target, Source, false, true, false> {
151 static bool inBounds(Source value)
152 {
153 // The unsigned Source type has greater precision than the target so max(Target) -> Source will widen.
154 return value <= static_cast<Source>(std::numeric_limits<Target>::max());
155 }
156};
157
158template <typename Target, typename Source> struct BoundsChecker<Target, Source, true, false, false> {
159 static bool inBounds(Source)
160 {
161 // Same sign, greater or same precision.
162 return true;
163 }
164};
165
166template <typename Target, typename Source> struct BoundsChecker<Target, Source, true, true, true> {
167 static bool inBounds(Source)
168 {
169 // Same sign, greater or same precision.
170 return true;
171 }
172};
173
174template <typename Target, typename Source> struct BoundsChecker<Target, Source, true, true, false> {
175 static bool inBounds(Source value)
176 {
177 // Target is signed with greater or same precision. If strictly greater, it is always safe.
178 if (sizeof(Target) > sizeof(Source))
179 return true;
180 return value <= static_cast<Source>(std::numeric_limits<Target>::max());
181 }
182};
183
184template <typename Target, typename Source> struct BoundsChecker<Target, Source, true, false, true> {
185 static bool inBounds(Source value)
186 {
187 // Target is unsigned with greater precision.
188 return value >= 0;
189 }
190};
191
192template <typename Target, typename Source> static inline bool isInBounds(Source value)
193{
194 return BoundsChecker<Target, Source>::inBounds(value);
195}
196
197template <typename Target, typename Source> static inline bool convertSafely(Source input, Target& output)
198{
199 if (!isInBounds<Target>(input))
200 return false;
201 output = static_cast<Target>(input);
202 return true;
203}
204
205template <typename T> struct RemoveChecked {
206 typedef T CleanType;
207 static const CleanType DefaultValue = 0;
208};
209
210template <typename T> struct RemoveChecked<Checked<T, CrashOnOverflow>> {
211 typedef typename RemoveChecked<T>::CleanType CleanType;
212 static const CleanType DefaultValue = 0;
213};
214
215template <typename T> struct RemoveChecked<Checked<T, RecordOverflow>> {
216 typedef typename RemoveChecked<T>::CleanType CleanType;
217 static const CleanType DefaultValue = 0;
218};
219
220// The ResultBase and SignednessSelector are used to workaround typeof not being
221// available in MSVC
222template <typename U, typename V, bool uIsBigger = (sizeof(U) > sizeof(V)), bool sameSize = (sizeof(U) == sizeof(V))> struct ResultBase;
223template <typename U, typename V> struct ResultBase<U, V, true, false> {
224 typedef U ResultType;
225};
226
227template <typename U, typename V> struct ResultBase<U, V, false, false> {
228 typedef V ResultType;
229};
230
231template <typename U> struct ResultBase<U, U, false, true> {
232 typedef U ResultType;
233};
234
235template <typename U, typename V, bool uIsSigned = std::numeric_limits<U>::is_signed, bool vIsSigned = std::numeric_limits<V>::is_signed> struct SignednessSelector;
236template <typename U, typename V> struct SignednessSelector<U, V, true, true> {
237 typedef U ResultType;
238};
239
240template <typename U, typename V> struct SignednessSelector<U, V, false, false> {
241 typedef U ResultType;
242};
243
244template <typename U, typename V> struct SignednessSelector<U, V, true, false> {
245 typedef V ResultType;
246};
247
248template <typename U, typename V> struct SignednessSelector<U, V, false, true> {
249 typedef U ResultType;
250};
251
252template <typename U, typename V> struct ResultBase<U, V, false, true> {
253 typedef typename SignednessSelector<U, V>::ResultType ResultType;
254};
255
256template <typename U, typename V> struct Result : ResultBase<typename RemoveChecked<U>::CleanType, typename RemoveChecked<V>::CleanType> {
257};
258
259template <typename LHS, typename RHS, typename ResultType = typename Result<LHS, RHS>::ResultType,
260 bool lhsSigned = std::numeric_limits<LHS>::is_signed, bool rhsSigned = std::numeric_limits<RHS>::is_signed> struct ArithmeticOperations;
261
262template <typename LHS, typename RHS, typename ResultType> struct ArithmeticOperations<LHS, RHS, ResultType, true, true> {
263 // LHS and RHS are signed types
264
265 // Helper function
266 static inline bool signsMatch(LHS lhs, RHS rhs)
267 {
268 return (lhs ^ rhs) >= 0;
269 }
270
271 static inline bool add(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
272 {
273 if (signsMatch(lhs, rhs)) {
274 if (lhs >= 0) {
275 if ((std::numeric_limits<ResultType>::max() - rhs) < lhs)
276 return false;
277 } else {
278 ResultType temp = lhs - std::numeric_limits<ResultType>::min();
279 if (rhs < -temp)
280 return false;
281 }
282 } // if the signs do not match this operation can't overflow
283 result = lhs + rhs;
284 return true;
285 }
286
287 static inline bool sub(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
288 {
289 if (!signsMatch(lhs, rhs)) {
290 if (lhs >= 0) {
291 if (lhs > std::numeric_limits<ResultType>::max() + rhs)
292 return false;
293 } else {
294 if (rhs > std::numeric_limits<ResultType>::max() + lhs)
295 return false;
296 }
297 } // if the signs match this operation can't overflow
298 result = lhs - rhs;
299 return true;
300 }
301
302 static inline bool multiply(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
303 {
304 if (signsMatch(lhs, rhs)) {
305 if (lhs >= 0) {
306 if (lhs && (std::numeric_limits<ResultType>::max() / lhs) < rhs)
307 return false;
308 } else {
309 if (static_cast<ResultType>(lhs) == std::numeric_limits<ResultType>::min() || static_cast<ResultType>(rhs) == std::numeric_limits<ResultType>::min())
310 return false;
311 if ((std::numeric_limits<ResultType>::max() / -lhs) < -rhs)
312 return false;
313 }
314 } else {
315 if (lhs < 0) {
316 if (rhs && lhs < (std::numeric_limits<ResultType>::min() / rhs))
317 return false;
318 } else {
319 if (lhs && rhs < (std::numeric_limits<ResultType>::min() / lhs))
320 return false;
321 }
322 }
323 result = lhs * rhs;
324 return true;
325 }
326
327 static inline bool equals(LHS lhs, RHS rhs) { return lhs == rhs; }
328
329};
330
331template <typename LHS, typename RHS, typename ResultType> struct ArithmeticOperations<LHS, RHS, ResultType, false, false> {
332 // LHS and RHS are unsigned types so bounds checks are nice and easy
333 static inline bool add(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
334 {
335 ResultType temp = lhs + rhs;
336 if (temp < lhs)
337 return false;
338 result = temp;
339 return true;
340 }
341
342 static inline bool sub(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
343 {
344 ResultType temp = lhs - rhs;
345 if (temp > lhs)
346 return false;
347 result = temp;
348 return true;
349 }
350
351 static inline bool multiply(LHS lhs, RHS rhs, ResultType& result) WARN_UNUSED_RETURN
352 {
353 if (!lhs || !rhs) {
354 result = 0;
355 return true;
356 }
357 if (std::numeric_limits<ResultType>::max() / lhs < rhs)
358 return false;
359 result = lhs * rhs;
360 return true;
361 }
362
363 static inline bool equals(LHS lhs, RHS rhs) { return lhs == rhs; }
364
365};
366
367template <typename ResultType> struct ArithmeticOperations<int, unsigned, ResultType, true, false> {
368 static inline bool add(int64_t lhs, int64_t rhs, ResultType& result)
369 {
370 int64_t temp = lhs + rhs;
371 if (temp < std::numeric_limits<ResultType>::min())
372 return false;
373 if (temp > std::numeric_limits<ResultType>::max())
374 return false;
375 result = static_cast<ResultType>(temp);
376 return true;
377 }
378
379 static inline bool sub(int64_t lhs, int64_t rhs, ResultType& result)
380 {
381 int64_t temp = lhs - rhs;
382 if (temp < std::numeric_limits<ResultType>::min())
383 return false;
384 if (temp > std::numeric_limits<ResultType>::max())
385 return false;
386 result = static_cast<ResultType>(temp);
387 return true;
388 }
389
390 static inline bool multiply(int64_t lhs, int64_t rhs, ResultType& result)
391 {
392 int64_t temp = lhs * rhs;
393 if (temp < std::numeric_limits<ResultType>::min())
394 return false;
395 if (temp > std::numeric_limits<ResultType>::max())
396 return false;
397 result = static_cast<ResultType>(temp);
398 return true;
399 }
400
401 static inline bool equals(int lhs, unsigned rhs)
402 {
403 return static_cast<int64_t>(lhs) == static_cast<int64_t>(rhs);
404 }
405};
406
407template <typename ResultType> struct ArithmeticOperations<unsigned, int, ResultType, false, true> {
408 static inline bool add(int64_t lhs, int64_t rhs, ResultType& result)
409 {
410 return ArithmeticOperations<int, unsigned, ResultType>::add(rhs, lhs, result);
411 }
412
413 static inline bool sub(int64_t lhs, int64_t rhs, ResultType& result)
414 {
415 return ArithmeticOperations<int, unsigned, ResultType>::sub(lhs, rhs, result);
416 }
417
418 static inline bool multiply(int64_t lhs, int64_t rhs, ResultType& result)
419 {
420 return ArithmeticOperations<int, unsigned, ResultType>::multiply(rhs, lhs, result);
421 }
422
423 static inline bool equals(unsigned lhs, int rhs)
424 {
425 return ArithmeticOperations<int, unsigned, ResultType>::equals(rhs, lhs);
426 }
427};
428
429template <typename U, typename V, typename R> static inline bool safeAdd(U lhs, V rhs, R& result)
430{
431 return ArithmeticOperations<U, V, R>::add(lhs, rhs, result);
432}
433
434template <typename U, typename V, typename R> static inline bool safeSub(U lhs, V rhs, R& result)
435{
436 return ArithmeticOperations<U, V, R>::sub(lhs, rhs, result);
437}
438
439template <typename U, typename V, typename R> static inline bool safeMultiply(U lhs, V rhs, R& result)
440{
441 return ArithmeticOperations<U, V, R>::multiply(lhs, rhs, result);
442}
443
444template <typename U, typename V> static inline bool safeEquals(U lhs, V rhs)
445{
446 return ArithmeticOperations<U, V>::equals(lhs, rhs);
447}
448
449enum ResultOverflowedTag { ResultOverflowed };
450
451template <typename T, class OverflowHandler> class Checked : public OverflowHandler {
452public:
453 template <typename _T, class _OverflowHandler> friend class Checked;
454 Checked()
455 : m_value(0)
456 {
457 }
458
459 Checked(ResultOverflowedTag)
460 : m_value(0)
461 {
462 this->overflowed();
463 }
464
465 template <typename U> Checked(U value)
466 {
467 if (!isInBounds<T>(value))
468 this->overflowed();
469 m_value = static_cast<T>(value);
470 }
471
472 template <typename V> Checked(const Checked<T, V>& rhs)
473 : m_value(rhs.m_value)
474 {
475 if (rhs.hasOverflowed())
476 this->overflowed();
477 }
478
479 template <typename U> Checked(const Checked<U, OverflowHandler>& rhs)
480 : OverflowHandler(rhs)
481 {
482 if (!isInBounds<T>(rhs.m_value))
483 this->overflowed();
484 m_value = static_cast<T>(rhs.m_value);
485 }
486
487 template <typename U, typename V> Checked(const Checked<U, V>& rhs)
488 {
489 if (rhs.hasOverflowed())
490 this->overflowed();
491 if (!isInBounds<T>(rhs.m_value))
492 this->overflowed();
493 m_value = static_cast<T>(rhs.m_value);
494 }
495
496 const Checked& operator=(Checked rhs)
497 {
498 this->clearOverflow();
499 if (rhs.hasOverflowed())
500 this->overflowed();
501 m_value = static_cast<T>(rhs.m_value);
502 return *this;
503 }
504
505 template <typename U> const Checked& operator=(U value)
506 {
507 return *this = Checked(value);
508 }
509
510 template <typename U, typename V> const Checked& operator=(const Checked<U, V>& rhs)
511 {
512 return *this = Checked(rhs);
513 }
514
515 // prefix
516 const Checked& operator++()
517 {
518 if (m_value == std::numeric_limits<T>::max())
519 this->overflowed();
520 m_value++;
521 return *this;
522 }
523
524 const Checked& operator--()
525 {
526 if (m_value == std::numeric_limits<T>::min())
527 this->overflowed();
528 m_value--;
529 return *this;
530 }
531
532 // postfix operators
533 const Checked operator++(int)
534 {
535 if (m_value == std::numeric_limits<T>::max())
536 this->overflowed();
537 return Checked(m_value++);
538 }
539
540 const Checked operator--(int)
541 {
542 if (m_value == std::numeric_limits<T>::min())
543 this->overflowed();
544 return Checked(m_value--);
545 }
546
547 // Boolean operators
548 bool operator!() const
549 {
550 if (this->hasOverflowed())
551 this->crash();
552 return !m_value;
553 }
554
555 explicit operator bool() const
556 {
557 if (this->hasOverflowed())
558 this->crash();
559 return m_value;
560 }
561
562 // Value accessors. unsafeGet() will crash if there's been an overflow.
563 T unsafeGet() const
564 {
565 if (this->hasOverflowed())
566 this->crash();
567 return m_value;
568 }
569
570 inline CheckedState safeGet(T& value) const WARN_UNUSED_RETURN
571 {
572 value = m_value;
573 if (this->hasOverflowed())
574 return CheckedState::DidOverflow;
575 return CheckedState::DidNotOverflow;
576 }
577
578 // Mutating assignment
579 template <typename U> const Checked operator+=(U rhs)
580 {
581 if (!safeAdd(m_value, rhs, m_value))
582 this->overflowed();
583 return *this;
584 }
585
586 template <typename U> const Checked operator-=(U rhs)
587 {
588 if (!safeSub(m_value, rhs, m_value))
589 this->overflowed();
590 return *this;
591 }
592
593 template <typename U> const Checked operator*=(U rhs)
594 {
595 if (!safeMultiply(m_value, rhs, m_value))
596 this->overflowed();
597 return *this;
598 }
599
600 const Checked operator*=(double rhs)
601 {
602 double result = rhs * m_value;
603 // Handle +/- infinity and NaN
604 if (!(std::numeric_limits<T>::min() <= result && std::numeric_limits<T>::max() >= result))
605 this->overflowed();
606 m_value = (T)result;
607 return *this;
608 }
609
610 const Checked operator*=(float rhs)
611 {
612 return *this *= (double)rhs;
613 }
614
615 template <typename U, typename V> const Checked operator+=(Checked<U, V> rhs)
616 {
617 if (rhs.hasOverflowed())
618 this->overflowed();
619 return *this += rhs.m_value;
620 }
621
622 template <typename U, typename V> const Checked operator-=(Checked<U, V> rhs)
623 {
624 if (rhs.hasOverflowed())
625 this->overflowed();
626 return *this -= rhs.m_value;
627 }
628
629 template <typename U, typename V> const Checked operator*=(Checked<U, V> rhs)
630 {
631 if (rhs.hasOverflowed())
632 this->overflowed();
633 return *this *= rhs.m_value;
634 }
635
636 // Equality comparisons
637 template <typename V> bool operator==(Checked<T, V> rhs)
638 {
639 return unsafeGet() == rhs.unsafeGet();
640 }
641
642 template <typename U> bool operator==(U rhs)
643 {
644 if (this->hasOverflowed())
645 this->crash();
646 return safeEquals(m_value, rhs);
647 }
648
649 template <typename U, typename V> const Checked operator==(Checked<U, V> rhs)
650 {
651 return unsafeGet() == Checked(rhs.unsafeGet());
652 }
653
654 template <typename U> bool operator!=(U rhs)
655 {
656 return !(*this == rhs);
657 }
658
659 // Other comparisons
660 template <typename V> bool operator<(Checked<T, V> rhs) const
661 {
662 return unsafeGet() < rhs.unsafeGet();
663 }
664
665 bool operator<(T rhs) const
666 {
667 return unsafeGet() < rhs;
668 }
669
670 template <typename V> bool operator<=(Checked<T, V> rhs) const
671 {
672 return unsafeGet() <= rhs.unsafeGet();
673 }
674
675 bool operator<=(T rhs) const
676 {
677 return unsafeGet() <= rhs;
678 }
679
680 template <typename V> bool operator>(Checked<T, V> rhs) const
681 {
682 return unsafeGet() > rhs.unsafeGet();
683 }
684
685 bool operator>(T rhs) const
686 {
687 return unsafeGet() > rhs;
688 }
689
690 template <typename V> bool operator>=(Checked<T, V> rhs) const
691 {
692 return unsafeGet() >= rhs.unsafeGet();
693 }
694
695 bool operator>=(T rhs) const
696 {
697 return unsafeGet() >= rhs;
698 }
699
700private:
701 // Disallow implicit conversion of floating point to integer types
702 Checked(float);
703 Checked(double);
704 void operator=(float);
705 void operator=(double);
706 void operator+=(float);
707 void operator+=(double);
708 void operator-=(float);
709 void operator-=(double);
710 T m_value;
711};
712
713template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator+(Checked<U, OverflowHandler> lhs, Checked<V, OverflowHandler> rhs)
714{
715 U x = 0;
716 V y = 0;
717 bool overflowed = lhs.safeGet(x) == CheckedState::DidOverflow || rhs.safeGet(y) == CheckedState::DidOverflow;
718 typename Result<U, V>::ResultType result = 0;
719 overflowed |= !safeAdd(x, y, result);
720 if (overflowed)
721 return ResultOverflowed;
722 return result;
723}
724
725template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator-(Checked<U, OverflowHandler> lhs, Checked<V, OverflowHandler> rhs)
726{
727 U x = 0;
728 V y = 0;
729 bool overflowed = lhs.safeGet(x) == CheckedState::DidOverflow || rhs.safeGet(y) == CheckedState::DidOverflow;
730 typename Result<U, V>::ResultType result = 0;
731 overflowed |= !safeSub(x, y, result);
732 if (overflowed)
733 return ResultOverflowed;
734 return result;
735}
736
737template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator*(Checked<U, OverflowHandler> lhs, Checked<V, OverflowHandler> rhs)
738{
739 U x = 0;
740 V y = 0;
741 bool overflowed = lhs.safeGet(x) == CheckedState::DidOverflow || rhs.safeGet(y) == CheckedState::DidOverflow;
742 typename Result<U, V>::ResultType result = 0;
743 overflowed |= !safeMultiply(x, y, result);
744 if (overflowed)
745 return ResultOverflowed;
746 return result;
747}
748
749template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator+(Checked<U, OverflowHandler> lhs, V rhs)
750{
751 return lhs + Checked<V, OverflowHandler>(rhs);
752}
753
754template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator-(Checked<U, OverflowHandler> lhs, V rhs)
755{
756 return lhs - Checked<V, OverflowHandler>(rhs);
757}
758
759template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator*(Checked<U, OverflowHandler> lhs, V rhs)
760{
761 return lhs * Checked<V, OverflowHandler>(rhs);
762}
763
764template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator+(U lhs, Checked<V, OverflowHandler> rhs)
765{
766 return Checked<U, OverflowHandler>(lhs) + rhs;
767}
768
769template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator-(U lhs, Checked<V, OverflowHandler> rhs)
770{
771 return Checked<U, OverflowHandler>(lhs) - rhs;
772}
773
774template <typename U, typename V, typename OverflowHandler> static inline Checked<typename Result<U, V>::ResultType, OverflowHandler> operator*(U lhs, Checked<V, OverflowHandler> rhs)
775{
776 return Checked<U, OverflowHandler>(lhs) * rhs;
777}
778
779// Convenience typedefs.
780typedef Checked<int8_t, RecordOverflow> CheckedInt8;
781typedef Checked<uint8_t, RecordOverflow> CheckedUint8;
782typedef Checked<int16_t, RecordOverflow> CheckedInt16;
783typedef Checked<uint16_t, RecordOverflow> CheckedUint16;
784typedef Checked<int32_t, RecordOverflow> CheckedInt32;
785typedef Checked<uint32_t, RecordOverflow> CheckedUint32;
786typedef Checked<int64_t, RecordOverflow> CheckedInt64;
787typedef Checked<uint64_t, RecordOverflow> CheckedUint64;
788typedef Checked<size_t, RecordOverflow> CheckedSize;
789
790template<typename T, typename U>
791Checked<T, RecordOverflow> checkedSum(U value)
792{
793 return Checked<T, RecordOverflow>(value);
794}
795template<typename T, typename U, typename... Args>
796Checked<T, RecordOverflow> checkedSum(U value, Args... args)
797{
798 return Checked<T, RecordOverflow>(value) + checkedSum<T>(args...);
799}
800
801// Sometimes, you just want to check if some math would overflow - the code to do the math is
802// already in place, and you want to guard it.
803
804template<typename T, typename... Args> bool sumOverflows(Args... args)
805{
806 return checkedSum<T>(args...).hasOverflowed();
807}
808
809template<typename T, typename U> bool differenceOverflows(U left, U right)
810{
811 return (Checked<T, RecordOverflow>(left) - Checked<T, RecordOverflow>(right)).hasOverflowed();
812}
813
814template<typename T, typename U>
815Checked<T, RecordOverflow> checkedProduct(U value)
816{
817 return Checked<T, RecordOverflow>(value);
818}
819template<typename T, typename U, typename... Args>
820Checked<T, RecordOverflow> checkedProduct(U value, Args... args)
821{
822 return Checked<T, RecordOverflow>(value) * checkedProduct<T>(args...);
823}
824
825// Sometimes, you just want to check if some math would overflow - the code to do the math is
826// already in place, and you want to guard it.
827
828template<typename T, typename... Args> bool productOverflows(Args... args)
829{
830 return checkedProduct<T>(args...).hasOverflowed();
831}
832
833}
834
835using WTF::Checked;
836using WTF::CheckedState;
837using WTF::RecordOverflow;
838using WTF::CheckedInt8;
839using WTF::CheckedUint8;
840using WTF::CheckedInt16;
841using WTF::CheckedUint16;
842using WTF::CheckedInt32;
843using WTF::CheckedUint32;
844using WTF::CheckedInt64;
845using WTF::CheckedUint64;
846using WTF::CheckedSize;
847using WTF::checkedSum;
848using WTF::differenceOverflows;
849using WTF::productOverflows;
850using WTF::sumOverflows;
851
852#endif
853