git: f8aa0ee8d017 - main - devinfo: Introduce function for printing indent

From: Warner Losh <imp_at_FreeBSD.org>
Date: Tue, 06 May 2025 22:02:11 UTC
The branch main has been updated by imp:

URL: https://cgit.FreeBSD.org/src/commit/?id=f8aa0ee8d017a276d22521fa7c809aa0f3349be2

commit f8aa0ee8d017a276d22521fa7c809aa0f3349be2
Author:     ktullavik <ktullavik@gmail.com>
AuthorDate: 2024-10-17 15:37:44 +0000
Commit:     Warner Losh <imp@FreeBSD.org>
CommitDate: 2025-05-06 22:01:45 +0000

    devinfo: Introduce function for printing indent
    
    When libxo is added we want the whole indentation to
    be printed in a single call. Otherwise the html will be
    spammed with indentation tags.
    
    Reviewed by: imp
    Pull Request: https://github.com/freebsd/freebsd-src/pull/1480
---
 usr.sbin/devinfo/devinfo.c | 31 +++++++++++++++++++++----------
 1 file changed, 21 insertions(+), 10 deletions(-)

diff --git a/usr.sbin/devinfo/devinfo.c b/usr.sbin/devinfo/devinfo.c
index 4ca417368514..306d752e884e 100644
--- a/usr.sbin/devinfo/devinfo.c
+++ b/usr.sbin/devinfo/devinfo.c
@@ -31,7 +31,8 @@
  * Print information about system device configuration.
  */
 
-#include <sys/types.h>
+#include <sys/param.h>
+
 #include <err.h>
 #include <errno.h>
 #include <stdbool.h>
@@ -57,6 +58,20 @@ struct indent_arg
 	void	*arg;
 };
 
+
+static void
+print_indent(int n)
+{
+	static char	buffer[1024];
+
+	if (n < 1)
+		return;
+	n = MIN((size_t)n, sizeof(buffer) - 1);
+	memset(buffer, ' ', n);
+	buffer[n] = '\0';
+	printf("%s", buffer);
+}
+
 /*
  * Print a resource.
  */
@@ -86,14 +101,12 @@ print_device_matching_resource(struct devinfo_res *res, void *arg)
 {
 	struct indent_arg	*ia = (struct indent_arg *)arg;
 	struct devinfo_dev	*dev = (struct devinfo_dev *)ia->arg;
-	int			i;
 
 	if (devinfo_handle_to_device(res->dr_device) == dev) {
 		/* in 'detect' mode, found a match */
 		if (ia->indent == 0)
 			return(1);
-		for (i = 0; i < ia->indent; i++)
-			printf(" ");
+		print_indent(ia->indent);
 		print_resource(res);
 		printf("\n");
 	}
@@ -107,7 +120,7 @@ int
 print_device_rman_resources(struct devinfo_rman *rman, void *arg)
 {
 	struct indent_arg	*ia = (struct indent_arg *)arg;
-	int			indent, i;
+	int			indent;
 
 	indent = ia->indent;
 
@@ -117,8 +130,7 @@ print_device_rman_resources(struct devinfo_rman *rman, void *arg)
 	    print_device_matching_resource, ia) != 0) {
 
 		/* there are, print header */
-		for (i = 0; i < indent; i++)
-			printf(" ");
+		print_indent(indent);
 		printf("%s:\n", rman->dm_desc);
 
 		/* print resources */
@@ -155,12 +167,11 @@ static int
 print_device(struct devinfo_dev *dev, void *arg)
 {
 	struct indent_arg	ia;
-	int			i, indent;
+	int			indent;
 
 	if (vflag || (dev->dd_name[0] != 0 && dev->dd_state >= DS_ATTACHED)) {
 		indent = (int)(intptr_t)arg;
-		for (i = 0; i < indent; i++)
-			printf(" ");
+		print_indent(indent);
 		print_dev(dev);
 		printf("\n");
 		if (rflag) {