lib/: Use NITEMS() instead of SIZEOF_ARRAY() where number of elements is meant

For arrays of char, both NITEMS() and SIZEOF_ARRAY() return the same
value.  However, NITEMS() is more appropriate.  Think of wide-character
equivalents of the same code; with NITEMS(), they would continue to be
valid, while with SIZEOF_ARRAY(), they would be wrong.

In the implementation of ZUSTR2STP(), we want SIZEOF_ARRAY() within the
static assert, because we're just comparing the sizes of the source and
destination buffers, and we don't care if we compare sizes or numbers of
elements, and using sizes is just simpler.  But we want NITEMS() in the
zustr2stp() call, where we want to copy a specific number of characters.

Signed-off-by: Alejandro Colomar <alx@kernel.org>
This commit is contained in:
Alejandro Colomar
2023-11-26 21:01:05 -06:00
committed by Serge Hallyn
parent a5cddf243a
commit 721b9096eb
3 changed files with 6 additions and 6 deletions
+2 -2
View File
@@ -31,7 +31,7 @@
* at the buffer pointed to by dst. If the destination buffer,
* isn't large enough to hold the copy, the resulting string is
* truncated. The size of the buffer is calculated internally via
* SIZEOF_ARRAY().
* NITEMS().
*
* RETURN VALUE
* -1 If this call truncated the resulting string.
@@ -44,7 +44,7 @@
*/
#define STRTCPY(dst, src) strtcpy(dst, src, SIZEOF_ARRAY(dst))
#define STRTCPY(dst, src) strtcpy(dst, src, NITEMS(dst))
inline ssize_t strtcpy(char *restrict dst, const char *restrict src,
+1 -1
View File
@@ -246,7 +246,7 @@ static
#ifdef HAVE_STRUCT_UTMP_UT_HOST
} else if ( (NULL != ut)
&& ('\0' != ut->ut_host[0])) {
hostname = XMALLOC(SIZEOF_ARRAY(ut->ut_host) + 1, char);
hostname = XMALLOC(NITEMS(ut->ut_host) + 1, char);
ZUSTR2STP(hostname, ut->ut_host);
#endif /* HAVE_STRUCT_UTMP_UT_HOST */
}
+3 -3
View File
@@ -22,7 +22,7 @@
({ \
static_assert(!is_array(dst) || sizeof(dst) > SIZEOF_ARRAY(src), ""); \
\
zustr2stp(dst, src, SIZEOF_ARRAY(src)); \
zustr2stp(dst, src, NITEMS(src)); \
})
@@ -62,9 +62,9 @@ inline char *zustr2stp(char *restrict dst, const char *restrict src, size_t sz);
*
* EXAMPLES
* char src[13] = "Hello, world!" // No '\0' in this buffer!
* char dst[SIZEOF_ARRAY(src) + 1];
* char dst[NITEMS(src) + 1];
*
* zustr2stp(dst, src, SIZEOF_ARRAY(src));
* zustr2stp(dst, src, NITEMS(src));
* puts(dst);
*/