xo-object2: + DString::from_view()

This commit is contained in:
Roland Conybeare 2026-01-15 19:37:32 -05:00
commit 2edfb56530
3 changed files with 50 additions and 0 deletions

View file

@ -72,6 +72,12 @@ namespace xo {
static DString * from_cstr(obj<AAllocator> mm,
const char * cstr);
/** create string containing a copy of @p sv.
* Use memory from allocator @p mm
**/
static DString * from_view(obj<AAllocator> mm,
std::string_view sv);
/** clone existing string **/
static DString * clone(obj<AAllocator> mm,
const DString * src);

View file

@ -57,6 +57,25 @@ namespace xo {
return result;
}
DString *
DString::from_view(obj<AAllocator> mm,
std::string_view sv)
{
size_type len = sv.size();
size_type cap = len + 1;
void * mem = mm.alloc(typeseq::id<DString>(),
sizeof(DString) + cap);
DString * result = new (mem) DString();
result->capacity_ = cap;
result->size_ = len;
std::memcpy(result->chars_, sv.data(), len);
result->chars_[len] = '\0';
return result;
}
DString *
DString::clone(obj<AAllocator> mm, const DString * src)
{

View file

@ -50,6 +50,31 @@ namespace xo {
REQUIRE(std::strcmp(s->chars(), cstr) == 0);
}
TEST_CASE("DString-from_view", "[object2][DString]")
{
ArenaConfig cfg { .name_ = "testarena",
.size_ = 4*1024 };
DArena arena = DArena::map(cfg);
auto alloc = with_facet<AAllocator>::mkobj(&arena);
std::string_view sv = "hello world";
DString * s = DString::from_view(alloc, sv);
REQUIRE(s != nullptr);
REQUIRE(s->capacity() == 12);
REQUIRE(s->size() == 11);
REQUIRE(std::strcmp(s->chars(), "hello world") == 0);
// test with substring (not null-terminated)
std::string_view sub = sv.substr(0, 5);
DString * s2 = DString::from_view(alloc, sub);
REQUIRE(s2 != nullptr);
REQUIRE(s2->capacity() == 6);
REQUIRE(s2->size() == 5);
REQUIRE(std::strcmp(s2->chars(), "hello") == 0);
}
TEST_CASE("DString-assign", "[object2][DString]")
{
ArenaConfig cfg { .name_ = "testarena",