Skip to content

Commit

Permalink
move StringPiece to separate file
Browse files Browse the repository at this point in the history
  • Loading branch information
profezzorn committed Apr 5, 2024
1 parent a3361b1 commit bac8e8f
Showing 1 changed file with 49 additions and 0 deletions.
49 changes: 49 additions & 0 deletions common/string_piece.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#ifndef COMMON_STRING_PIECE_H
#define COMMON_STRING_PIECE_H

class Print;
struct StringPiece {
StringPiece(const char* s) : str(s), len(strlen(s)) {}
StringPiece(const char* s, size_t l) : str(s), len(l) {}
StringPiece(const char* begin, const char* end) : str(begin), len(end >= begin ? end - begin : 0) {}
StringPiece() : str(0), len(0) {}
int cmp(const StringPiece& other) const {
const char* a = str;
const char* b = other.str;
size_t l = 0;
while (true) {
if (l == len && l == other.len) return 0;
if (l == len) return -1;
if (l == other.len) return 1;
char A = toLower(*a);
char B = toLower(*b);
if (A != B) return A < B ? -1 : 1;
a++;
b++;
l++;
}
}
bool operator<(const StringPiece& other) const { return cmp(other) < 0; }
bool operator>(const StringPiece& other) const { return cmp(other) > 0; }
bool operator<=(const StringPiece& other) const { return cmp(other) <= 0; }
bool operator>=(const StringPiece& other) const { return cmp(other) <= 0; }
bool operator==(const StringPiece& other) const { return cmp(other) == 0; }
bool operator!=(const StringPiece& other) const { return cmp(other) != 0; }
char operator[](size_t x) const { return str[x]; }
explicit operator bool() const { return str != nullptr && len != 0; }

void printTo(Print& p);
void paste(char* to) const { memcpy(to, str, len); }

bool contains(char c) const {
for (size_t i = 0; i < len; i++) {
if (str[i] == c) return true;
}
return false;
}

const char* str;
size_t len;
};

#endif

0 comments on commit bac8e8f

Please sign in to comment.