2 * Helper functions for outputting text.
3 * Copyright © 2011, 2021, 2023 Nick Bowler
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 #include "cdecl-internal.h"
28 size_t cdecl__advance(struct output_state *dst, size_t amount)
30 size_t x = MIN(amount, dst->dstlen);
39 size_t cdecl__strlcpy(char *dst, const char *src, size_t dstlen)
42 snprintf(dst, dstlen, "%s", src);
46 size_t cdecl__emit(struct output_state *dst, const char *src)
48 size_t rc = cdecl__strlcpy(dst->dst, src, dst->dstlen);
49 return cdecl__advance(dst, rc);
53 * 31 decimal digits is enough for values up to 2^102 - 1.
54 * 63 decimal digits is enough for values up to 2^209 - 1.
56 * We can't portably write numbers this large in preprocessor conditionals,
57 * but since the maximum values of unsigned integer types are always one
58 * less than a power of two, we can use a sequence of small shifts to infer
61 * All known implementations have 64-bit uintmax_t. Leave some headroom
62 * to support a possible future implementatons with 128-bit uintmax_t.
65 #if (UINTMAX_MAX >> 27 >> 27 >> 26 >> 26) == 0
67 #elif (UINTMAX_MAX >> 27 >> 26 >> 26 >> 26 >> 26 >> 26 >> 26 >> 26) == 0
70 # error UINTMAX_MAX is too large, please report a bug.
74 size_t cdecl__emit_uint(struct output_state *dst, uintmax_t val)
76 char buf[MAX_UINT_DIGITS + 1], *p = &buf[sizeof buf];
80 *(--p) = '0' + val % 10;
84 return cdecl__emit(dst, p);
87 static void explain_spec(struct output_state *dst, struct cdecl_declspec *s)
91 rc = cdecl__emit(dst, spec_string(s->type));
93 cdecl__emit(dst, " " + !rc);
94 cdecl__emit(dst, s->ident);
99 * Render a list of declaration specifiers. Only the declaration specifiers
100 * listed in mask, which is the bitwise OR of the desired specifier kinds, are
103 const char *cdecl__emit_specs(struct output_state *dst,
104 struct cdecl_declspec *s,
107 const char *sep = " ";
110 for (; s; s = s->next) {
111 if (!(s->type & mask))
114 cdecl__emit(dst, sep + empty);
115 explain_spec(dst, s);