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)
41 size_t srclen = strlen(src);
44 memcpy(dst, src, MIN(dstlen, srclen+1));
52 size_t cdecl__emit(struct output_state *dst, const char *src)
54 size_t rc = cdecl__strlcpy(dst->dst, src, dst->dstlen);
55 return cdecl__advance(dst, rc);
59 * 31 decimal digits is enough for values up to 2^102 - 1.
60 * 63 decimal digits is enough for values up to 2^209 - 1.
62 * We can't portably write numbers this large in preprocessor conditionals,
63 * but since the maximum values of unsigned integer types are always one
64 * less than a power of two, we can use a sequence of small shifts to infer
67 * All known implementations have 64-bit uintmax_t. Leave some headroom
68 * to support a possible future implementatons with 128-bit uintmax_t.
71 #if (UINTMAX_MAX >> 27 >> 27 >> 26 >> 26) == 0
73 #elif (UINTMAX_MAX >> 27 >> 26 >> 26 >> 26 >> 26 >> 26 >> 26 >> 26) == 0
76 # error UINTMAX_MAX is too large, please report a bug.
80 size_t cdecl__emit_uint(struct output_state *dst, uintmax_t val)
82 char buf[MAX_UINT_DIGITS + 1], *p = &buf[sizeof buf];
86 *(--p) = '0' + val % 10;
90 return cdecl__emit(dst, p);
93 static void explain_spec(struct output_state *dst, struct cdecl_declspec *s)
97 rc = cdecl__emit(dst, spec_string(s->type));
99 cdecl__emit(dst, " " + !rc);
100 cdecl__emit(dst, s->ident);
105 * Render a list of declaration specifiers. Only the declaration specifiers
106 * listed in mask, which is the bitwise OR of the desired specifier kinds, are
109 const char *cdecl__emit_specs(struct output_state *dst,
110 struct cdecl_declspec *s,
113 const char *sep = " ";
116 for (; s; s = s->next) {
117 if (!(s->type & mask))
120 cdecl__emit(dst, sep + empty);
121 explain_spec(dst, s);