cppx-core
integer-operations.hpp
Go to the documentation of this file.
1 #pragma once // Source encoding: UTF-8 with BOM (π is a lowercase Greek "pi").
2 
13 #include <cppx-core/language/syntax/macro-use.hpp> // CPPX_USE_CPPX
14 #include <cppx-core/language/types/Truth.hpp> // cppx::Truth
15 //#include <cppx-core/language/tmp/basic-type-traits.hpp> // cppx::is_unsigned_
16 
17 #include <c/limits.hpp> // INT_MAX
18 #include <c/stdint.hpp> // ::(uintXX_t)
19 #include <c/stdlib.hpp> // ::(div_t, div)
20 #include <algorithm> // std::max
21 #include <type_traits> // std::(common_type_t, is_integral_v, is_unsigned_v)
22 
23 namespace cppx
24 {
25  template< class Int >
26  inline auto is_even( const Int x )
27  -> Truth
28  { return x % 2 == 0; }
29 
30  template< class Int >
31  inline auto is_odd( const Int x )
32  -> Truth
33  { return x % 2 == 1; }
34 
35  template< class Int >
36  inline auto intdiv( const Int a, const Int b ) noexcept
37  -> Int
38  {
39  const div_t r = ::div( a, b );
40  return (r.quot < 0 and r.rem != 0? r.quot - 1 : r.quot);
41  }
42 
43  inline auto intmod( const int a, const int b ) noexcept
44  -> int
45  { return a - b*intdiv( a, b ); }
46 
47  template< class Int = int >
48  inline auto intsquare( const Int x )
49  -> Int
50  { return x*x; }
51 
52  template< class Int = int >
53  inline auto intcube( const Int x )
54  -> Int
55  { return x*x*x; }
56 
57  template< class... Ints >
58  inline auto intmin( const Ints... args )
59  -> std::common_type_t<Ints...>
60  {
61  static_assert( (... and std::is_integral_v<Ints> ) );
62  return std::min( {std::common_type_t<Ints...>( args )...} );
63  }
64 
65  template< class... Ints >
66  inline auto intmax( const Ints... args )
67  -> std::common_type_t<Ints...>
68  {
69  static_assert( (... and std::is_integral_v<Ints> ) );
70  return std::max( {std::common_type_t<Ints...>( args )...} );
71  }
72 
73  namespace calc
74  {
77  );
78  } // namespace calc
79 } // namespace cppx
auto intmax(const Ints... args) -> std::common_type_t< Ints... >
auto intmod(const int a, const int b) noexcept -> int
A drop-in replacement for bool without implicit conversion from/to types other than bool.
Definition: Truth.hpp:34
CPPX_USE_CPPX(intpow, squared, cubed)
auto is_even(const Int x) -> Truth
Truth is a drop-in replacement for bool without implicit conversion from/to types other than bool.
auto intsquare(const Int x) -> Int
auto intcube(const Int x) -> Int
Macros for generating more concise and clear using statements, primarily $use_cppx and $use_std,...
auto intmin(const Ints... args) -> std::common_type_t< Ints... >
auto is_odd(const Int x) -> Truth
auto intdiv(const Int a, const Int b) noexcept -> Int