diff options
| author | Luc Van Oostenryck <luc.vanoostenryck@gmail.com> | 2018-06-06 21:28:29 +0200 |
|---|---|---|
| committer | Luc Van Oostenryck <luc.vanoostenryck@gmail.com> | 2018-06-08 17:07:08 +0200 |
| commit | 4e0624c3b8dd0d543d7d47db6f7e9827cd1a3da2 (patch) | |
| tree | 8b2b57fdeadb655281520f73264637b626ed97be | |
| parent | fb1d00d35713111043391bdf4a0e182552d691ec (diff) | |
| download | sparse-dev-4e0624c3b8dd0d543d7d47db6f7e9827cd1a3da2.tar.gz | |
utils: add xmemdup() & xstrdup()
Add small helpers for copying a memory buffer or a string
into a newly allocated buffer.
Signed-off-by: Luc Van Oostenryck <luc.vanoostenryck@gmail.com>
| -rw-r--r-- | Documentation/api.rst | 1 | ||||
| -rw-r--r-- | Makefile | 1 | ||||
| -rw-r--r-- | lib.h | 1 | ||||
| -rw-r--r-- | utils.c | 17 | ||||
| -rw-r--r-- | utils.h | 25 |
5 files changed, 45 insertions, 0 deletions
diff --git a/Documentation/api.rst b/Documentation/api.rst index d1a1d3ca..1270551c 100644 --- a/Documentation/api.rst +++ b/Documentation/api.rst @@ -9,6 +9,7 @@ Utilities ~~~~~~~~~ .. c:autodoc:: ptrlist.c +.. c:autodoc:: utils.h Parsing ~~~~~~~ @@ -61,6 +61,7 @@ LIB_OBJS += symbol.o LIB_OBJS += target.o LIB_OBJS += tokenize.o LIB_OBJS += unssa.o +LIB_OBJS += utils.o PROGRAMS := PROGRAMS += compile @@ -33,6 +33,7 @@ #include "compat.h" #include "ptrlist.h" +#include "utils.h" #define DO_STRINGIFY(x) #x #define STRINGIFY(x) DO_STRINGIFY(x) diff --git a/utils.c b/utils.c new file mode 100644 index 00000000..4945e1ca --- /dev/null +++ b/utils.c @@ -0,0 +1,17 @@ +// SPDX-License-Identifier: MIT +// Copyright (C) 2018 Luc Van Oostenryck + +#include "utils.h" +#include "allocate.h" +#include <string.h> + + +void *xmemdup(const void *src, size_t len) +{ + return memcpy(__alloc_bytes(len), src, len); +} + +char *xstrdup(const char *src) +{ + return xmemdup(src, strlen(src) + 1); +} diff --git a/utils.h b/utils.h new file mode 100644 index 00000000..38749be2 --- /dev/null +++ b/utils.h @@ -0,0 +1,25 @@ +#ifndef UTILS_H +#define UTILS_H + +/// +// Miscellaneous utilities +// ----------------------- + +#include <stddef.h> + +/// +// duplicate a memory buffer in a newly allocated buffer. +// @src: a pointer to the memory buffer to be duplicated +// @len: the size of the memory buffer to be duplicated +// @return: a pointer to a copy of @src allocated via +// :func:`__alloc_bytes()`. +void *xmemdup(const void *src, size_t len); + +/// +// duplicate a null-terminated string in a newly allocated buffer. +// @src: a pointer to string to be duplicated +// @return: a pointer to a copy of @str allocated via +// :func:`__alloc_bytes()`. +char *xstrdup(const char *src); + +#endif |
