Home | History | Annotate | Line # | Download | only in libutil
snprintb.c revision 1.27
      1 /*	$NetBSD: snprintb.c,v 1.27 2024/02/16 17:42:49 rillig Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  *
     16  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     17  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     18  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     19  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     20  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     21  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     22  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     23  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     24  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     25  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     26  * POSSIBILITY OF SUCH DAMAGE.
     27  */
     28 
     29 /*
     30  * snprintb: print an interpreted bitmask to a buffer
     31  *
     32  * => returns the length of the buffer that would be required to print the
     33  *    string minus the terminating NUL.
     34  */
     35 #ifndef _STANDALONE
     36 # ifndef _KERNEL
     37 
     38 #  if HAVE_NBTOOL_CONFIG_H
     39 #   include "nbtool_config.h"
     40 #  endif
     41 
     42 #  include <sys/cdefs.h>
     43 #  if defined(LIBC_SCCS) && !defined(lint)
     44 __RCSID("$NetBSD: snprintb.c,v 1.27 2024/02/16 17:42:49 rillig Exp $");
     45 #  endif
     46 
     47 #  include <sys/types.h>
     48 #  include <inttypes.h>
     49 #  include <stdio.h>
     50 #  include <util.h>
     51 #  include <errno.h>
     52 # else /* ! _KERNEL */
     53 #  include <sys/cdefs.h>
     54 __KERNEL_RCSID(0, "$NetBSD: snprintb.c,v 1.27 2024/02/16 17:42:49 rillig Exp $");
     55 #  include <sys/param.h>
     56 #  include <sys/inttypes.h>
     57 #  include <sys/systm.h>
     58 #  include <lib/libkern/libkern.h>
     59 # endif /* ! _KERNEL */
     60 
     61 # ifndef HAVE_SNPRINTB_M
     62 int
     63 snprintb_m(char *buf, size_t bufsize, const char *bitfmt, uint64_t val,
     64 	   size_t line_max)
     65 {
     66 	char *bp = buf, *sep_bp = NULL;
     67 	const char *c_fmt, *sep_fmt = NULL, *cur_fmt;
     68 	const char *num_fmt;
     69 	int ch, total_len, sep_line_len = 0, line_len, val_len, sep;
     70 	int restart = 0;
     71 
     72 #ifdef _KERNEL
     73 	/*
     74 	 * For safety; no other *s*printf() do this, but in the kernel
     75 	 * we don't usually check the return value
     76 	 */
     77 	(void)memset(buf, 0, bufsize);
     78 #endif /* _KERNEL */
     79 
     80 	ch = *bitfmt++;
     81 	switch (ch != '\177' ? ch : *bitfmt++) {
     82 	case 8:
     83 		num_fmt = "%#jo";
     84 		break;
     85 	case 10:
     86 		num_fmt = "%ju";
     87 		break;
     88 	case 16:
     89 		num_fmt = "%#jx";
     90 		break;
     91 	default:
     92 		goto internal;
     93 	}
     94 
     95 	/* Reserve space for trailing blank line if needed */
     96 	if (line_max > 0)
     97 		bufsize--;
     98 
     99 	total_len = snprintf(bp, bufsize, num_fmt, (uintmax_t)val);
    100 	if (total_len < 0)
    101 		goto internal;
    102 
    103 	val_len = line_len = total_len;
    104 
    105 	if ((size_t)total_len < bufsize)
    106 		bp += total_len;
    107 	else
    108 		bp += bufsize - 1;
    109 
    110 	if (val == 0 && ch != '\177')
    111 		goto done;
    112 
    113 #define	STORE(c) do {							\
    114 		line_len++;						\
    115 		if ((size_t)(++total_len) < bufsize)			\
    116 			*bp++ = (c);					\
    117 	} while (0)
    118 
    119 #define	BACKUP() do {							\
    120 		if (sep_bp != NULL) {					\
    121 			bp = sep_bp;					\
    122 			sep_bp = NULL;					\
    123 			total_len -= line_len - sep_line_len;		\
    124 			restart = 1;					\
    125 			bitfmt = sep_fmt;				\
    126 		}							\
    127 		STORE('>');						\
    128 		STORE('\0');						\
    129 		if ((size_t)total_len < bufsize)			\
    130 			snprintf(bp, bufsize - total_len, num_fmt,	\
    131 			    (uintmax_t)val);				\
    132 		total_len += val_len;					\
    133 		line_len = val_len;					\
    134 		bp += val_len;						\
    135 	} while (0)
    136 
    137 #define	PUTSEP() do {							\
    138 		if (line_max > 0 && (size_t)line_len >= line_max) {	\
    139 			BACKUP();					\
    140 			STORE('<');					\
    141 		} else {						\
    142 			/* Remember separator location */		\
    143 			if (line_max > 0 && sep != '<') {		\
    144 				sep_line_len = line_len;		\
    145 				sep_bp = bp;				\
    146 				sep_fmt = cur_fmt;			\
    147 			}						\
    148 			STORE(sep);					\
    149 			restart = 0;					\
    150 		}							\
    151 	} while (0)
    152 
    153 #define	PUTCHR(c) do {							\
    154 		if (line_max > 0 && (size_t)line_len >= line_max - 1) {	\
    155 			BACKUP();					\
    156 			if (restart == 0)				\
    157 				STORE(c);				\
    158 			else						\
    159 				sep = '<';				\
    160 		} else {						\
    161 			STORE(c);					\
    162 			restart = 0;					\
    163 		}							\
    164 	} while (0)
    165 
    166 #define	PUTS(s) do {							\
    167 		while ((ch = *(s)++) != 0) {				\
    168 			PUTCHR(ch);					\
    169 			if (restart)					\
    170 				break;					\
    171 		}							\
    172 	} while (0)
    173 
    174 #define	FMTSTR(sb, f) do {						\
    175 		int fmt_len = snprintf(bp, bufsize - total_len, sb,	\
    176 		    (uintmax_t)f);					\
    177 		if (fmt_len < 0)					\
    178 			goto internal;					\
    179 		total_len += fmt_len;					\
    180 		line_len += fmt_len;					\
    181 		if ((size_t)total_len < bufsize)			\
    182 			bp += fmt_len;					\
    183 	} while (0)
    184 
    185 	sep = '<';
    186 	if (ch != '\177') {
    187 		/* old-style format, 32-bit, 1-origin. */
    188 		for (int bit; (bit = *bitfmt) != 0;) {
    189 			cur_fmt = bitfmt++;
    190 			if (val & (1U << (bit - 1))) {
    191 				PUTSEP();
    192 				if (restart)
    193 					continue;
    194 				sep = ',';
    195 				for (; (ch = *bitfmt) > ' '; ++bitfmt) {
    196 					PUTCHR(ch);
    197 					if (restart)
    198 						break;
    199 				}
    200 			} else
    201 				for (; *bitfmt > ' '; ++bitfmt)
    202 					continue;
    203 		}
    204 	} else {
    205 		/* new-style format, 64-bit, 0-origin; also does fields. */
    206 		uint64_t field = val;
    207 		int matched = 1;
    208 		while (c_fmt = bitfmt, (ch = *bitfmt++) != '\0') {
    209 			int bit = *bitfmt++;
    210 			switch (ch) {
    211 			case 'b':
    212 				if (((val >> bit) & 1) == 0)
    213 					goto skip;
    214 				cur_fmt = c_fmt;
    215 				PUTSEP();
    216 				if (restart)
    217 					break;
    218 				PUTS(bitfmt);
    219 				if (restart == 0)
    220 					sep = ',';
    221 				break;
    222 			case 'f':
    223 			case 'F':
    224 				matched = 0;
    225 				cur_fmt = c_fmt;
    226 				int field_width = *bitfmt++;
    227 				field = (val >> bit) &
    228 				    (((uint64_t)1 << field_width) - 1);
    229 				PUTSEP();
    230 				if (restart == 0)
    231 					sep = ',';
    232 				if (ch == 'F') {	/* just extract */
    233 					/* duplicate PUTS() effect on bitfmt */
    234 					while (*bitfmt++ != '\0')
    235 						continue;
    236 					break;
    237 				}
    238 				if (restart == 0)
    239 					PUTS(bitfmt);
    240 				if (restart == 0)
    241 					PUTCHR('=');
    242 				if (restart == 0) {
    243 					FMTSTR(num_fmt, field);
    244 					if (line_max > 0
    245 					    && (size_t)line_len > line_max)
    246 						PUTCHR('#');
    247 				}
    248 				break;
    249 			case '=':
    250 			case ':':
    251 				/*
    252 				 * Here "bit" is actually a value instead,
    253 				 * to be compared against the last field.
    254 				 * This only works for values in [0..255],
    255 				 * of course.
    256 				 */
    257 				if ((int)field != bit)
    258 					goto skip;
    259 				matched = 1;
    260 				if (ch == '=')
    261 					PUTCHR('=');
    262 				PUTS(bitfmt);
    263 				break;
    264 			case '*':
    265 				bitfmt--;
    266 				if (!matched) {
    267 					matched = 1;
    268 					FMTSTR(bitfmt, field);
    269 				}
    270 				/*FALLTHROUGH*/
    271 			default:
    272 			skip:
    273 				while (*bitfmt++ != '\0')
    274 					continue;
    275 				break;
    276 			}
    277 		}
    278 	}
    279 	if (sep != '<')
    280 		STORE('>');
    281 done:
    282 	if (line_max > 0) {
    283 		bufsize++;
    284 		STORE('\0');
    285 		if ((size_t)total_len >= bufsize && bufsize > 1)
    286 			buf[bufsize - 2] = '\0';
    287 	}
    288 	STORE('\0');
    289 	if ((size_t)total_len >= bufsize && bufsize > 0)
    290 		buf[bufsize - 1] = '\0';
    291 	return total_len - 1;
    292 internal:
    293 #ifndef _KERNEL
    294 	errno = EINVAL;
    295 #endif
    296 	return -1;
    297 }
    298 
    299 int
    300 snprintb(char *buf, size_t bufsize, const char *bitfmt, uint64_t val)
    301 {
    302 	return snprintb_m(buf, bufsize, bitfmt, val, 0);
    303 }
    304 # endif /* ! HAVE_SNPRINTB_M */
    305 #endif /* ! _STANDALONE */
    306