OLD | NEW |
(Empty) | |
| 1 /* |
| 2 * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved. |
| 3 * |
| 4 * Use of this source code is governed by a BSD-style license |
| 5 * that can be found in the LICENSE file in the root of the source |
| 6 * tree. An additional intellectual property rights grant can be found |
| 7 * in the file PATENTS. All contributing project authors may |
| 8 * be found in the AUTHORS file in the root of the source tree. |
| 9 */ |
| 10 |
| 11 #ifndef WEBRTC_BASE_MOD_OPS_H_ |
| 12 #define WEBRTC_BASE_MOD_OPS_H_ |
| 13 |
| 14 #include <limits> |
| 15 #include <type_traits> |
| 16 |
| 17 #include "webrtc/base/checks.h" |
| 18 |
| 19 #define MOD_OPS_ASSERT_TYPE_IS_UNSIGNED(T) \ |
| 20 static_assert(std::numeric_limits<T>::is_integer && \ |
| 21 !std::numeric_limits<T>::is_signed, \ |
| 22 "ModNum type must be of unsigned integer.") |
| 23 |
| 24 namespace webrtc { |
| 25 |
| 26 template <size_t M> inline size_t Add(size_t a , size_t b) { |
| 27 size_t add = b % M; |
| 28 if (a + add < a) |
| 29 return M - a + add; |
| 30 return (a + add) % M; |
| 31 } |
| 32 |
| 33 template <size_t M> inline size_t Subtract(size_t a, size_t b) { |
| 34 size_t sub = b % M; |
| 35 if (a < sub) |
| 36 return M - (sub - a); |
| 37 return a - sub; |
| 38 } |
| 39 |
| 40 template <typename T> inline T PositiveDiff(T a, T b) { |
| 41 MOD_OPS_ASSERT_TYPE_IS_UNSIGNED(T); |
| 42 return a <= b ? b - a : std::numeric_limits<T>::max() - (a - b); |
| 43 } |
| 44 |
| 45 template <typename T> inline T NegativeDiff(T a, T b) { |
| 46 MOD_OPS_ASSERT_TYPE_IS_UNSIGNED(T); |
| 47 return a < b ? std::numeric_limits<T>::max() - (b - a) : a - b; |
| 48 } |
| 49 |
| 50 template <typename T> inline bool AheadOrAt(T a, T b) { |
| 51 MOD_OPS_ASSERT_TYPE_IS_UNSIGNED(T); |
| 52 return PositiveDiff(b, a) < std::numeric_limits<T>::max() / 2; |
| 53 } |
| 54 |
| 55 template <typename T> inline bool AheadOf(T a, T b) { |
| 56 MOD_OPS_ASSERT_TYPE_IS_UNSIGNED(T); |
| 57 return a != b && AheadOrAt(a, b); |
| 58 } |
| 59 |
| 60 } // namespace webrtc |
| 61 |
| 62 #endif // WEBRTC_BASE_MOD_OPS_H_ |
OLD | NEW |