Debian Codegraph @

lib/util/itos.h

raw
1 #pragma once
2
3 #include <stdio.h>
4
5 /// return type of `itos_`
6 struct itos_ {
7 // space to print a NUL-terminated ≤128-bit signed integer
8 char str[41];
9 };
10
11 /// convert a signed number to a string
12 ///
13 /// This is not expected to be used directly. Callers are expected to use the
14 /// `ITOS` macro instead.
15 ///
16 /// @param i Number to convert
17 /// @return Stringized conversion of the number
18 static inline struct itos_ itos_(long long i) {
19 struct itos_ s;
20 snprintf(s.str, sizeof(s.str), "%lld", i);
21 return s;
22 }
23
24 /// convert a signed number to a string
25 ///
26 /// The string returned by this macro has a lifetime that (under ≥C11 semantics)
27 /// only lasts until the end of the containing full expression. Thus intended
28 /// usage is something like:
29 ///
30 /// void foo(char *);
31 /// foo(ITOS(42));
32 ///
33 /// In particular, it is incorrect to store the result of this macro anywhere:
34 ///
35 /// char *p = ITOS(42); // ← WRONG
36 /// // p is now a dangling pointer, pointing to deallocated stack memory
37 ///
38 /// You can think of `ITOS` as a C equivalent of the C++
39 /// `std::to_string(i).c_str()`.
40 ///
41 /// @param i Number to convert
42 /// @return Stringized conversion of the number
43 #define ITOS(i) (itos_(i).str)