ScummVM API documentation
string.h
1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21 
22 //=============================================================================
23 //
24 // String class with simple memory management and copy-on-write behavior.
25 //
26 // String objects do reference counting and share data buffer on assignment.
27 // The reallocation and copying is done only when the string is modified.
28 //
29 // The copying of memory inside buffer is reduced to minimum. If the string is
30 // truncated, it is not aligned to buffer head each time, instead the c-str
31 // pointer is advanced, or null-terminator is put on the new place. Similarly,
32 // when string is enlarged and new characters are prepended or appended, only
33 // c-str pointer and null-terminator's position are changed, if there's enough
34 // space before and after meaningful string data.
35 //
36 // The class provides means to reserve large amount of buffer space before
37 // making modifications, as well as compacting buffer to minimal size.
38 //
39 // For all methods that expect C-string as parameter - if the null pointer is
40 // passed in place of C-string it is treated in all aspects as a valid empty
41 // string.
42 //
43 //=============================================================================
44 
45 #ifndef AGS_SHARED_UTIL_STRING_H
46 #define AGS_SHARED_UTIL_STRING_H
47 
48 #include "common/str.h"
49 
50 #include "common/std/vector.h"
51 #include "ags/shared/core/platform.h"
52 #include "ags/shared/core/types.h"
53 
54 namespace AGS3 {
55 namespace AGS {
56 namespace Shared {
57 
58 class Stream;
59 
60 class String {
61 public:
62  static const size_t NoIndex = (size_t)-1;
63 
64  // Standard constructor: intialize empty string
65  String();
66  // Copy constructor
67  String(const String &);
68  // Move constructor
69  String(String &&);
70  // Initialize with C-string
71  String(const char *cstr);
72  // Initialize by copying up to N chars from C-string
73  String(const char *cstr, size_t length);
74  // Initialize by filling N chars with certain value
75  String(char c, size_t count);
76  // Initialize from a ScummVM string
77  String(const Common::String &s);
78  ~String();
79 
80  // Get underlying C-string for reading; this method guarantees valid C-string
81  inline const char *GetCStr() const {
82  return _cstr;
83  }
84  // Get character count
85  inline size_t GetLength() const {
86  return _len;
87  }
88  // Know if the string is empty (has no meaningful characters)
89  inline bool IsEmpty() const {
90  return _len == 0;
91  }
92  // Tells if the string is either empty or has only whitespace characters
93  bool IsNullOrSpace() const;
94 
95  // Those getters are for tests only, hence if AGS_PLATFORM_TEST
96 #if defined(AGS_PLATFORM_TEST) && AGS_PLATFORM_TEST
97  inline const char *GetBuffer() const {
98  return _buf;
99  }
100 
101  inline size_t GetCapacity() const {
102  return _bufHead ? _bufHead->Capacity : 0;
103  }
104 
105  inline size_t GetRefCount() const {
106  return _bufHead ? _bufHead->RefCount : 0;
107  }
108 #endif
109 
110  // Read() method implies that string length is initially unknown.
111  // max_chars parameter determine the buffer size limit.
112  // If stop_at_limit flag is set, it will read only up to the max_chars.
113  // Otherwise (by default) hitting the limit won't stop stream reading;
114  // the data will be read until null-terminator or EOS is met, and buffer
115  // will contain only leftmost part of the longer string that fits in.
116  // This method is better fit for reading from binary streams.
117  void Read(Stream *in, size_t max_chars = 5 * 1024 * 1024, bool stop_at_limit = false);
118  // ReadCount() reads up to N characters from stream, ignoring null-
119  // terminator. This method is better fit for reading from text
120  // streams, or when the length of string is known beforehand.
121  void ReadCount(Stream *in, size_t count);
122  // Write() puts the null-terminated string into the stream.
123  void Write(Stream *out) const;
124  // WriteCount() writes N characters to stream, filling the remaining
125  // space with null-terminators when needed.
126  void WriteCount(Stream *out, size_t count) const;
127 
128  //-------------------------------------------------------------------------
129  // String analysis methods
130  //-------------------------------------------------------------------------
131 
132  // Compares with given string
133  int Compare(const String &str) const {
134  return Compare(str._cstr);
135  }
136  int Compare(const char *cstr) const;
137  int CompareNoCase(const String &str) const {
138  return CompareNoCase(str._cstr);
139  }
140  int CompareNoCase(const char *cstr) const;
141  // Compares the leftmost part of this string with given string
142  int CompareLeft(const String &str, size_t count = -1) const {
143  return CompareLeft(str._cstr, count != NoIndex ? count : str._len);
144  }
145  int CompareLeft(const char *cstr, size_t count = -1) const;
146  int CompareLeftNoCase(const String &str, size_t count = -1) const {
147  return CompareLeftNoCase(str._cstr, count != NoIndex ? count : str._len);
148  }
149  int CompareLeftNoCase(const char *cstr, size_t count = -1) const;
150  // Compares any part of this string with given string
151  int CompareMid(const String &str, size_t from, size_t count = -1) const {
152  return CompareMid(str._cstr, from, count != NoIndex ? count : str._len);
153  }
154  int CompareMid(const char *cstr, size_t from, size_t count = -1) const;
155  int CompareMidNoCase(const String &str, size_t from, size_t count = -1) const {
156  return CompareMidNoCase(str._cstr, from, count != NoIndex ? count : str._len);
157  }
158  int CompareMidNoCase(const char *cstr, size_t from, size_t count = -1) const;
159  // Compares the rightmost part of this string with given C-string
160  int CompareRight(const String &str, size_t count = -1) const {
161  return CompareRight(str._cstr, count != NoIndex ? count : str._len);
162  }
163  int CompareRight(const char *cstr, size_t count = -1) const;
164  int CompareRightNoCase(const String &str, size_t count = -1) const {
165  return CompareRightNoCase(str._cstr, count != NoIndex ? count : str._len);
166  }
167  int CompareRightNoCase(const char *cstr, size_t count = -1) const;
168  // Convenience aliases for Compare functions
169  inline bool Equals(const String &str) const {
170  return Compare(str) == 0;
171  }
172  inline bool Equals(const char *cstr) const {
173  return Compare(cstr) == 0;
174  }
175  inline bool StartsWith(const String &str) const {
176  return CompareLeft(str) == 0;
177  }
178  inline bool StartsWith(const char *cstr) const {
179  return CompareLeft(cstr) == 0;
180  }
181  inline bool EndsWidth(const String &str) const {
182  return CompareRight(str) == 0;
183  }
184  inline bool EndsWidth(const char *cstr) const {
185  return CompareRight(cstr) == 0;
186  }
187 
188  // These functions search for character or substring inside this string
189  // and return the index of the (first) character, or -1 if nothing found.
190  size_t FindChar(char c, size_t from = 0) const;
191  size_t FindCharReverse(char c, size_t from = -1) const;
192  size_t FindString(const String &str, size_t from = 0) const {
193  return FindString(str._cstr, from);
194  }
195  size_t FindString(const char *cstr, size_t from = 0) const;
196 
197  // Section methods treat string as a sequence of 'fields', separated by
198  // special character. They search for a substring consisting of all such
199  // 'fields' from the 'first' to the 'last', inclusive; the bounding
200  // separators are optionally included too.
201  // Section indexes are zero-based. The first (0th) section is always
202  // located before the first separator and the last section is always
203  // located after the last separator, meaning that if the outermost
204  // character in string is separator char, there's still an empty trailing
205  // field beyond that.
206  // This also means that there's always at least one section in any string,
207  // even if there are no separating chars.
208  bool FindSection(char separator, size_t first, size_t last, bool exclude_first_sep, bool exclude_last_sep,
209  size_t &from, size_t &to) const;
210 
211  // Get Nth character with bounds check (as opposed to subscript operator)
212  inline char GetAt(size_t index) const {
213  return (index < _len) ? _cstr[index] : 0;
214  }
215  inline char GetLast() const {
216  return (_len > 0) ? _cstr[_len - 1] : 0;
217  }
218 
219  //-------------------------------------------------------------------------
220  // Value cast methods
221  //-------------------------------------------------------------------------
222 
223  int ToInt() const;
224 
225  //-------------------------------------------------------------------------
226  // Factory methods
227  //-------------------------------------------------------------------------
228 
229  // Wraps the given string buffer without owning it, won't count references,
230  // won't delete it at destruction. Can be used with string literals.
231  static String Wrapper(const char *cstr);
232 
233  // TODO: investigate C++11 solution for variadic templates (would that be more convenient here?)
234 
235  static String FromFormat(const char *fcstr, ...);
236  static String FromFormatV(const char *fcstr, va_list argptr);
237  // Reads stream until null-terminator or EOS
238  static String FromStream(Stream *in, size_t max_chars = 5 * 1024 * 1024, bool stop_at_limit = false);
239  // Reads up to N chars from stream
240  static String FromStreamCount(Stream *in, size_t count);
241 
242  // Creates a lowercased copy of the string
243  String Lower() const;
244  // Creates an uppercased copy of the string
245  String Upper() const;
246 
247  // Extract N leftmost characters as a new string
248  String Left(size_t count) const;
249  // Extract up to N characters starting from given index
250  String Mid(size_t from, size_t count = -1) const;
251  // Extract N rightmost characters
252  String Right(size_t count) const;
253 
254  // Extract leftmost part, separated by the given char; if no separator was
255  // found returns the whole string
256  String LeftSection(char separator, bool exclude_separator = true) const;
257  // Extract rightmost part, separated by the given char; if no separator was
258  // found returns the whole string
259  String RightSection(char separator, bool exclude_separator = true) const;
260  // Extract the range of Xth to Yth fields, separated by the given character
261  String Section(char separator, size_t first, size_t last,
262  bool exclude_first_sep = true, bool exclude_last_sep = true) const;
263  // Splits the string into segments divided by the instances of a given character,
264  // including empty segments e.g. if separators follow each other;
265  // returns at least one segment (equal to full string if no separator was found)
266  std::vector<String> Split(char separator) const;
267 
268  //-------------------------------------------------------------------------
269  // String modification methods
270  //-------------------------------------------------------------------------
271 
272  // Ensure string has at least space to store N chars;
273  // this does not change string contents, nor length
274  void Reserve(size_t max_length);
275  // Ensure string has at least space to store N additional chars
276  void ReserveMore(size_t more_length);
277  // Make string's buffer as small as possible to hold current data
278  void Compact();
279 
280  // Append* methods add content at the string's end, increasing its length
281  // Appends another string to this string
282  void Append(const String &str);
283  void Append(const char *cstr) {
284  String str = String::Wrapper(cstr);
285  Append(str);
286  }
287  void Append(const char *cstr, size_t len);
288  // Appends a single character
289  void AppendChar(char c);
290  // Appends a formatted string
291  void AppendFmt(MSVC_PRINTF const char *fcstr, ...) GCC_PRINTF(2, 3);
292  void AppendFmtv(const char *fcstr, va_list argptr);
293  // Clip* methods decrease the string, removing defined part
294  // Cuts off leftmost N characters
295  void ClipLeft(size_t count);
296  // Cuts out N characters starting from given index
297  void ClipMid(size_t from, size_t count = -1);
298  // Cuts off rightmost N characters
299  void ClipRight(size_t count);
300  // Cuts off leftmost part, separated by the given char; if no separator was
301  // found cuts whole string, leaving empty string
302  void ClipLeftSection(char separator, bool include_separator = true);
303  // Cuts off rightmost part, separated by the given char; if no separator
304  // was found cuts whole string, leaving empty string
305  void ClipRightSection(char separator, bool include_separator = true);
306  // Cuts out the range of Xth to Yth fields separated by the given character
307  void ClipSection(char separator, size_t first, size_t last,
308  bool include_first_sep = true, bool include_last_sep = true);
309  // Sets string length to zero
310  void Empty();
311  // Makes a new string by filling N chars with certain value
312  void FillString(char c, size_t count);
313  // Makes a new string by putting in parameters according to format string
314  void Format(const char *fcstr, ...);
315  void FormatV(const char *fcstr, va_list argptr);
316  // Decrement ref counter and deallocate data if must.
317  // Free() should be called only when buffer is not needed anymore;
318  // if string must be truncated to zero length, but retain the allocated
319  // memory, call Empty() instead.
320  void Free();
321  // Convert string to lowercase equivalent
322  void MakeLower();
323  // Convert string to uppercase equivalent
324  void MakeUpper();
325  // Merges sequences of same characters into one
326  void MergeSequences(char c = 0);
327  // Prepend* methods add content before the string's head, increasing its length
328  // Prepends another string to this string
329  void Prepend(const String &str);
330  void Prepend(const char *cstr) {
331  String str = String::Wrapper(cstr); Prepend(str);
332  }
333  // Prepends a single character
334  void PrependChar(char c);
335  // Replaces all occurrences of one character with another character
336  void Replace(char what, char with);
337  // Replaces all occurrences of one substring with another substring
338  void Replace(const String &what, const String &with);
339  void Replace(const char *what, const char *with) {
340  String whats = String::Wrapper(what), withs = String::Wrapper(with); Replace(whats, withs);
341  }
342  // Replaces particular substring with another substring; new substring
343  // may have different length
344  void ReplaceMid(size_t from, size_t count, const String &str);
345  void ReplaceMid(size_t from, size_t count, const char *cstr) {
346  String str = String::Wrapper(cstr); ReplaceMid(from, count, str);
347  }
348  // Reverses the string
349  void Reverse();
350  // Reverse the multibyte unicode string
351  // FIXME: name? invent some consistent naming for necessary multibyte funcs,
352  // proper utf8 support where necessary
353  void ReverseUTF8();
354  // Overwrite the Nth character of the string; does not change string's length
355  void SetAt(size_t index, char c);
356  // Makes a new string by copying up to N chars from C-string
357  void SetString(const char *cstr, size_t length = -1);
358  // For all Trim functions, if given character value is 0, all whitespace
359  // characters (space, tabs, CRLF) are removed.
360  // Remove heading and trailing characters from the string
361  void Trim(char c = 0);
362  // Remove heading characters from the string;
363  void TrimLeft(char c = 0);
364  // Remove trailing characters from the string
365  void TrimRight(char c = 0);
366  // Truncate* methods decrease the string to the part of itself
367  // Truncate the string to the leftmost N characters
368  void TruncateToLeft(size_t count);
369  // Truncate the string to the middle N characters
370  void TruncateToMid(size_t from, size_t count = -1);
371  // Truncate the string to the rightmost N characters
372  void TruncateToRight(size_t count);
373  // Truncate the string to the leftmost part, separated by the given char;
374  // if no separator was found leaves string unchanged
375  void TruncateToLeftSection(char separator, bool exclude_separator = true);
376  // Truncate the string to the rightmost part, separated by the given char;
377  // if no separator was found leaves string unchanged
378  void TruncateToRightSection(char separator, bool exclude_separator = true);
379  // Truncate the string to range of Xth to Yth fields separated by the
380  // given character
381  void TruncateToSection(char separator, size_t first, size_t last,
382  bool exclude_first_sep = true, bool exclude_last_sep = true);
383  // Wraps the given string buffer without owning it, won't count references,
384  // won't delete it at destruction. Can be used with string literals.
385  void Wrap(const char *cstr);
386 
387  //-------------------------------------------------------------------------
388  // Operators
389  //-------------------------------------------------------------------------
390 
391  // Assign String by sharing data reference
392  String &operator=(const String &str);
393  // Move operator
394  String &operator=(String &&str);
395  // Assign C-string by copying contents
396  String &operator=(const char *cstr);
397  inline char operator[](size_t index) const {
398  assert(index < _len);
399  return _cstr[index];
400  }
401  inline bool operator ==(const String &str) const {
402  return Compare(str) == 0;
403  }
404  inline bool operator ==(const char *cstr) const {
405  return Compare(cstr) == 0;
406  }
407  inline bool operator !=(const String &str) const {
408  return Compare(str) != 0;
409  }
410  inline bool operator !=(const char *cstr) const {
411  return Compare(cstr) != 0;
412  }
413  inline bool operator <(const String &str) const {
414  return Compare(str) < 0;
415  }
416  inline bool operator <(const char *cstr) const {
417  return Compare(cstr) < 0;
418  }
419  // Converts an AGS string to a ScummVM one
420  operator Common::String() const {
421  return Common::String(_cstr);
422  }
423  // Fixes compilation error in script_set
424  operator bool() const {
425  return !IsEmpty();
426  }
427  operator const char *() const {
428  return GetCStr();
429  }
430 
431 private:
432  // Creates new empty string with buffer enough to fit given length
433  void Create(size_t buffer_length);
434  // Release string and copy data to the new buffer
435  void Copy(size_t buffer_length, size_t offset = 0);
436  // Aligns data at given offset
437  void Align(size_t offset);
438 
439  // Tells if this object shares its string buffer with others
440  bool IsShared() const;
441  // Ensure this string is a writeable independent copy, with ref counter = 1
442  void BecomeUnique();
443  // Ensure this string is independent, and there's enough space before
444  // or after the current string data
445  void ReserveAndShift(bool left, size_t more_length);
446 
447  // Internal String data
448  char *_cstr; // pointer to actual string data; always valid, never null
449  size_t _len; // valid string length, in characters, excluding null-term
450 
451  // Header of a reference-counted buffer
452  struct BufHeader {
453  size_t RefCount = 0; // reference count
454  size_t Capacity = 0; // available space, in characters
455  };
456 
457  // Union that groups mutually exclusive data (currently only ref counted buffer)
458  union {
459  char *_buf; // reference-counted data (raw ptr)
460  BufHeader *_bufHead; // the header of a reference-counted data
461  };
462 };
463 
464 } // namespace Shared
465 } // namespace AGS
466 } // namespace AGS3
467 
468 #endif
Definition: achievements_tables.h:27
Definition: str.h:59
int FORCEINLINE GCC_PRINTF(2, 0) int vsprintf_s(T(&dst)[N]
Definition: string.h:60
Definition: stream.h:52
Definition: ags.h:40