123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147 |
- #ifndef STRINGBUFFER_H
- #define STRINGBUFFER_H
- #include <cstring>
- #include <iostream>
- #include "utils/Types.h"
- template<int N>
- class StringBuffer final {
- int length;
- Hash hash;
- char data[N];
- void addToHash(char c) {
- hash = 2120251889 * hash + c;
- }
- void addToHash(int from, int to) {
- for(int i = from; i < to; i++) {
- addToHash(data[i]);
- }
- }
- public:
- StringBuffer() : length(0), hash(0) {
- data[0] = '\0';
- }
- template<typename T>
- StringBuffer(const T& t) : StringBuffer() {
- append(t);
- }
- bool operator==(const char* str) const {
- return strcmp(data, str) == 0;
- }
- bool operator==(const StringBuffer& other) const {
- return length == other.length && other == data;
- }
- bool operator!=(const char* str) const {
- return !((*this) == str);
- }
- bool operator!=(const StringBuffer& other) const {
- return !((*this) == other);
- }
- operator const char*() const {
- return data;
- }
- char operator[](int index) const {
- return data[index];
- }
- int getLength() const {
- return length;
- }
- StringBuffer& append(char c) {
- if(length < N - 1) {
- data[length++] = c;
- addToHash(c);
- data[length] = '\0';
- }
- return *this;
- }
- StringBuffer& append(const char* str) {
- for(int i = 0; length < N - 1 && str[i] != '\0'; length++, i++) {
- data[length] = str[i];
- addToHash(str[i]);
- }
- data[length] = '\0';
- return *this;
- }
- StringBuffer& append(char* str) {
- return append(static_cast<const char*>(str));
- }
- template<typename T>
- StringBuffer& append(const char* format, const T& t) {
- int left = N - length;
- int written = snprintf(data + length, left, format, t);
- int oldLength = length;
- if(written < left) {
- length += written;
- } else {
- length = N - 1;
- }
- addToHash(oldLength, length);
- return *this;
- }
- StringBuffer& append(int i) {
- return append("%d", i);
- }
- StringBuffer& append(float i) {
- return append("%.2f", i);
- }
- StringBuffer& append(bool b) {
- return b ? append("true") : append("false");
- }
- template<typename T>
- StringBuffer& append(const T& t) {
- t.toString(*this);
- return *this;
- }
- StringBuffer& clear() {
- length = 0;
- hash = 0;
- data[0] = '\0';
- return *this;
- }
- Hash hashCode() const {
- return hash;
- }
- void print() {
- std::cout << data;
- }
- void printLine() {
- std::cout << data << '\n';
- }
- };
- template<int N>
- bool operator==(const char* str, const StringBuffer<N> buffer) {
- return buffer == str;
- }
- template<int N>
- bool operator!=(const char* str, const StringBuffer<N> buffer) {
- return buffer != str;
- }
- #endif
|