1+ #include " doctest.hpp"
2+
3+ #include < cstdint>
4+ #include < limits>
5+
6+ #include < oryx/crt/narrow_cast.hpp>
7+
8+ using namespace oryx ::crt;
9+
10+ TEST_CASE (" same type conversions" ) {
11+ CHECK (Narrow<int , int >(0 ) == 0 );
12+ CHECK (Narrow<int , int >(42 ) == 42 );
13+ CHECK (Narrow<unsigned , unsigned >(123u ) == 123u );
14+ }
15+
16+ TEST_CASE (" signed to signed" ) {
17+ CHECK (Narrow<int8_t , int >(127 ) == 127 );
18+ CHECK (Narrow<int8_t , int >(-128 ) == -128 );
19+
20+ CHECK_FALSE (Narrow<int8_t , int >(128 ).has_value ());
21+ CHECK_FALSE (Narrow<int8_t , int >(-129 ).has_value ());
22+ }
23+
24+ TEST_CASE (" unsigned to unsigned" ) {
25+ CHECK (Narrow<uint8_t , unsigned >(255u ) == 255u );
26+ CHECK_FALSE (Narrow<uint8_t , unsigned >(256u ).has_value ());
27+ }
28+
29+ TEST_CASE (" signed to unsigned" ) {
30+ CHECK (Narrow<unsigned , int >(0 ) == 0u );
31+ CHECK (Narrow<unsigned , int >(42 ) == 42u );
32+
33+ CHECK_FALSE (Narrow<unsigned , int >(-1 ).has_value ());
34+ CHECK_FALSE (Narrow<uint8_t , int >(std::numeric_limits<int >::max ()).has_value ());
35+ }
36+
37+ TEST_CASE (" unsigned to signed" ) {
38+ CHECK (Narrow<int , unsigned >(0u ) == 0 );
39+ CHECK (Narrow<int , unsigned >(42u ) == 42 );
40+
41+ CHECK_FALSE (Narrow<int8_t , unsigned >(128u ).has_value ());
42+ }
43+
44+ TEST_CASE (" boundary conditions" ) {
45+ CHECK (Narrow<int , unsigned >(static_cast <unsigned >(std::numeric_limits<int >::max ())) ==
46+ std::numeric_limits<int >::max ());
47+
48+ CHECK_FALSE (Narrow<int , unsigned >(static_cast <unsigned >(std::numeric_limits<int >::max ()) + 1u ).has_value ());
49+ }
0 commit comments