Home | History | Annotate | Line # | Download | only in libutil
snprintb.c revision 1.32
      1 /*	$NetBSD: snprintb.c,v 1.32 2024/02/16 19:31:25 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.32 2024/02/16 19:31:25 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.32 2024/02/16 19:31:25 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 *num_fmt, *cur_bitfmt, *sep_bitfmt = NULL;
     68 	char sep;
     69 	int restart = 0;
     70 
     71 #ifdef _KERNEL
     72 	/*
     73 	 * For safety; no other *s*printf() do this, but in the kernel
     74 	 * we don't usually check the return value
     75 	 */
     76 	(void)memset(buf, 0, bufsize);
     77 #endif /* _KERNEL */
     78 
     79 	int old_style = *bitfmt != '\177';
     80 	if (!old_style)
     81 		bitfmt++;
     82 	switch (*bitfmt++) {
     83 	case 8:
     84 		num_fmt = "%#jo";
     85 		break;
     86 	case 10:
     87 		num_fmt = "%ju";
     88 		break;
     89 	case 16:
     90 		num_fmt = "%#jx";
     91 		break;
     92 	default:
     93 		goto internal;
     94 	}
     95 
     96 	/* Reserve space for trailing blank line if needed */
     97 	if (line_max > 0)
     98 		bufsize--;
     99 
    100 	int val_len = snprintf(bp, bufsize, num_fmt, (uintmax_t)val);
    101 	if (val_len < 0)
    102 		goto internal;
    103 
    104 	size_t total_len = val_len, line_len = val_len, sep_line_len = 0;
    105 
    106 	if (total_len < bufsize)
    107 		bp += total_len;
    108 	else
    109 		bp += bufsize - 1;
    110 
    111 #define	STORE(c) do {							\
    112 		line_len++;						\
    113 		if (++total_len < bufsize)				\
    114 			*bp++ = (c);					\
    115 	} while (0)
    116 
    117 #define	BACKUP() do {							\
    118 		if (sep_bp != NULL) {					\
    119 			bp = sep_bp;					\
    120 			sep_bp = NULL;					\
    121 			total_len -= line_len - sep_line_len;		\
    122 			restart = 1;					\
    123 			bitfmt = sep_bitfmt;				\
    124 		}							\
    125 		STORE('>');						\
    126 		STORE('\0');						\
    127 		if (total_len < bufsize)				\
    128 			snprintf(bp, bufsize - total_len, num_fmt,	\
    129 			    (uintmax_t)val);				\
    130 		total_len += val_len;					\
    131 		line_len = val_len;					\
    132 		bp += val_len;						\
    133 	} while (0)
    134 
    135 #define	PUTSEP() do {							\
    136 		if (line_max > 0 && line_len >= line_max) {		\
    137 			BACKUP();					\
    138 			STORE('<');					\
    139 		} else {						\
    140 			/* Remember separator location */		\
    141 			if (line_max > 0 && sep != '<') {		\
    142 				sep_line_len = line_len;		\
    143 				sep_bp = bp;				\
    144 				sep_bitfmt = cur_bitfmt;		\
    145 			}						\
    146 			STORE(sep);					\
    147 			restart = 0;					\
    148 		}							\
    149 	} while (0)
    150 
    151 #define	PUTCHR(c) do {							\
    152 		if (line_max > 0 && line_len >= line_max - 1) {		\
    153 			BACKUP();					\
    154 			if (restart == 0)				\
    155 				STORE(c);				\
    156 			else						\
    157 				sep = '<';				\
    158 		} else {						\
    159 			STORE(c);					\
    160 			restart = 0;					\
    161 		}							\
    162 	} while (0)
    163 
    164 #define	PUTS(s) do {							\
    165 		while ((*(s)++) != 0) {					\
    166 			PUTCHR((s)[-1]);				\
    167 			if (restart)					\
    168 				break;					\
    169 		}							\
    170 	} while (0)
    171 
    172 #define	FMTSTR(sb, f) do {						\
    173 		size_t n = total_len < bufsize				\
    174 		    ? bufsize - total_len : 0;				\
    175 		int fmt_len = snprintf(bp, n, sb, (uintmax_t)f);	\
    176 		if (fmt_len < 0)					\
    177 			goto internal;					\
    178 		total_len += fmt_len;					\
    179 		line_len += fmt_len;					\
    180 		if (total_len < bufsize)				\
    181 			bp += fmt_len;					\
    182 	} while (0)
    183 
    184 	sep = '<';
    185 	if (old_style) {
    186 		/* old-style format, 32-bit, 1-origin. */
    187 		for (uint8_t bit; (bit = *bitfmt) != 0;) {
    188 			cur_bitfmt = bitfmt++;
    189 			if (val & (1U << (bit - 1))) {
    190 				PUTSEP();
    191 				if (restart)
    192 					continue;
    193 				sep = ',';
    194 				for (; *bitfmt > ' '; ++bitfmt) {
    195 					PUTCHR(*bitfmt);
    196 					if (restart)
    197 						break;
    198 				}
    199 			} else
    200 				for (; *bitfmt > ' '; ++bitfmt)
    201 					continue;
    202 		}
    203 	} else {
    204 		/* new-style format, 64-bit, 0-origin; also does fields. */
    205 		uint64_t field = val;
    206 		int matched = 1;
    207 		while (*bitfmt != '\0') {
    208 			uint8_t kind = *bitfmt++;
    209 			uint8_t bit = *bitfmt++;
    210 			switch (kind) {
    211 			case 'b':
    212 				if (((val >> bit) & 1) == 0)
    213 					goto skip;
    214 				cur_bitfmt = bitfmt - 2;
    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_bitfmt = bitfmt - 2;
    226 				uint8_t field_width = *bitfmt++;
    227 				field = (val >> bit) &
    228 				    (((uint64_t)1 << field_width) - 1);
    229 				PUTSEP();
    230 				if (restart == 0)
    231 					sep = ',';
    232 				if (kind == '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 					    && 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 (field != bit)
    258 					goto skip;
    259 				matched = 1;
    260 				if (kind == '=')
    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 	if (line_max > 0) {
    282 		bufsize++;
    283 		STORE('\0');
    284 		if (total_len >= bufsize && bufsize > 1)
    285 			buf[bufsize - 2] = '\0';
    286 	}
    287 	STORE('\0');
    288 	if (total_len >= bufsize && bufsize > 0)
    289 		buf[bufsize - 1] = '\0';
    290 	return (int)(total_len - 1);
    291 internal:
    292 #ifndef _KERNEL
    293 	errno = EINVAL;
    294 #endif
    295 	return -1;
    296 }
    297 
    298 int
    299 snprintb(char *buf, size_t bufsize, const char *bitfmt, uint64_t val)
    300 {
    301 	return snprintb_m(buf, bufsize, bitfmt, val, 0);
    302 }
    303 # endif /* ! HAVE_SNPRINTB_M */
    304 #endif /* ! _STANDALONE */
    305