C++ API Reference RNBO: common/RNBO_String.h Source File

RNBO: common/RNBO_String.h Source File

1 //
2 // RNBO_String.h
3 //
4 // Created by Jeremy Bernstein on 5/9/16.
5 //
6 //
7 
8 #ifndef _RNBO_String_H_
9 #define _RNBO_String_H_
10 
11 #include "RNBO_PlatformInterface.h"
12 
13 namespace RNBO {
14 
18  class String {
19 
20  public:
21 
25  String() : _ptr(new char[1]), _len(0), _truelen(1) { _ptr[0] = '\0'; }
26 
32  String(const char* str) : _ptr(nullptr), _len(0), _truelen(0) { copy(str); }
33 
39  String(String const& str) : _ptr(nullptr), _len(0), _truelen(0) { copy(str._ptr); }
40 
44  ~String() { delete[] _ptr; }
45 
51  size_t len() const { return _len; }
52 
56  void clear() { if (_ptr) _ptr[0] = '\0'; _len = 0; }
57 
64  bool empty() const { return _len == 0; }
65 
71  void append(const char* astr) {
72  size_t alen = Platform::get()->strlen(astr);
73  size_t newlen = alen + _len;
74 
75  if (newlen >= _truelen) {
76  char* oldptr = _ptr;
77 
78  if (_truelen < 16) _truelen = 16;
79  while (newlen >= _truelen)
80  _truelen *= 2;
81  _ptr = new char[_truelen];
82  Platform::get()->memcpy(_ptr, oldptr, _len);
83  if (oldptr)
84  delete[] oldptr;
85  }
86  Platform::get()->memcpy(_ptr + _len, astr, alen);
87  _ptr[newlen] = '\0';
88  _len = newlen;
89  }
90 
96  void append(String& astr) {
97  append(astr._ptr);
98  }
99 
105  const char* c_str() const { return const_cast<const char*>(_ptr); }
106 
113  String& operator = (const String& origin) { copy(origin._ptr); return *this; }
114 
121  String& operator = (const char* origin) { copy(origin); return *this; }
122 
131  String& operator += (const String& origin) { append(origin._ptr); return *this; }
132 
141  String& operator += (const char* origin) { append(origin); return *this; }
142 
150  friend String operator+ (String& str1, String& str2);
151 
159  bool operator==(const String& other) const {
160  return Platform::get()->strcmp(_ptr, other._ptr) == 0;
161  }
162 
170  bool operator<(const String& other) const {
171  return (Platform::get()->strcmp(_ptr, other._ptr)) < 0 ? true : false;
172  }
173 
181  bool operator>(const String& other) const {
182  return (Platform::get()->strcmp(_ptr, other._ptr)) > 0 ? true : false;
183  }
184 
185  friend struct StringHasher;
186 
187  private:
188 
189  int copy(const char* origin) {
190  clear();
191  append(origin);
192  return 0;
193  }
194 
195  char* _ptr;
196  size_t _len;
197  size_t _truelen;
198  };
199 
207  inline String operator+ (String& str1, String& str2) {
208  String* newstr = new String(str1);
209  newstr->append(str2._ptr);
210  return *newstr;
211  }
212 
216  struct StringHasher {
217 
224  size_t operator()(const String& k) const {
225  const char* str = k.c_str();
226  return TAG(str);
227  }
228  };
229 
230 } // namespace RNBO
231 
232 #endif // #ifndef _RNBO_String_H_