aboutsummaryrefslogtreecommitdiffstatshomepage
diff options
authorLuc Van Oostenryck <luc.vanoostenryck@gmail.com>2018-06-06 21:28:29 +0200
committerLuc Van Oostenryck <luc.vanoostenryck@gmail.com>2018-06-08 17:07:08 +0200
commit4e0624c3b8dd0d543d7d47db6f7e9827cd1a3da2 (patch)
tree8b2b57fdeadb655281520f73264637b626ed97be
parentfb1d00d35713111043391bdf4a0e182552d691ec (diff)
downloadsparse-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.rst1
-rw-r--r--Makefile1
-rw-r--r--lib.h1
-rw-r--r--utils.c17
-rw-r--r--utils.h25
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
~~~~~~~
diff --git a/Makefile b/Makefile
index c89f2c85..0b6c32cf 100644
--- a/Makefile
+++ b/Makefile
@@ -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
diff --git a/lib.h b/lib.h
index 4d613936..0e5f3e4a 100644
--- a/lib.h
+++ b/lib.h
@@ -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