ImmutableString, StringRef: Add empty() and operator[]
We won't add operator[] to StringRef. This is because it may be undefined if pos == size(), and StringRef's base + len does not point to the valid region. This solely depends on the given buffer, so we cannot do anything to fix. For workaround, if we need this kind of operator, we may add it under another name, like char_at(size_type).
This commit is contained in:
parent
5131b95c2f
commit
eb7b3295d1
|
@ -281,6 +281,8 @@ public:
|
|||
|
||||
const char *c_str() const { return base; }
|
||||
size_type size() const { return len; }
|
||||
bool empty() const { return len == 0; }
|
||||
const_reference operator[](size_type pos) const { return *(base + pos); }
|
||||
|
||||
private:
|
||||
size_type len;
|
||||
|
@ -323,6 +325,7 @@ public:
|
|||
|
||||
const char *c_str() const { return base; }
|
||||
size_type size() const { return len; }
|
||||
bool empty() const { return len == 0; }
|
||||
|
||||
std::string str() const { return std::string(base, len); }
|
||||
|
||||
|
|
|
@ -38,11 +38,13 @@ void test_template_immutable_string(void) {
|
|||
|
||||
CU_ASSERT("" == null);
|
||||
CU_ASSERT(0 == null.size());
|
||||
CU_ASSERT(null.empty());
|
||||
|
||||
ImmutableString from_cstr("alpha");
|
||||
|
||||
CU_ASSERT(0 == strcmp("alpha", from_cstr.c_str()));
|
||||
CU_ASSERT(5 == from_cstr.size());
|
||||
CU_ASSERT(!from_cstr.empty());
|
||||
CU_ASSERT("alpha" == from_cstr);
|
||||
CU_ASSERT(from_cstr == "alpha");
|
||||
CU_ASSERT(std::string("alpha") == from_cstr);
|
||||
|
@ -95,6 +97,14 @@ void test_template_immutable_string(void) {
|
|||
CU_ASSERT("delt" != eq);
|
||||
CU_ASSERT(eq != "delta1");
|
||||
CU_ASSERT(eq != "delt");
|
||||
|
||||
// operator[]
|
||||
ImmutableString br_op("foxtrot");
|
||||
|
||||
CU_ASSERT('f' == br_op[0]);
|
||||
CU_ASSERT('o' == br_op[1]);
|
||||
CU_ASSERT('t' == br_op[6]);
|
||||
CU_ASSERT('\0' == br_op[7]);
|
||||
}
|
||||
|
||||
void test_template_string_ref(void) {
|
||||
|
|
Loading…
Reference in New Issue