diff --git a/lib/bytes.cc b/lib/bytes.cc index 532dd1c9..23610295 100644 --- a/lib/bytes.cc +++ b/lib/bytes.cc @@ -41,6 +41,12 @@ Bytes::Bytes(const uint8_t* ptr, size_t len): _high(len) {} +Bytes::Bytes(const std::string& s): + _data(createVector((const uint8_t*)&s[0], s.size())), + _low(0), + _high(s.size()) +{} + Bytes::Bytes(std::initializer_list data): _data(createVector(data)), _low(0), diff --git a/lib/bytes.h b/lib/bytes.h index 0a5d82c9..d7651770 100644 --- a/lib/bytes.h +++ b/lib/bytes.h @@ -41,6 +41,8 @@ public: uint8_t* begin() { checkWritable(); return &(*_data)[_low]; } uint8_t* end() { checkWritable(); return &(*_data)[_high]; } + operator const std::string () const { return std::string(cbegin(), cend()); } + void boundsCheck(unsigned pos) const; void checkWritable(); void adjustBounds(unsigned pos); diff --git a/tests/bytes.cc b/tests/bytes.cc index 05233b3f..5e8be65e 100644 --- a/tests/bytes.cc +++ b/tests/bytes.cc @@ -124,6 +124,13 @@ static void test_tobits() })); } +static void test_tostring() +{ + std::string s = "Hello, world"; + Bytes b(s); + assert(b == s); +} + int main(int argc, const char* argv[]) { test_bounds(); @@ -133,5 +140,6 @@ int main(int argc, const char* argv[]) test_writes(); test_slice(); test_tobits(); + test_tostring(); return 0; }