Re: [PATCH 1/4] lib/sprintf: add scnprintf_append() helper function
From: Andy Shevchenko
Date: Fri Nov 07 2025 - 04:34:09 EST
On Fri, Nov 07, 2025 at 01:16:13PM +0800, Junrui Luo wrote:
> Add a new scnprintf_append() helper function that appends formatted
> strings to an existing buffer.
>
> The function safely handles buffer bounds and returns the total length
> of the string, making it suitable for chaining multiple append operations.
This won't work as expected in the *printf() functions.
...
> +/**
> + * scnprintf_append - Append a formatted string to a buffer
The name with _cat would be probably closer to the strcpy()/strcat().
OTOH we have pr_cont(), so perhaps I would name this scnprintf_cont().
> + * @buf: The buffer to append to (must be null-terminated)
Yeah, and must be not NULL which is no go. The *printf() should tolerate
the (buf = NULL, size = 0) input.
> + * @size: The size of the buffer
> + * @fmt: Format string
> + * @...: Arguments for the format string
> + *
> + * This function appends a formatted string to an existing null-terminated
Use the form of "null-terminated" used in the file. Perhaps you want to update
the existing one(s), just make sure there is some consistency.
> + * buffer. It is safe to use in a chain of calls, as it returns the total
> + * length of the string.
> + *
> + * Returns: The total length of the string in @buf
> + */
> +int scnprintf_append(char *buf, size_t size, const char *fmt, ...)
> +{
> + va_list args;
> + size_t len;
> + len = strnlen(buf, size);
> + if (len >= size)
How can it be '>' ?
> + return len;
> + va_start(args, fmt);
> + len += vscnprintf(buf + len, size - len, fmt, args);
> + va_end(args);
> + return len;
> +}
--
With Best Regards,
Andy Shevchenko