+2016-11-30 David Malcolm <dmalcolm@redhat.com>
+
+ PR c/78498
+ * selftest.c (selftest::assert_strndup_eq): New function.
+ (selftest::test_strndup): New function.
+ (selftest::test_libiberty): New function.
+ (selftest::selftest_c_tests): Call test_libiberty.
+
2016-11-30 Segher Boessenkool <segher@kernel.crashing.org>
PR rtl-optimization/78610
return result;
}
+/* Selftests for libiberty. */
+
+/* Verify that both strndup and xstrndup generate EXPECTED
+ when called on SRC and N. */
+
+static void
+assert_strndup_eq (const char *expected, const char *src, size_t n)
+{
+ char *buf = strndup (src, n);
+ if (buf)
+ ASSERT_STREQ (expected, buf);
+ free (buf);
+
+ buf = xstrndup (src, n);
+ ASSERT_STREQ (expected, buf);
+ free (buf);
+}
+
+/* Verify that strndup and xstrndup work as expected. */
+
+static void
+test_strndup ()
+{
+ assert_strndup_eq ("", "test", 0);
+ assert_strndup_eq ("t", "test", 1);
+ assert_strndup_eq ("te", "test", 2);
+ assert_strndup_eq ("tes", "test", 3);
+ assert_strndup_eq ("test", "test", 4);
+ assert_strndup_eq ("test", "test", 5);
+
+ /* Test on an string without zero termination. */
+ const char src[4] = {'t', 'e', 's', 't'};
+ assert_strndup_eq ("", src, 0);
+ assert_strndup_eq ("t", src, 1);
+ assert_strndup_eq ("te", src, 2);
+ assert_strndup_eq ("tes", src, 3);
+ assert_strndup_eq ("test", src, 4);
+}
+
+/* Run selftests for libiberty. */
+
+static void
+test_libiberty ()
+{
+ test_strndup ();
+}
+
/* Selftests for the selftest system itself. */
/* Sanity-check the ASSERT_ macros with various passing cases. */
void
selftest_c_tests ()
{
+ test_libiberty ();
test_assertions ();
test_named_temp_file ();
test_read_file ();
#include "ansidecl.h"
#include <stddef.h>
-extern size_t strlen (const char*);
+extern size_t strnlen (const char *s, size_t maxlen);
extern PTR malloc (size_t);
extern PTR memcpy (PTR, const PTR, size_t);
strndup (const char *s, size_t n)
{
char *result;
- size_t len = strlen (s);
-
- if (n < len)
- len = n;
+ size_t len = strnlen (s, n);
result = (char *) malloc (len + 1);
if (!result)