diff --git a/xo-object2/src/object2/DString.cpp b/xo-object2/src/object2/DString.cpp index 0fad514e..7f5aee15 100644 --- a/xo-object2/src/object2/DString.cpp +++ b/xo-object2/src/object2/DString.cpp @@ -4,6 +4,7 @@ **/ #include "DString.hpp" +#include namespace xo { using xo::facet::typeseq; @@ -31,6 +32,24 @@ namespace xo { return result; } + + DString * + DString::from_cstr(obj mm, + const char * cstr) + { + size_type len = std::strlen(cstr); + size_type cap = len + 1; + + void * mem = mm.alloc(typeseq::id(), + sizeof(DString) + cap); + + DString * result = new (mem) DString(); + result->capacity_ = cap; + result->size_ = len; + std::memcpy(result->chars_, cstr, cap); + + return result; + } } /*namespace scm*/ } /*namespace xo*/ diff --git a/xo-object2/utest/DString.test.cpp b/xo-object2/utest/DString.test.cpp index da4d8ca4..c3437b6b 100644 --- a/xo-object2/utest/DString.test.cpp +++ b/xo-object2/utest/DString.test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include namespace xo { using xo::scm::DString; @@ -30,6 +31,22 @@ namespace xo { REQUIRE(s->size() == 0); REQUIRE(s->chars()[0] == '\0'); } + + TEST_CASE("DString-from_cstr", "[object2][DString]") + { + ArenaConfig cfg { .name_ = "testarena", + .size_ = 4*1024 }; + DArena arena = DArena::map(cfg); + auto alloc = with_facet::mkobj(&arena); + + const char * cstr = "hello world"; + DString * s = DString::from_cstr(alloc, cstr); + + REQUIRE(s != nullptr); + REQUIRE(s->capacity() == 12); + REQUIRE(s->size() == 11); + REQUIRE(std::strcmp(s->chars(), cstr) == 0); + } } /*namespace ut*/ } /*namespace xo*/