Debian Codegraph @

lib/util/gv_math.h

raw
1 /// \file
2 /// \brief Arithmetic helper functions
3 /// \ingroup cgraph_utils
4
5 #pragma once
6
7 #include <assert.h>
8 #include <float.h>
9 #include <limits.h>
10 #include <stdbool.h>
11 #include <stddef.h>
12 #include <string.h>
13
14 /// comparator for doubles
15 static inline int fcmp(double a, double b) {
16 if (a < b) {
17 return -1;
18 }
19 if (a > b) {
20 return 1;
21 }
22 return 0;
23 }
24
25 /// maximum of two integers
26 static inline int imax(int a, int b) { return a > b ? a : b; }
27
28 /// maximum of two sizes
29 static inline size_t zmax(size_t a, size_t b) { return a > b ? a : b; }
30
31 /// minimum of two integers
32 static inline int imin(int a, int b) { return a < b ? a : b; }
33
34 /**
35 * \brief are two values precisely the same?
36 *
37 * This function should only be used when you know you want comparison with no
38 * tolerance, which is rare. Floating-point arithmetic accumulates imprecision,
39 * so equality comparisons should generally include a non-zero tolerance to
40 * account for this. In general, this function is only applicable for checking
41 * things like “is this variable unchanged since a previous assignment from a
42 * literal?”
43 *
44 * \param a First operand to comparison
45 * \param b Second operand to comparison
46 * \return True if the values are equal
47 */
48 static inline bool is_exactly_equal(double a, double b) {
49 return memcmp(&a, &b, sizeof(a)) == 0;
50 }
51
52 /**
53 * \brief is a value precisely 0.0?
54 *
55 * This function should only be used when you know you want comparison with no
56 * tolerance, which is rare. Floating-point arithmetic accumulates imprecision,
57 * so equality comparisons should generally include a non-zero tolerance to
58 * account for this. Valid `double` representations even include -0.0, for which
59 * this function will return false. In general, this function is only applicable
60 * for checking things like “is this variable unchanged since a previous
61 * assignment from the literal `0`?” or “did this value we parsed from user
62 * input originate from the string "0.0"?”
63 *
64 * \param v Value to check
65 * \return True if the value is equal to exactly 0.0
66 */
67 static inline bool is_exactly_zero(double v) { return is_exactly_equal(v, 0); }
68
69 /**
70 * \brief scale up or down a non-negative integer, clamping to \p [0, INT_MAX]
71 *
72 * \param original Value to scale
73 * \param scale Scale factor to apply
74 * \return Clamped result
75 */
76 static inline int scale_clamp(int original, double scale) {
77 assert(original >= 0);
78
79 if (scale < 0) {
80 return 0;
81 }
82
83 if (scale > 1 && original > INT_MAX / scale) {
84 return INT_MAX;
85 }
86
87 return (int)(original * scale);
88 }
89
90 /// byte length of data per pixel in image data buffers
91 enum { BYTES_PER_PIXEL = 4 };
92
93 /// in-place conversion of ARGB32 big endian to RGBA32 little endian
94 ///
95 /// Image data originating from sources like Cairo comes in a 4-byte-per-pixel
96 /// format ordered {blue, green, red, alpha}. Some output libraries/devices
97 /// instead consume a 4-byte-per-pixel format ordered {red, green, blue, alpha}.
98 /// This function converts the former to the latter.
99 ///
100 /// It is confusing to refer to these formats as ARGB32 and RGBA32 when the
101 /// first is big endian and the second is little endian, and thus the mappings
102 /// of letters in the acronym to bytes in memory are opposites. Nevertheless
103 /// that appears to be what is in common usage.
104 ///
105 /// @param width Width of the image in pixels
106 /// @param height Height of the image in pixels
107 /// @param data [inout] Image data in ARGB32 format on entry and RGBA32 format
108 /// on exit
109 static inline void argb2rgba(size_t width, size_t height, unsigned char *data) {
110 assert(data != NULL || (width == 0 && height == 0));
111
112 // indices to color bytes in each format
113 enum { Ba = 0, Ga = 1, Ra = 2, Aa = 3 };
114 enum { Rb = 0, Gb = 1, Bb = 2, Ab = 3 };
115
116 for (size_t y = 0; y < height; ++y) {
117 for (size_t x = 0; x < width; ++x) {
118 const unsigned char red = data[Ra];
119 const unsigned char blue = data[Ba];
120 data[Rb] = red;
121 data[Bb] = blue;
122 data += BYTES_PER_PIXEL;
123 }
124 }
125 }
126
127 /// swap data referenced by two pointers
128 ///
129 /// You can think of this macro as having the following C type:
130 ///
131 /// void SWAP(<t1> *a, <t1> *b);
132 ///
133 /// Both `a` and `b` are expected to be pure expressions.
134 #define SWAP(a, b) \
135 do { \
136 /* trigger a -Wcompare-distinct-pointer-types compiler warning if `a` */ \
137 /* and `b` have differing types */ \
138 (void)((a) == (b)); \
139 \
140 /* Swap their targets. Contemporary compilers will optimize the `memcpy`s \
141 * into direct writes for primitive types. \
142 */ \
143 char tmp_[sizeof(*(a))]; \
144 memcpy(tmp_, (a), sizeof(*(a))); \
145 *(a) = *(b); \
146 memcpy((b), tmp_, sizeof(*(b))); \
147 } while (0)
148
149 /// convert a double-precision floating-point to integer
150 ///
151 /// Values below or above the range of representable integers are clamped. The
152 /// caller should verify this lossy conversion is acceptable/desirable.
153 ///
154 /// @param v Double value to convert
155 /// @return Closest integer value
156 static inline int d2i(double v) {
157 if (v > INT_MAX) {
158 return INT_MAX;
159 }
160 if (v < INT_MIN) {
161 return INT_MIN;
162 }
163 return (int)v;
164 }
165
166 /// convert a double-precision floating-point to single-precision
167 ///
168 /// Values below or above the range of representable floats are clamped. There
169 /// is loss of precision resulting from both this and that single-precision
170 /// space inherently has less resolution than double-precision space. The caller
171 /// should verify this loss of precision is acceptable/desirable.
172 ///
173 /// @param v Double value to convert
174 /// @return Closest float value
175 static inline float d2f(double v) {
176 if (v > FLT_MAX) {
177 return FLT_MAX;
178 }
179 if (v < -FLT_MAX) {
180 return -FLT_MAX;
181 }
182 return (float)v;
183 }