add mrb_debug_strdup() and mrb_debug_strndup()
authorcremno <[email protected]>
Tue, 25 Nov 2014 23:52:54 +0000 (26 00:52 +0100)
committercremno <[email protected]>
Mon, 1 Dec 2014 23:00:54 +0000 (2 00:00 +0100)
They behave similar to their POSIX equivalents, except
mrb_malloc_simple() is used for memory allocation and
errno might not be set since ISO C99 doesn't have ENOMEM.

mrbgems/mruby-bin-debugger/tools/mrdb/apistring.c [new file with mode: 0644]
mrbgems/mruby-bin-debugger/tools/mrdb/apistring.h [new file with mode: 0644]

diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apistring.c b/mrbgems/mruby-bin-debugger/tools/mrdb/apistring.c
new file mode 100644 (file)
index 0000000..4cf528f
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+** apistring.c
+**
+*/
+
+#include <string.h>
+#include "apistring.h"
+
+static size_t
+mrb_debug_strnlen(const char *s, size_t maxlen)
+{
+  const char *p = memchr(s, '\0', maxlen);
+  return p != NULL ? (size_t)(p - s) : maxlen;
+}
+
+char*
+mrb_debug_strndup(mrb_state *mrb, const char *s, size_t size)
+{
+  size_t l = mrb_debug_strnlen(s, size);
+  char *d = mrb_malloc_simple(mrb, l + 1);
+  if (d != NULL) {
+    memcpy(d, s, l);
+    d[l] = '\0';
+  }
+  return d;
+}
+
+char*
+mrb_debug_strdup(mrb_state *mrb, const char *s)
+{
+  size_t z = strlen(s) + 1;
+  char *d = mrb_malloc_simple(mrb, z);
+  return d != NULL ? memcpy(d, s, z) : NULL;
+}
diff --git a/mrbgems/mruby-bin-debugger/tools/mrdb/apistring.h b/mrbgems/mruby-bin-debugger/tools/mrdb/apistring.h
new file mode 100644 (file)
index 0000000..e48478d
--- /dev/null
@@ -0,0 +1,14 @@
+/*
+ * apistring.h
+ */
+
+#ifndef APISTRING_H_
+#define APISTRING_H_
+
+#include "mruby.h"
+
+/* both functions return a null pointer on failure */
+char *mrb_debug_strndup(mrb_state *mrb, const char *s, size_t size);
+char *mrb_debug_strdup(mrb_state *mrb, const char *s);
+
+#endif /* APISTRING_H_ */