Jelajahi Sumber

SCDString_alloc_copy function.

Aaro Saila 1 bulan lalu
induk
melakukan
b5a27e45e4
3 mengubah file dengan 26 tambahan dan 0 penghapusan
  1. 1 0
      include/scufcont/DString.h
  2. 7 0
      src/DString.c
  3. 18 0
      tests/cmocka/DString_tests.c

+ 1 - 0
include/scufcont/DString.h

@@ -18,6 +18,7 @@ typedef struct {
 } SCDString;
 
 ScufContResult SCDString_alloc(SCDString *const dstr, const char *str, const size_t len);
+ScufContResult SCDString_alloc_copy(SCDString *const dstr, const SCDString *const o);
 ScufContResult SCDString_reserve(SCDString *const dstr, const size_t new_capacity);
 void SCDString_free(SCDString *const dstr);
 ScufContResult SCDString_copy(const SCDString *const src, SCDString *const dst);

+ 7 - 0
src/DString.c

@@ -19,6 +19,13 @@ ScufContResult SCDString_alloc(SCDString *const dstr, const char *str, const siz
     return SCUFCONT_SUCCESS;
 }
 
+/**
+  @param dstr Must not be allocated with any of the alloc functions. This functions allocates it.
+*/
+ScufContResult SCDString_alloc_copy(SCDString *const dstr, const SCDString *const o) {
+    return SCDString_alloc(dstr, SCDString_c_str(o), o->len);
+}
+
 ScufContResult SCDString_reserve(SCDString *const dstr, const size_t new_capacity) {
     if (dstr->capacity < new_capacity) {
         errno = 0;

+ 18 - 0
tests/cmocka/DString_tests.c

@@ -21,6 +21,23 @@ void test_SCDString_alloc(void **state) {
     free(dstr.data);
 }
 
+void test_SCDString_alloc_copy(void **state) {
+    (void) state;
+
+    SCDString dstr;
+    assert_true(SCDString_alloc(&dstr, "Hello", strlen("Hello")) == SCUFCONT_SUCCESS);
+    assert_string_equal(SCDString_c_str(&dstr), "Hello");
+    assert_uint_equal(dstr.len, strlen("Hello"));
+
+    SCDString cpy;
+    assert_true(SCDString_alloc_copy(&cpy, &dstr) == SCUFCONT_SUCCESS);
+    assert_string_equal(SCDString_c_str(&dstr), "Hello");
+    assert_uint_equal(dstr.len, strlen("Hello"));
+
+    SCDString_free(&dstr);
+    SCDString_free(&cpy);
+}
+
 void test_SCDString_free(void **state) {
     (void) state;
 
@@ -273,6 +290,7 @@ void test_SCDString_char_insert(void **state) {
 int DString_tests_run(void) {
     const struct CMUnitTest tests[] = {
         cmocka_unit_test(test_SCDString_alloc),
+        cmocka_unit_test(test_SCDString_alloc_copy),
         cmocka_unit_test(test_SCDString_free),
         cmocka_unit_test(test_SCDString_copy),
         cmocka_unit_test(test_SCDString_equal),