[v2,1/3] string: Add stpecpy()

Message ID 20221228231741.125945-2-alx@kernel.org
State Not applicable
Headers
Series [v2,1/3] string: Add stpecpy() |

Commit Message

Alejandro Colomar Dec. 28, 2022, 11:17 p.m. UTC
  This function is similar to stpcpy(3), but it tuncates the destination
string if it doesn't fit the buffer.  It's much simpler to use than
strscpy(9) or strlcpy(3), and slightly faster.

It also allows chaining with stpeprintf(3), which has the same interface
as stpecpy(3), but prints a formatted string (like snprintf(3)).

Signed-off-by: Alejandro Colomar <alx@kernel.org>
---
 string/Makefile  |  1 +
 string/stpecpy.c | 45 +++++++++++++++++++++++++++++++++++++++++++++
 string/string.h  |  7 +++++++
 3 files changed, 53 insertions(+)
 create mode 100644 string/stpecpy.c
  

Comments

Alejandro Colomar Dec. 28, 2022, 11:27 p.m. UTC | #1
stpecpy(3)                 Library Functions Manual                 stpecpy(3)

NAME
        stpecpy - copy a string with truncation

LIBRARY
        stp string library (libstp, pkgconf ‐‐cflags ‐‐libs libstp)

SYNOPSIS
        #include <stp/stpe/stpecpy.h>

        char *_Nullable stpecpy(char *_Nullable dst, char end[0],
                                const char *restrict src);

DESCRIPTION
        This function copies the string pointed to by src, into a string at the
        buffer  pointed  to  by  dst.   If the destination buffer, limited by a
        pointer to its end —one after its last element—, isn’t large enough  to
        hold the copy, the resulting string is truncated.

        This   function   can  be  chained  with  calls  to  stpeprintf(3)  and
        vstpeprintf(3).

        An implementation of this function might be

            /* This code is in the public domain. */

            char *
            stpecpy(char *dst, char end[0], const char *restrict src)
            {
                char *p;

                if (dst == end || dst == NULL)
                    return dst;

                p = memccpy(dst, src, '\0', end - dst);
                if (p != NULL)
                    return p - 1;

                /* truncation detected */
                end[-1] = '\0';
                return end;
            }

RETURN VALUE
        NULL   If dst was NULL.

        end
               •  If this call truncated.
               •  If dst was equal to end (a previous  call  to  this  function
                  truncated).

        dst + strlen(dst)
               On  success,  this function returns a pointer to the terminating
               null byte.

ATTRIBUTES
        For an explanation of the terms  used  in  this  section,  see  attrib‐
        utes(7).
        ┌────────────────────────────────────────────┬───────────────┬─────────┐
        │Interface                                   │ Attribute     │ Value   │
        ├────────────────────────────────────────────┼───────────────┼─────────┤
        │stpecpy(3)                                  │ Thread safety │ MT‐Safe │
        └────────────────────────────────────────────┴───────────────┴─────────┘

STANDARDS
        None.

EXAMPLES
        $ cc ./stpecpy.c $(pkgconf --cflags --libs libbsd-overlay libstp)
        $ ./a.out
        [len = 12]: Hello world!
        $

        // stpecpy.c
        #include <err.h>
        #include <stdio.h>
        #include <stdlib.h>

        #include <stp/stpe/stpecpy.h>
        #include <stp/stpe/stpeprintf.h>

        int
        main(void)
        {
            char    *p, *end;
            char    buf[BUFSIZ];
            size_t  len;

            end = buf + BUFSIZ;
            p = buf;
            p = stpecpy(p, end, "Hello, ");
            p = stpeprintf(p, end, "%d worlds", 22);
            p = stpecpy(p, end, "!");
            if (p == NULL)
                err(EXIT_FAILURE, "stpeprintf()");
            if (p == end) {
                p--;
                warnx("Truncated");
            }
            len = p - buf;
            printf("[len = %zu]: ", len);
            puts(buf);

            exit(EXIT_SUCCESS);
        }

SEE ALSO
        stpeprintf(3), string_copying(7)

libstp (unreleased)                 (date)                          stpecpy(3)
  

Patch

diff --git a/string/Makefile b/string/Makefile
index 938f528b8d..95e9ebce6d 100644
--- a/string/Makefile
+++ b/string/Makefile
@@ -73,6 +73,7 @@  routines := \
   sigabbrev_np \
   sigdescr_np \
   stpcpy \
+  stpecpy \
   stpncpy \
   strcasecmp \
   strcasecmp_l \
diff --git a/string/stpecpy.c b/string/stpecpy.c
new file mode 100644
index 0000000000..6884a949a0
--- /dev/null
+++ b/string/stpecpy.c
@@ -0,0 +1,45 @@ 
+/* Copyright (C) 2022 Free Software Foundation, Inc.
+   This file is part of the GNU C Library.
+
+   The GNU C Library is free software; you can redistribute it and/or
+   modify it under the terms of the GNU Lesser General Public
+   License as published by the Free Software Foundation; either
+   version 2.1 of the License, or (at your option) any later version.
+
+   The GNU C Library is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+   Lesser General Public License for more details.
+
+   You should have received a copy of the GNU Lesser General Public
+   License along with the GNU C Library; if not, see
+   <https://www.gnu.org/licenses/>.  */
+
+#ifdef HAVE_CONFIG_H
+# include <config.h>
+#endif
+
+#include <stdbool.h>
+#include <string.h>
+
+char *
+stpecpy(char *dst, char *end, const char *restrict src)
+{
+	bool    trunc;
+	size_t  dsize, dlen, slen;
+
+	if (dst == end)
+		return end;
+	if (dst == NULL)  // Allow chaining with stpeprintf().
+		return NULL;
+	if (dst > end)
+		__builtin_unreachable();
+
+	dsize = end - dst;
+	slen = strnlen(src, dsize);
+	trunc = (slen == dsize);
+	dlen = slen - trunc;
+	dst[dlen] = '\0';
+
+	return mempcpy(dst, src, dlen) + trunc;
+}
diff --git a/string/string.h b/string/string.h
index 54dd8344de..966a8cb744 100644
--- a/string/string.h
+++ b/string/string.h
@@ -502,6 +502,13 @@  extern char *stpncpy (char *__restrict __dest,
 #endif
 
 #ifdef	__USE_GNU
+/* Copy the string SRC into a null-terminated string at DEST,
+   truncating if it would run after END.  Return a pointer to
+   the terminating null byte, or END if the string was truncated,
+   or NULL if DEST was NULL. */
+extern char *stpecpy (char *__dest, char *__end, const char *__restrict __src)
+     __THROW __nonnull ((2, 3));
+
 /* Compare S1 and S2 as strings holding name & indices/version numbers.  */
 extern int strverscmp (const char *__s1, const char *__s2)
      __THROW __attribute_pure__ __nonnull ((1, 2));