[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <20251107091246.4e5900f4@pumpkin>
Date: Fri, 7 Nov 2025 09:12:46 +0000
From: David Laight <david.laight.linux@...il.com>
To: Andrew Morton <akpm@...ux-foundation.org>
Cc: Junrui Luo <moonafterrain@...look.com>, linux-kernel@...r.kernel.org,
pmladek@...e.com, rostedt@...dmis.org, andriy.shevchenko@...ux.intel.com,
tiwai@...e.com, perex@...ex.cz, linux-sound@...r.kernel.org,
mchehab@...nel.org, awalls@...metrocast.net, linux-media@...r.kernel.org,
davem@...emloft.net, edumazet@...gle.com, kuba@...nel.org,
pabeni@...hat.com, netdev@...r.kernel.org
Subject: Re: [PATCH 1/4] lib/sprintf: add scnprintf_append() helper function
On Thu, 6 Nov 2025 21:38:33 -0800
Andrew Morton <akpm@...ux-foundation.org> wrote:
> On Fri, 7 Nov 2025 13:16:13 +0800 Junrui Luo <moonafterrain@...look.com> wrote:
>
> > +/**
> > + * scnprintf_append - Append a formatted string to a buffer
> > + * @buf: The buffer to append to (must be null-terminated)
> > + * @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
> > + * 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
>
> It wouldn't hurt to describe the behavior when this runs out of space
> in *buf.
>
>
>
> The whole thing is a bit unweildy - how much space must the caller
> allocate for `buf'? I bet that's a wild old guess.
That is true for all the snprintf() functions.
> I wonder if we should instead implement a kasprintf() version of this
> which reallocs each time and then switch all the callers over to that.
That adds the cost of a malloc, and I, like kasprintf() probably ends up
doing all the work of snprintf twice.
I'd be tempted to avoid the strlen() by passing in the offset.
So (say):
#define scnprintf_at(buf, len, off, ...) \
scnprintf((buf) + off, (len) - off, __VA_ARGS__)
Then you can chain calls, eg:
off = scnprintf(buf, sizeof buf, ....);
off += scnprintf_at(buf, sizeof buf, off, ....);
David
Powered by blists - more mailing lists