| 1 |
// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 |
|
| 4 |
/** |
| 5 |
* @file |
| 6 |
* |
| 7 |
* Minimum/maximum operations. |
| 8 |
* |
| 9 |
* See @ref MinMaxOperations. |
| 10 |
*/ |
| 11 |
|
| 12 |
#ifndef DRGN_MINMAX_H |
| 13 |
#define DRGN_MINMAX_H |
| 14 |
|
| 15 |
#include "pp.h" |
| 16 |
|
| 17 |
/** |
| 18 |
* @ingroup Internals |
| 19 |
* |
| 20 |
* @defgroup MinMaxOperations Minimum/maximum operations |
| 21 |
* |
| 22 |
* Generic minimum/maximum operations. |
| 23 |
* |
| 24 |
* @{ |
| 25 |
*/ |
| 26 |
|
| 27 |
/** Get the minimum of two expressions with compatible types. */ |
| 28 |
#define min(x, y) cmp_once_impl(x, y, PP_UNIQUE(_x), PP_UNIQUE(_y), <) |
| 29 |
/** Get the maximum of two expressions with compatible types. */ |
| 30 |
#define max(x, y) cmp_once_impl(x, y, PP_UNIQUE(_x), PP_UNIQUE(_y), >) |
| 31 |
/** @cond */ |
| 32 |
#define cmp_once_impl(x, y, unique_x, unique_y, op) ({ \ |
| 33 |
__auto_type unique_x = (x); \ |
| 34 |
__auto_type unique_y = (y); \ |
| 35 |
/* Generate a warning if x and y do not have compatible types. */ \ |
| 36 |
(void)(&unique_x == &unique_y); \ |
| 37 |
unique_x op unique_y ? unique_x : unique_y; \ |
| 38 |
}) |
| 39 |
/** @endcond */ |
| 40 |
|
| 41 |
/** |
| 42 |
* Get the minimum of two integer constant expressions, resulting in an integer |
| 43 |
* constant expression. |
| 44 |
*/ |
| 45 |
#define min_iconst(x, y) cmp_iconst_impl(x, y, <) |
| 46 |
/** |
| 47 |
* Get the maximum of two integer constant expressions, resulting in an integer |
| 48 |
* constant expression. |
| 49 |
*/ |
| 50 |
#define max_iconst(x, y) cmp_iconst_impl(x, y, >) |
| 51 |
/** @cond */ |
| 52 |
#define cmp_iconst_impl(x, y, op) \ |
| 53 |
/* \ |
| 54 |
* Enforce that the arguments are integer constant expressions. The \ |
| 55 |
* size of a non-VLA array must be an integer constant expression, and \ |
| 56 |
* a compound literal cannot be a VLA. Evaluates to non-zero to fall \ |
| 57 |
* through to the comparison. \ |
| 58 |
*/ \ |
| 59 |
(sizeof((char [(x) * 0 + (y) * 0 + 1]){0}) && \ |
| 60 |
(x) op (y) ? (x) : (y)) |
| 61 |
/** @endcond */ |
| 62 |
|
| 63 |
/** @} */ |
| 64 |
|
| 65 |
#endif /* DRGN_MINMAX_H */ |