diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-07 18:45:59 +0000 |
commit | 19fcec84d8d7d21e796c7624e521b60d28ee21ed (patch) | |
tree | 42d26aa27d1e3f7c0b8bd3fd14e7d7082f5008dc /src/boost/libs/safe_numerics/example/example84.cpp | |
parent | Initial commit. (diff) | |
download | ceph-upstream.tar.xz ceph-upstream.zip |
Adding upstream version 16.2.11+ds.upstream/16.2.11+dsupstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'src/boost/libs/safe_numerics/example/example84.cpp')
-rw-r--r-- | src/boost/libs/safe_numerics/example/example84.cpp | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/boost/libs/safe_numerics/example/example84.cpp b/src/boost/libs/safe_numerics/example/example84.cpp new file mode 100644 index 000000000..f7809d9a7 --- /dev/null +++ b/src/boost/libs/safe_numerics/example/example84.cpp @@ -0,0 +1,66 @@ +#include <stdexcept> +#include <iostream> +#include <sstream> + +#include <boost/safe_numerics/safe_integer.hpp> +#include <boost/safe_numerics/safe_integer_range.hpp> +#include <boost/safe_numerics/native.hpp> +#include <boost/safe_numerics/exception.hpp> + +#include "safe_format.hpp" // prints out range and value of any type + +using namespace boost::safe_numerics; + +using safe_t = safe_signed_range< + -24, + 82, + native, + loose_trap_policy +>; + +// define variables used for input +using input_safe_t = safe_signed_range< + -24, + 82, + native, // we don't need automatic in this case + loose_exception_policy // assignment of out of range value should throw +>; + +// function arguments can never be outside of limits +auto f(const safe_t & x, const safe_t & y){ + auto z = x + y; // we know that this cannot fail + std::cout << "z = " << safe_format(z) << std::endl; + std::cout << "(x + y) = " << safe_format(x + y) << std::endl; + std::cout << "(x - y) = " << safe_format(x - y) << std::endl; + return z; +} + +bool test(const char * test_string){ + std::istringstream sin(test_string); + input_safe_t x, y; + try{ + std::cout << "type in values in format x y:" << test_string << std::endl; + sin >> x >> y; // read varibles, maybe throw exception + } + catch(const std::exception & e){ + // none of the above should trap. Mark failure if they do + std::cout << e.what() << '\n' << "input failure" << std::endl; + return false; + } + std::cout << "x" << safe_format(x) << std::endl; + std::cout << "y" << safe_format(y) << std::endl; + std::cout << safe_format(f(x, y)) << std::endl; + std::cout << "input success" << std::endl; + return true; +} + +int main(){ + std::cout << "example 84:\n"; + bool result = + ! test("123 125") + && test("0 0") + && test("-24 82") + ; + std::cout << (result ? "Success!" : "Failure") << std::endl; + return result ? EXIT_SUCCESS : EXIT_FAILURE; +} |