ic-macros  0.1.5
integer_cast.h
Go to the documentation of this file.
1 /*
2  * Copyright (c) 2023, Intercreate, Inc.
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include <stdint.h>
8 
9 #include "ic_macros/ic_assert.h"
10 #include "zephyr/util.h"
11 
21 #define IC_G_CAST_NUMBER(type, min, max, expr) \
22  (type)(expr) + IC_ZERO_OR_COMPILE_ERROR((expr) >= min && (expr) <= max)
23 
24 
34 #define IC_CAST_NUMBER(type, min, max, expr) \
35  ({ \
36  __auto_type const _IC_CAST_NUMBER_expr_ = (expr); \
37  IC_ASSERT(IC_G_IN_RANGE(_IC_CAST_NUMBER_expr_, min, max)); \
38  (type) _IC_CAST_NUMBER_expr_; \
39  })
40 
50 #define IC_CAST_UNSIGNED(type, _, max, expr) \
51  ({ \
52  __auto_type const _IC_CAST_NUMBER_expr_ = (expr); \
53  IC_ASSERT(_IC_CAST_NUMBER_expr_ <= max); \
54  (type) _IC_CAST_NUMBER_expr_; \
55  })
56 
66 #define _IC_CAST_NUMBER(type, min, max, expr) \
67  _Generic((expr), uint8_t: IC_CAST_UNSIGNED, uint16_t: IC_CAST_UNSIGNED, uint32_t: IC_CAST_UNSIGNED, uint64_t: IC_CAST_UNSIGNED, default: IC_CAST_SIGNED)( \
68  type, min, max, expr \
69  )
70 
77 #define IC_UINT8(expr) IC_CAST_NUMBER(uint8_t, 0, UINT8_MAX, expr)
78 
85 #define IC_UINT16(expr) IC_CAST_NUMBER(uint16_t, 0, UINT16_MAX, expr)
86 
93 #define IC_UINT32(expr) IC_CAST_NUMBER(uint32_t, 0, UINT32_MAX, expr)
94 
101 #define IC_UINT64(expr) IC_CAST_NUMBER(uint64_t, 0, UINT64_MAX, expr)
102 
109 #define IC_INT8(expr) IC_CAST_NUMBER(int8_t, INT8_MIN, INT8_MAX, expr)
110 
117 #define IC_INT16(expr) IC_CAST_NUMBER(int16_t, INT16_MIN, INT16_MAX, expr)
118 
125 #define IC_INT32(expr) IC_CAST_NUMBER(int32_t, INT32_MIN, INT32_MAX, expr)
126 
133 #define IC_INT64(expr) IC_CAST_NUMBER(int64_t, INT64_MIN, INT64_MAX, expr)
134 
140 #define IC_G_UINT8(expr) IC_G_CAST_NUMBER(uint8_t, 0, UINT8_MAX, expr)
141 
147 #define IC_G_UINT16(expr) IC_G_CAST_NUMBER(uint16_t, 0, UINT16_MAX, expr)
148 
154 #define IC_G_UINT32(expr) IC_G_CAST_NUMBER(uint32_t, 0, UINT32_MAX, expr)
155 
161 #define IC_G_UINT64(expr) IC_G_CAST_NUMBER(uint64_t, 0, UINT64_MAX, expr)
162 
168 #define IC_G_INT8(expr) IC_G_CAST_NUMBER(int8_t, INT8_MIN, INT8_MAX, expr)
169 
175 #define IC_G_INT16(expr) IC_G_CAST_NUMBER(int16_t, INT16_MIN, INT16_MAX, expr)
176 
182 #define IC_G_INT32(expr) IC_G_CAST_NUMBER(int32_t, INT32_MIN, INT32_MAX, expr)
183 
189 #define IC_G_INT64(expr) IC_G_CAST_NUMBER(int64_t, INT64_MIN, INT64_MAX, expr)