Skip to content

Commit 0dac6e8

Browse files
committed
str copy (w/ zero size) fix
1 parent 8bb5f4a commit 0dac6e8

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

ctl/str.h

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@
1515
#define str_init str___INIT
1616
#define str_equal str___EQUAL
1717
#define str_find str___FIND
18+
#define str_copy str___COPY
1819
#include <vec.h>
1920
#undef str_init
21+
#undef str_copy
2022
#undef str_equal
2123
#undef str_find
2224
#undef vec_char
@@ -46,6 +48,14 @@ str_append(str* self, const char* s)
4648
self->value[start + i] = s[i];
4749
}
4850

51+
static inline str
52+
str_copy(str* s)
53+
{
54+
str other = str_init("");
55+
str_append(&other, s->value);
56+
return other;
57+
}
58+
4959
static inline void
5060
str_insert_str(str* self, size_t index, const char* s)
5161
{

tests/func/test_str.cc

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,12 +52,28 @@ char_compare(char* a, char* b)
5252
return *a > *b;
5353
}
5454

55+
static void
56+
test_zero_size_copy(void)
57+
{
58+
str a = str_init("");
59+
str b = str_copy(&a);
60+
std::string aa = "";
61+
std::string bb = aa;
62+
assert(aa.size() == a.size);
63+
assert(bb.size() == b.size);
64+
assert(aa.capacity() == a.capacity);
65+
assert(bb.capacity() == b.capacity);
66+
str_free(&a);
67+
str_free(&b);
68+
}
69+
5570
int
5671
main(void)
5772
{
5873
#ifdef SRAND
5974
srand(time(NULL));
6075
#endif
76+
test_zero_size_copy();
6177
const size_t loops = TEST_RAND(TEST_MAX_LOOPS);
6278
for(size_t loop = 0; loop < loops; loop++)
6379
{

0 commit comments

Comments
 (0)