jcs
/subtext
/amendments
/16
util: add xmallocarray and strlcpy
jcs made amendment 16 over 2 years ago
--- util.c Mon Dec 6 09:08:13 2021
+++ util.c Mon Dec 6 15:57:08 2021
@@ -88,18 +88,23 @@ xrealloc(void *src, size_t size)
#define MUL_NO_OVERFLOW ((size_t)1 << (sizeof(size_t) * 4))
void *
+xmallocarray(size_t nmemb, size_t size)
+{
+ if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
+ nmemb > 0 && SIZE_MAX / nmemb < size)
+ err(2, "xmallocarray");
+ return xmalloc(size * nmemb);
+}
+
+void *
xreallocarray(void *optr, size_t nmemb, size_t size)
{
void *new_ptr;
if ((nmemb >= MUL_NO_OVERFLOW || size >= MUL_NO_OVERFLOW) &&
- nmemb > 0 && SIZE_MAX / nmemb < size) {
- err(2, "reallocarray");
- }
- if ((new_ptr = realloc(optr, size * nmemb)) == NULL)
- err(2, "realloc");
-
- return new_ptr;
+ nmemb > 0 && SIZE_MAX / nmemb < size)
+ err(2, "xreallocarray");
+ return xrealloc(optr, size * nmemb);
}
char *
@@ -137,6 +142,29 @@ getline(char *str, size_t len, char **ret)
}
return 0;
+}
+
+size_t
+strlcpy(char *dst, const char *src, size_t dsize)
+{
+ const char *osrc = src;
+ size_t nleft = dsize;
+
+ if (nleft != 0) {
+ while (--nleft != 0) {
+ if ((*dst++ = *src++) == '\0')
+ break;
+ }
+ }
+
+ if (nleft == 0) {
+ if (dsize != 0)
+ *dst = '\0';
+ while (*src++)
+ ;
+ }
+
+ return (src - osrc - 1);
}
/*
--- util.h Mon Dec 6 09:08:31 2021
+++ util.h Mon Dec 6 15:57:30 2021
@@ -57,10 +57,12 @@ void *xmalloc(size_t);
void *xmalloczero(size_t);
void *xcalloc(size_t, size_t);
void *xrealloc(void *src, size_t size);
+void *xmallocarray(size_t nmemb, size_t size);
void *xreallocarray(void *, size_t, size_t);
char *xstrdup(const char *);
short getline(char *str, size_t len, char **ret);
+size_t strlcpy(char *dst, const char *src, size_t dsize);
#if 0
/* from strnatcmp.c */
int strnatcmp(char const *a, char const *b);