blob: de56477ae338defe29bd50f43ebeb5ad0dc939e2 [file] [log] [blame]
Marshall Clow5b08c172018-10-16 17:27:54 +00001//===----------------------------------------------------------------------===//
2//
Chandler Carruth57b08b02019-01-19 10:56:40 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Marshall Clow5b08c172018-10-16 17:27:54 +00006//
7//===----------------------------------------------------------------------===//
8
9
10// Assumption: minValue < maxValue
11// Assumption: minValue <= rhs <= maxValue
12// Assumption: minValue <= lhs <= maxValue
13// Assumption: minValue >= 0
14template <typename T, T minValue, T maxValue>
15T euclidian_addition(T rhs, T lhs)
16{
17 const T modulus = maxValue - minValue + 1;
18 T ret = rhs + lhs;
Stephan T. Lavavejdec89052018-11-14 03:06:06 +000019 if (ret > maxValue)
Marshall Clow5b08c172018-10-16 17:27:54 +000020 ret -= modulus;
21 return ret;
22}
23
24// Assumption: minValue < maxValue
25// Assumption: minValue <= rhs <= maxValue
26// Assumption: minValue <= lhs <= maxValue
27// Assumption: minValue >= 0
28template <typename T, T minValue, T maxValue>
29T euclidian_subtraction(T lhs, T rhs)
30{
31 const T modulus = maxValue - minValue + 1;
32 T ret = lhs - rhs;
Stephan T. Lavavejdec89052018-11-14 03:06:06 +000033 if (ret < minValue)
Marshall Clow5b08c172018-10-16 17:27:54 +000034 ret += modulus;
35 if (ret > maxValue) // this can happen if T is unsigned
36 ret += modulus;
37 return ret;
38}