diff --git a/xo-object2/include/xo/object2/DString.hpp b/xo-object2/include/xo/object2/DString.hpp index 6f3fa4ec..39890498 100644 --- a/xo-object2/include/xo/object2/DString.hpp +++ b/xo-object2/include/xo/object2/DString.hpp @@ -164,6 +164,11 @@ namespace xo { return size_; } + /** lexicographically compare two strings. + * @return <0 if lhs < rhs, 0 if equal, >0 if lhs > rhs + **/ + static int compare(const DString & lhs, const DString & rhs) noexcept; + // TODO - behave like std::string, to the extent feasible // insert // insert_range @@ -181,7 +186,6 @@ namespace xo { // find_first_not_of // find_last_of // find_last_not_of - // compare // starts_with // end_with // contains diff --git a/xo-object2/src/object2/DString.cpp b/xo-object2/src/object2/DString.cpp index 8787f687..d96f712b 100644 --- a/xo-object2/src/object2/DString.cpp +++ b/xo-object2/src/object2/DString.cpp @@ -84,6 +84,12 @@ namespace xo { return *this; } + int + DString::compare(const DString & lhs, const DString & rhs) noexcept + { + return ::strcmp(lhs.chars_, rhs.chars_); + } + auto DString::fixup_size() noexcept -> size_type { diff --git a/xo-object2/utest/DString.test.cpp b/xo-object2/utest/DString.test.cpp index 226d63c8..c779c42f 100644 --- a/xo-object2/utest/DString.test.cpp +++ b/xo-object2/utest/DString.test.cpp @@ -292,6 +292,25 @@ namespace xo { REQUIRE(s->size() == 7); REQUIRE(std::strcmp(s->chars(), "hello w") == 0); } + + TEST_CASE("DString-compare", "[object2][DString]") + { + ArenaConfig cfg { .name_ = "testarena", + .size_ = 4*1024 }; + DArena arena = DArena::map(cfg); + auto alloc = with_facet::mkobj(&arena); + + DString * s1 = DString::from_cstr(alloc, "apple"); + DString * s2 = DString::from_cstr(alloc, "apple"); + DString * s3 = DString::from_cstr(alloc, "banana"); + DString * s4 = DString::from_cstr(alloc, "aardvark"); + + REQUIRE(DString::compare(*s1, *s2) == 0); + REQUIRE(DString::compare(*s1, *s3) < 0); + REQUIRE(DString::compare(*s3, *s1) > 0); + REQUIRE(DString::compare(*s1, *s4) > 0); + REQUIRE(DString::compare(*s4, *s1) < 0); + } } /*namespace ut*/ } /*namespace xo*/