Created
January 10, 2022 10:21
-
-
Save edlongman/cecab627063ef6db08261fe6232b0db6 to your computer and use it in GitHub Desktop.
A quick test of a NoOverflow library
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <limits> | |
#include <stdint.h> | |
#include <type_traits> | |
namespace NoOverflow{ | |
template <class T> | |
using enable_if_unsigned_t = typename ::std::enable_if<std::is_unsigned<T>::value, T>::type; | |
template <class T> | |
using enable_if_signed_t = typename ::std::enable_if<std::is_signed<T>::value, T>::type; | |
template<typename T> enable_if_unsigned_t<T> add(T a, T b){ | |
T res; | |
if(__builtin_add_overflow(a, b, &res)){ | |
return std::numeric_limits<T>::max(); | |
} | |
return res; | |
} | |
template<typename T> enable_if_signed_t<T> add(T a, T b){ | |
T res; | |
if(__builtin_add_overflow(a, b, &res)){ | |
if(res<0)return std::numeric_limits<T>::max(); | |
else return std::numeric_limits<T>::min(); | |
} | |
return res; | |
} | |
}; | |
int main() | |
{ | |
{ | |
uint16_t a = 1; | |
uint16_t b = -1; | |
a = 33000; | |
b = 34000; | |
std::cout << "16 bit overflow" << NoOverflow::add(a, b) << std::endl; | |
} | |
{ | |
int8_t a = 1; | |
int8_t b = -1; | |
a = -120; | |
b = -120; | |
std::cout << "8 bit overflow" << (int)NoOverflow::add(a, b) << std::endl; | |
} | |
{ | |
int8_t a = 1; | |
int8_t b = -1; | |
a = 120; | |
b = 9; | |
std::cout << "8 bit overflow" << (int)NoOverflow::add(a, b) << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment