From 1e06c66c776e2dca217059d7d94309b0c5431a3f Mon Sep 17 00:00:00 2001
From: Max Kellermann <max@duempel.org>
Date: Sat, 1 Mar 2014 09:19:32 +0100
Subject: java: new helper library for the Android port

---
 src/util/StringUtil.cxx | 14 ++++++++++++++
 src/util/StringUtil.hxx | 14 ++++++++++++++
 2 files changed, 28 insertions(+)

(limited to 'src/util')

diff --git a/src/util/StringUtil.cxx b/src/util/StringUtil.cxx
index 9a1a74f86..50885a34a 100644
--- a/src/util/StringUtil.cxx
+++ b/src/util/StringUtil.cxx
@@ -21,6 +21,8 @@
 #include "CharUtil.hxx"
 #include "ASCII.hxx"
 
+#include <algorithm>
+
 #include <assert.h>
 #include <string.h>
 
@@ -65,6 +67,18 @@ StringEndsWith(const char *haystack, const char *needle)
 		       needle, needle_length) == 0;
 }
 
+char *
+CopyString(char *gcc_restrict dest, const char *gcc_restrict src, size_t size)
+{
+	size_t length = strlen(src);
+	if (length >= size)
+		length = size - 1;
+
+	char *p = std::copy(src, src + length, dest);
+	*p = '\0';
+	return p;
+}
+
 bool
 string_array_contains(const char *const* haystack, const char *needle)
 {
diff --git a/src/util/StringUtil.hxx b/src/util/StringUtil.hxx
index 779d5d776..e8e3b2b5d 100644
--- a/src/util/StringUtil.hxx
+++ b/src/util/StringUtil.hxx
@@ -22,6 +22,8 @@
 
 #include "Compiler.h"
 
+#include <stddef.h>
+
 /**
  * Returns a pointer to the first non-whitespace character in the
  * string, or to the end of the string.
@@ -55,6 +57,18 @@ gcc_pure
 bool
 StringEndsWith(const char *haystack, const char *needle);
 
+/**
+ * Copy a string.  If the buffer is too small, then the string is
+ * truncated.  This is a safer version of strncpy().
+ *
+ * @param size the size of the destination buffer (including the null
+ * terminator)
+ * @return a pointer to the null terminator
+ */
+gcc_nonnull_all
+char *
+CopyString(char *dest, const char *src, size_t size);
+
 /**
  * Checks whether a string array contains the specified string.
  *
-- 
cgit v1.2.3