Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1205 lines
54KB

  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2022 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #ifndef WATER_STRING_H_INCLUDED
  21. #define WATER_STRING_H_INCLUDED
  22. #include "CharPointer_UTF8.h"
  23. #include "../memory/Memory.h"
  24. #include <limits>
  25. #include <string>
  26. namespace water {
  27. //==============================================================================
  28. /**
  29. The Water String class!
  30. Using a reference-counted internal representation, these strings are fast
  31. and efficient, and there are methods to do just about any operation you'll ever
  32. dream of.
  33. @see StringArray, StringPairArray
  34. */
  35. class String
  36. {
  37. public:
  38. //==============================================================================
  39. /** Creates an empty string.
  40. @see empty
  41. */
  42. String() noexcept;
  43. /** Creates a copy of another string. */
  44. String (const String& other) noexcept;
  45. /** Creates a string from a zero-terminated ascii text string.
  46. The string passed-in must not contain any characters with a value above 127, because
  47. these can't be converted to unicode without knowing the original encoding that was
  48. used to create the string. If you attempt to pass-in values above 127, you'll get an
  49. assertion.
  50. To create strings with extended characters from UTF-8, you should explicitly call
  51. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  52. use UTF-8 with escape characters in your source code to represent extended characters,
  53. because there's no other way to represent unicode strings in a way that isn't dependent
  54. on the compiler, source code editor and platform.
  55. */
  56. String (const char* text);
  57. /** Creates a string from a string of 8-bit ascii characters.
  58. The string passed-in must not contain any characters with a value above 127, because
  59. these can't be converted to unicode without knowing the original encoding that was
  60. used to create the string. If you attempt to pass-in values above 127, you'll get an
  61. assertion.
  62. To create strings with extended characters from UTF-8, you should explicitly call
  63. String (CharPointer_UTF8 ("my utf8 string..")). It's *highly* recommended that you
  64. use UTF-8 with escape characters in your source code to represent extended characters,
  65. because there's no other way to represent unicode strings in a way that isn't dependent
  66. on the compiler, source code editor and platform.
  67. This will use up to the first maxChars characters of the string (or less if the string
  68. is actually shorter).
  69. */
  70. String (const char* text, size_t maxChars);
  71. //==============================================================================
  72. /** Creates a string from a UTF-8 character string */
  73. String (const CharPointer_UTF8 text);
  74. /** Creates a string from a UTF-8 character string */
  75. String (const CharPointer_UTF8 text, size_t maxChars);
  76. /** Creates a string from a UTF-8 character string */
  77. String (const CharPointer_UTF8 start, const CharPointer_UTF8 end);
  78. //==============================================================================
  79. /** Creates a string from a UTF-8 encoded std::string. */
  80. String (const std::string&);
  81. /** Creates a string from a StringRef */
  82. String (StringRef);
  83. //==============================================================================
  84. /** Creates a string from a single character. */
  85. static String charToString (water_uchar character);
  86. /** Destructor. */
  87. ~String() noexcept;
  88. //==============================================================================
  89. /** Generates a probably-unique 32-bit hashcode from this string. */
  90. int hashCode() const noexcept;
  91. /** Generates a probably-unique 64-bit hashcode from this string. */
  92. int64 hashCode64() const noexcept;
  93. /** Generates a probably-unique hashcode from this string. */
  94. size_t hash() const noexcept;
  95. /** Returns the number of characters in the string. */
  96. int length() const noexcept;
  97. //==============================================================================
  98. // Assignment and concatenation operators..
  99. /** Replaces this string's contents with another string. */
  100. String& operator= (const String& other) noexcept;
  101. /** Appends another string at the end of this one. */
  102. String& operator+= (const String& stringToAppend);
  103. /** Appends another string at the end of this one. */
  104. String& operator+= (const char* textToAppend);
  105. /** Appends another string at the end of this one. */
  106. String& operator+= (StringRef textToAppend);
  107. /** Appends a decimal number at the end of this string. */
  108. String& operator+= (int numberToAppend);
  109. /** Appends a decimal number at the end of this string. */
  110. String& operator+= (long numberToAppend);
  111. /** Appends a decimal number at the end of this string. */
  112. String& operator+= (int64 numberToAppend);
  113. /** Appends a decimal number at the end of this string. */
  114. String& operator+= (uint64 numberToAppend);
  115. /** Appends a character at the end of this string. */
  116. String& operator+= (char characterToAppend);
  117. /** Appends a character at the end of this string. */
  118. String& operator+= (water_uchar characterToAppend);
  119. /** Appends a string to the end of this one.
  120. @param textToAppend the string to add
  121. @param maxCharsToTake the maximum number of characters to take from the string passed in
  122. */
  123. void append (const String& textToAppend, size_t maxCharsToTake);
  124. /** Appends a string to the end of this one.
  125. @param startOfTextToAppend the start of the string to add. This must not be a nullptr
  126. @param endOfTextToAppend the end of the string to add. This must not be a nullptr
  127. */
  128. void appendCharPointer (const CharPointer_UTF8 startOfTextToAppend,
  129. const CharPointer_UTF8 endOfTextToAppend);
  130. /** Appends a string to the end of this one.
  131. @param startOfTextToAppend the start of the string to add. This must not be a nullptr
  132. @param endOfTextToAppend the end of the string to add. This must not be a nullptr
  133. */
  134. template <class CharPointer>
  135. void appendCharPointer (const CharPointer startOfTextToAppend,
  136. const CharPointer endOfTextToAppend)
  137. {
  138. wassert (startOfTextToAppend.getAddress() != nullptr && endOfTextToAppend.getAddress() != nullptr);
  139. size_t extraBytesNeeded = 0, numChars = 1;
  140. for (CharPointer t (startOfTextToAppend); t != endOfTextToAppend && ! t.isEmpty(); ++numChars)
  141. extraBytesNeeded += CharPointer_UTF8::getBytesRequiredFor (t.getAndAdvance());
  142. if (extraBytesNeeded > 0)
  143. {
  144. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  145. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  146. CharPointer_UTF8 (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull))
  147. .writeWithCharLimit (startOfTextToAppend, (int) numChars);
  148. }
  149. }
  150. /** Appends a string to the end of this one. */
  151. void appendCharPointer (const CharPointer_UTF8 textToAppend);
  152. /** Appends a string to the end of this one.
  153. @param textToAppend the string to add
  154. @param maxCharsToTake the maximum number of characters to take from the string passed in
  155. */
  156. template <class CharPointer>
  157. void appendCharPointer (const CharPointer textToAppend, size_t maxCharsToTake)
  158. {
  159. if (textToAppend.getAddress() != nullptr)
  160. {
  161. size_t extraBytesNeeded = 0, numChars = 1;
  162. for (CharPointer t (textToAppend); numChars <= maxCharsToTake && ! t.isEmpty(); ++numChars)
  163. extraBytesNeeded += CharPointer_UTF8::getBytesRequiredFor (t.getAndAdvance());
  164. if (extraBytesNeeded > 0)
  165. {
  166. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  167. preallocateBytes (byteOffsetOfNull + extraBytesNeeded);
  168. CharPointer_UTF8 (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull))
  169. .writeWithCharLimit (textToAppend, (int) numChars);
  170. }
  171. }
  172. }
  173. /** Appends a string to the end of this one. */
  174. template <class CharPointer>
  175. void appendCharPointer (const CharPointer textToAppend)
  176. {
  177. appendCharPointer (textToAppend, std::numeric_limits<size_t>::max());
  178. }
  179. //==============================================================================
  180. // Comparison methods..
  181. /** Returns true if the string contains no characters.
  182. Note that there's also an isNotEmpty() method to help write readable code.
  183. @see containsNonWhitespaceChars()
  184. */
  185. inline bool isEmpty() const noexcept { return text.isEmpty(); }
  186. /** Returns true if the string contains at least one character.
  187. Note that there's also an isEmpty() method to help write readable code.
  188. @see containsNonWhitespaceChars()
  189. */
  190. inline bool isNotEmpty() const noexcept { return ! text.isEmpty(); }
  191. /** Resets this string to be empty. */
  192. void clear() noexcept;
  193. /** Case-insensitive comparison with another string. */
  194. bool equalsIgnoreCase (const String& other) const noexcept;
  195. /** Case-insensitive comparison with another string. */
  196. bool equalsIgnoreCase (StringRef other) const noexcept;
  197. /** Case-insensitive comparison with another string. */
  198. bool equalsIgnoreCase (const char* other) const noexcept;
  199. /** Case-sensitive comparison with another string.
  200. @returns 0 if the two strings are identical; negative if this string comes before
  201. the other one alphabetically, or positive if it comes after it.
  202. */
  203. int compare (const String& other) const noexcept;
  204. /** Case-sensitive comparison with another string.
  205. @returns 0 if the two strings are identical; negative if this string comes before
  206. the other one alphabetically, or positive if it comes after it.
  207. */
  208. int compare (const char* other) const noexcept;
  209. /** Case-insensitive comparison with another string.
  210. @returns 0 if the two strings are identical; negative if this string comes before
  211. the other one alphabetically, or positive if it comes after it.
  212. */
  213. int compareIgnoreCase (const String& other) const noexcept;
  214. /** Compares two strings, taking into account textual characteristics like numbers and spaces.
  215. This comparison is case-insensitive and can detect words and embedded numbers in the
  216. strings, making it good for sorting human-readable lists of things like filenames.
  217. @returns 0 if the two strings are identical; negative if this string comes before
  218. the other one alphabetically, or positive if it comes after it.
  219. */
  220. int compareNatural (StringRef other, bool isCaseSensitive = false) const noexcept;
  221. /** Tests whether the string begins with another string.
  222. If the parameter is an empty string, this will always return true.
  223. Uses a case-sensitive comparison.
  224. */
  225. bool startsWith (StringRef text) const noexcept;
  226. /** Tests whether the string begins with a particular character.
  227. If the character is 0, this will always return false.
  228. Uses a case-sensitive comparison.
  229. */
  230. bool startsWithChar (water_uchar character) const noexcept;
  231. /** Tests whether the string begins with another string.
  232. If the parameter is an empty string, this will always return true.
  233. Uses a case-insensitive comparison.
  234. */
  235. bool startsWithIgnoreCase (StringRef text) const noexcept;
  236. /** Tests whether the string ends with another string.
  237. If the parameter is an empty string, this will always return true.
  238. Uses a case-sensitive comparison.
  239. */
  240. bool endsWith (StringRef text) const noexcept;
  241. /** Tests whether the string ends with a particular character.
  242. If the character is 0, this will always return false.
  243. Uses a case-sensitive comparison.
  244. */
  245. bool endsWithChar (water_uchar character) const noexcept;
  246. /** Tests whether the string ends with another string.
  247. If the parameter is an empty string, this will always return true.
  248. Uses a case-insensitive comparison.
  249. */
  250. bool endsWithIgnoreCase (StringRef text) const noexcept;
  251. /** Tests whether the string contains another substring.
  252. If the parameter is an empty string, this will always return true.
  253. Uses a case-sensitive comparison.
  254. */
  255. bool contains (StringRef text) const noexcept;
  256. /** Tests whether the string contains a particular character.
  257. Uses a case-sensitive comparison.
  258. */
  259. bool containsChar (water_uchar character) const noexcept;
  260. /** Tests whether the string contains another substring.
  261. Uses a case-insensitive comparison.
  262. */
  263. bool containsIgnoreCase (StringRef text) const noexcept;
  264. /** Tests whether the string contains another substring as a distinct word.
  265. @returns true if the string contains this word, surrounded by
  266. non-alphanumeric characters
  267. @see indexOfWholeWord, containsWholeWordIgnoreCase
  268. */
  269. bool containsWholeWord (StringRef wordToLookFor) const noexcept;
  270. /** Tests whether the string contains another substring as a distinct word.
  271. @returns true if the string contains this word, surrounded by
  272. non-alphanumeric characters
  273. @see indexOfWholeWordIgnoreCase, containsWholeWord
  274. */
  275. bool containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept;
  276. /** Finds an instance of another substring if it exists as a distinct word.
  277. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  278. then this will return the index of the start of the substring. If it isn't
  279. found, then it will return -1
  280. @see indexOfWholeWordIgnoreCase, containsWholeWord
  281. */
  282. int indexOfWholeWord (StringRef wordToLookFor) const noexcept;
  283. /** Finds an instance of another substring if it exists as a distinct word.
  284. @returns if the string contains this word, surrounded by non-alphanumeric characters,
  285. then this will return the index of the start of the substring. If it isn't
  286. found, then it will return -1
  287. @see indexOfWholeWord, containsWholeWordIgnoreCase
  288. */
  289. int indexOfWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept;
  290. /** Looks for any of a set of characters in the string.
  291. Uses a case-sensitive comparison.
  292. @returns true if the string contains any of the characters from
  293. the string that is passed in.
  294. */
  295. bool containsAnyOf (StringRef charactersItMightContain) const noexcept;
  296. /** Looks for a set of characters in the string.
  297. Uses a case-sensitive comparison.
  298. @returns Returns false if any of the characters in this string do not occur in
  299. the parameter string. If this string is empty, the return value will
  300. always be true.
  301. */
  302. bool containsOnly (StringRef charactersItMightContain) const noexcept;
  303. /** Returns true if this string contains any non-whitespace characters.
  304. This will return false if the string contains only whitespace characters, or
  305. if it's empty.
  306. It is equivalent to calling "myString.trim().isNotEmpty()".
  307. */
  308. bool containsNonWhitespaceChars() const noexcept;
  309. /** Returns true if the string matches this simple wildcard expression.
  310. So for example String ("abcdef").matchesWildcard ("*DEF", true) would return true.
  311. This isn't a full-blown regex though! The only wildcard characters supported
  312. are "*" and "?". It's mainly intended for filename pattern matching.
  313. */
  314. bool matchesWildcard (StringRef wildcard, bool ignoreCase) const noexcept;
  315. //==============================================================================
  316. // Substring location methods..
  317. /** Searches for a character inside this string.
  318. Uses a case-sensitive comparison.
  319. @returns the index of the first occurrence of the character in this
  320. string, or -1 if it's not found.
  321. */
  322. int indexOfChar (water_uchar characterToLookFor) const noexcept;
  323. /** Searches for a character inside this string.
  324. Uses a case-sensitive comparison.
  325. @param startIndex the index from which the search should proceed
  326. @param characterToLookFor the character to look for
  327. @returns the index of the first occurrence of the character in this
  328. string, or -1 if it's not found.
  329. */
  330. int indexOfChar (int startIndex, water_uchar characterToLookFor) const noexcept;
  331. /** Returns the index of the first character that matches one of the characters
  332. passed-in to this method.
  333. This scans the string, beginning from the startIndex supplied, and if it finds
  334. a character that appears in the string charactersToLookFor, it returns its index.
  335. If none of these characters are found, it returns -1.
  336. If ignoreCase is true, the comparison will be case-insensitive.
  337. @see indexOfChar, lastIndexOfAnyOf
  338. */
  339. int indexOfAnyOf (StringRef charactersToLookFor,
  340. int startIndex = 0,
  341. bool ignoreCase = false) const noexcept;
  342. /** Searches for a substring within this string.
  343. Uses a case-sensitive comparison.
  344. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  345. If textToLookFor is an empty string, this will always return 0.
  346. */
  347. int indexOf (StringRef textToLookFor) const noexcept;
  348. /** Searches for a substring within this string.
  349. Uses a case-sensitive comparison.
  350. @param startIndex the index from which the search should proceed
  351. @param textToLookFor the string to search for
  352. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  353. If textToLookFor is an empty string, this will always return -1.
  354. */
  355. int indexOf (int startIndex, StringRef textToLookFor) const noexcept;
  356. /** Searches for a substring within this string.
  357. Uses a case-insensitive comparison.
  358. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  359. If textToLookFor is an empty string, this will always return 0.
  360. */
  361. int indexOfIgnoreCase (StringRef textToLookFor) const noexcept;
  362. /** Searches for a substring within this string.
  363. Uses a case-insensitive comparison.
  364. @param startIndex the index from which the search should proceed
  365. @param textToLookFor the string to search for
  366. @returns the index of the first occurrence of this substring, or -1 if it's not found.
  367. If textToLookFor is an empty string, this will always return -1.
  368. */
  369. int indexOfIgnoreCase (int startIndex, StringRef textToLookFor) const noexcept;
  370. /** Searches for a character inside this string (working backwards from the end of the string).
  371. Uses a case-sensitive comparison.
  372. @returns the index of the last occurrence of the character in this string, or -1 if it's not found.
  373. */
  374. int lastIndexOfChar (water_uchar character) const noexcept;
  375. /** Searches for a substring inside this string (working backwards from the end of the string).
  376. Uses a case-sensitive comparison.
  377. @returns the index of the start of the last occurrence of the substring within this string,
  378. or -1 if it's not found. If textToLookFor is an empty string, this will always return -1.
  379. */
  380. int lastIndexOf (StringRef textToLookFor) const noexcept;
  381. /** Searches for a substring inside this string (working backwards from the end of the string).
  382. Uses a case-insensitive comparison.
  383. @returns the index of the start of the last occurrence of the substring within this string, or -1
  384. if it's not found. If textToLookFor is an empty string, this will always return -1.
  385. */
  386. int lastIndexOfIgnoreCase (StringRef textToLookFor) const noexcept;
  387. /** Returns the index of the last character in this string that matches one of the
  388. characters passed-in to this method.
  389. This scans the string backwards, starting from its end, and if it finds
  390. a character that appears in the string charactersToLookFor, it returns its index.
  391. If none of these characters are found, it returns -1.
  392. If ignoreCase is true, the comparison will be case-insensitive.
  393. @see lastIndexOf, indexOfAnyOf
  394. */
  395. int lastIndexOfAnyOf (StringRef charactersToLookFor,
  396. bool ignoreCase = false) const noexcept;
  397. //==============================================================================
  398. // Substring extraction and manipulation methods..
  399. /** Returns the character at this index in the string.
  400. In a release build, no checks are made to see if the index is within a valid range, so be
  401. careful! In a debug build, the index is checked and an assertion fires if it's out-of-range.
  402. Also beware that depending on the encoding format that the string is using internally, this
  403. method may execute in either O(1) or O(n) time, so be careful when using it in your algorithms.
  404. If you're scanning through a string to inspect its characters, you should never use this operator
  405. for random access, it's far more efficient to call getCharPointer() to return a pointer, and
  406. then to use that to iterate the string.
  407. @see getCharPointer
  408. */
  409. water_uchar operator[] (int index) const noexcept;
  410. /** Returns the final character of the string.
  411. If the string is empty this will return 0.
  412. */
  413. water_uchar getLastCharacter() const noexcept;
  414. //==============================================================================
  415. /** Returns a subsection of the string.
  416. If the range specified is beyond the limits of the string, as much as
  417. possible is returned.
  418. @param startIndex the index of the start of the substring needed
  419. @param endIndex all characters from startIndex up to (but not including)
  420. this index are returned
  421. @see fromFirstOccurrenceOf, dropLastCharacters, getLastCharacters, upToFirstOccurrenceOf
  422. */
  423. String substring (int startIndex, int endIndex) const;
  424. /** Returns a section of the string, starting from a given position.
  425. @param startIndex the first character to include. If this is beyond the end
  426. of the string, an empty string is returned. If it is zero or
  427. less, the whole string is returned.
  428. @returns the substring from startIndex up to the end of the string
  429. @see dropLastCharacters, getLastCharacters, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf
  430. */
  431. String substring (int startIndex) const;
  432. /** Returns a version of this string with a number of characters removed
  433. from the end.
  434. @param numberToDrop the number of characters to drop from the end of the
  435. string. If this is greater than the length of the string,
  436. an empty string will be returned. If zero or less, the
  437. original string will be returned.
  438. @see substring, fromFirstOccurrenceOf, upToFirstOccurrenceOf, fromLastOccurrenceOf, getLastCharacter
  439. */
  440. String dropLastCharacters (int numberToDrop) const;
  441. /** Returns a number of characters from the end of the string.
  442. This returns the last numCharacters characters from the end of the string. If the
  443. string is shorter than numCharacters, the whole string is returned.
  444. @see substring, dropLastCharacters, getLastCharacter
  445. */
  446. String getLastCharacters (int numCharacters) const;
  447. //==============================================================================
  448. /** Returns a section of the string starting from a given substring.
  449. This will search for the first occurrence of the given substring, and
  450. return the section of the string starting from the point where this is
  451. found (optionally not including the substring itself).
  452. e.g. for the string "123456", fromFirstOccurrenceOf ("34", true) would return "3456", and
  453. fromFirstOccurrenceOf ("34", false) would return "56".
  454. If the substring isn't found, the method will return an empty string.
  455. If ignoreCase is true, the comparison will be case-insensitive.
  456. @see upToFirstOccurrenceOf, fromLastOccurrenceOf
  457. */
  458. String fromFirstOccurrenceOf (StringRef substringToStartFrom,
  459. bool includeSubStringInResult,
  460. bool ignoreCase) const;
  461. /** Returns a section of the string starting from the last occurrence of a given substring.
  462. Similar to fromFirstOccurrenceOf(), but using the last occurrence of the substring, and
  463. unlike fromFirstOccurrenceOf(), if the substring isn't found, this method will
  464. return the whole of the original string.
  465. @see fromFirstOccurrenceOf, upToLastOccurrenceOf
  466. */
  467. String fromLastOccurrenceOf (StringRef substringToFind,
  468. bool includeSubStringInResult,
  469. bool ignoreCase) const;
  470. /** Returns the start of this string, up to the first occurrence of a substring.
  471. This will search for the first occurrence of a given substring, and then
  472. return a copy of the string, up to the position of this substring,
  473. optionally including or excluding the substring itself in the result.
  474. e.g. for the string "123456", upTo ("34", false) would return "12", and
  475. upTo ("34", true) would return "1234".
  476. If the substring isn't found, this will return the whole of the original string.
  477. @see upToLastOccurrenceOf, fromFirstOccurrenceOf
  478. */
  479. String upToFirstOccurrenceOf (StringRef substringToEndWith,
  480. bool includeSubStringInResult,
  481. bool ignoreCase) const;
  482. /** Returns the start of this string, up to the last occurrence of a substring.
  483. Similar to upToFirstOccurrenceOf(), but this finds the last occurrence rather than the first.
  484. If the substring isn't found, this will return the whole of the original string.
  485. @see upToFirstOccurrenceOf, fromFirstOccurrenceOf
  486. */
  487. String upToLastOccurrenceOf (StringRef substringToFind,
  488. bool includeSubStringInResult,
  489. bool ignoreCase) const;
  490. //==============================================================================
  491. /** Returns a copy of this string with any whitespace characters removed from the start and end. */
  492. String trim() const;
  493. /** Returns a copy of this string with any whitespace characters removed from the start. */
  494. String trimStart() const;
  495. /** Returns a copy of this string with any whitespace characters removed from the end. */
  496. String trimEnd() const;
  497. /** Returns a copy of this string, having removed a specified set of characters from its start.
  498. Characters are removed from the start of the string until it finds one that is not in the
  499. specified set, and then it stops.
  500. @param charactersToTrim the set of characters to remove.
  501. @see trim, trimStart, trimCharactersAtEnd
  502. */
  503. String trimCharactersAtStart (StringRef charactersToTrim) const;
  504. /** Returns a copy of this string, having removed a specified set of characters from its end.
  505. Characters are removed from the end of the string until it finds one that is not in the
  506. specified set, and then it stops.
  507. @param charactersToTrim the set of characters to remove.
  508. @see trim, trimEnd, trimCharactersAtStart
  509. */
  510. String trimCharactersAtEnd (StringRef charactersToTrim) const;
  511. //==============================================================================
  512. /** Returns an upper-case version of this string. */
  513. String toUpperCase() const;
  514. /** Returns an lower-case version of this string. */
  515. String toLowerCase() const;
  516. //==============================================================================
  517. /** Replaces a sub-section of the string with another string.
  518. This will return a copy of this string, with a set of characters
  519. from startIndex to startIndex + numCharsToReplace removed, and with
  520. a new string inserted in their place.
  521. Note that this is a const method, and won't alter the string itself.
  522. @param startIndex the first character to remove. If this is beyond the bounds of the string,
  523. it will be constrained to a valid range.
  524. @param numCharactersToReplace the number of characters to remove. If zero or less, no
  525. characters will be taken out.
  526. @param stringToInsert the new string to insert at startIndex after the characters have been
  527. removed.
  528. */
  529. String replaceSection (int startIndex,
  530. int numCharactersToReplace,
  531. StringRef stringToInsert) const;
  532. /** Replaces all occurrences of a substring with another string.
  533. Returns a copy of this string, with any occurrences of stringToReplace
  534. swapped for stringToInsertInstead.
  535. Note that this is a const method, and won't alter the string itself.
  536. */
  537. String replace (StringRef stringToReplace,
  538. StringRef stringToInsertInstead,
  539. bool ignoreCase = false) const;
  540. /** Returns a string with all occurrences of a character replaced with a different one. */
  541. String replaceCharacter (water_uchar characterToReplace,
  542. water_uchar characterToInsertInstead) const;
  543. /** Replaces a set of characters with another set.
  544. Returns a string in which each character from charactersToReplace has been replaced
  545. by the character at the equivalent position in newCharacters (so the two strings
  546. passed in must be the same length).
  547. e.g. replaceCharacters ("abc", "def") replaces 'a' with 'd', 'b' with 'e', etc.
  548. Note that this is a const method, and won't affect the string itself.
  549. */
  550. String replaceCharacters (StringRef charactersToReplace,
  551. StringRef charactersToInsertInstead) const;
  552. /** Returns a version of this string that only retains a fixed set of characters.
  553. This will return a copy of this string, omitting any characters which are not
  554. found in the string passed-in.
  555. e.g. for "1122334455", retainCharacters ("432") would return "223344"
  556. Note that this is a const method, and won't alter the string itself.
  557. */
  558. String retainCharacters (StringRef charactersToRetain) const;
  559. /** Returns a version of this string with a set of characters removed.
  560. This will return a copy of this string, omitting any characters which are
  561. found in the string passed-in.
  562. e.g. for "1122334455", removeCharacters ("432") would return "1155"
  563. Note that this is a const method, and won't alter the string itself.
  564. */
  565. String removeCharacters (StringRef charactersToRemove) const;
  566. /** Returns a section from the start of the string that only contains a certain set of characters.
  567. This returns the leftmost section of the string, up to (and not including) the
  568. first character that doesn't appear in the string passed in.
  569. */
  570. String initialSectionContainingOnly (StringRef permittedCharacters) const;
  571. /** Returns a section from the start of the string that only contains a certain set of characters.
  572. This returns the leftmost section of the string, up to (and not including) the
  573. first character that occurs in the string passed in. (If none of the specified
  574. characters are found in the string, the return value will just be the original string).
  575. */
  576. String initialSectionNotContaining (StringRef charactersToStopAt) const;
  577. //==============================================================================
  578. /** Checks whether the string might be in quotation marks.
  579. @returns true if the string begins with a quote character (either a double or single quote).
  580. It is also true if there is whitespace before the quote, but it doesn't check the end of the string.
  581. @see unquoted, quoted
  582. */
  583. bool isQuotedString() const;
  584. /** Removes quotation marks from around the string, (if there are any).
  585. Returns a copy of this string with any quotes removed from its ends. Quotes that aren't
  586. at the ends of the string are not affected. If there aren't any quotes, the original string
  587. is returned.
  588. Note that this is a const method, and won't alter the string itself.
  589. @see isQuotedString, quoted
  590. */
  591. String unquoted() const;
  592. /** Adds quotation marks around a string.
  593. This will return a copy of the string with a quote at the start and end, (but won't
  594. add the quote if there's already one there, so it's safe to call this on strings that
  595. may already have quotes around them).
  596. Note that this is a const method, and won't alter the string itself.
  597. @param quoteCharacter the character to add at the start and end
  598. @see isQuotedString, unquoted
  599. */
  600. String quoted (water_uchar quoteCharacter = '"') const;
  601. //==============================================================================
  602. /** Creates a string which is a version of a string repeated and joined together.
  603. @param stringToRepeat the string to repeat
  604. @param numberOfTimesToRepeat how many times to repeat it
  605. */
  606. static String repeatedString (StringRef stringToRepeat,
  607. int numberOfTimesToRepeat);
  608. /** Returns a copy of this string with the specified character repeatedly added to its
  609. beginning until the total length is at least the minimum length specified.
  610. */
  611. String paddedLeft (water_uchar padCharacter, int minimumLength) const;
  612. /** Returns a copy of this string with the specified character repeatedly added to its
  613. end until the total length is at least the minimum length specified.
  614. */
  615. String paddedRight (water_uchar padCharacter, int minimumLength) const;
  616. /** Creates a string from data in an unknown format.
  617. This looks at some binary data and tries to guess whether it's Unicode
  618. or 8-bit characters, then returns a string that represents it correctly.
  619. Should be able to handle Unicode endianness correctly, by looking at
  620. the first two bytes.
  621. */
  622. static String createStringFromData (const void* data, int size);
  623. /** Creates a String from a printf-style parameter list.
  624. I don't like this method. I don't use it myself, and I recommend avoiding it and
  625. using the operator<< methods or pretty much anything else instead. It's only provided
  626. here because of the popular unrest that was stirred-up when I tried to remove it...
  627. If you're really determined to use it, at least make sure that you never, ever,
  628. pass any String objects to it as parameters.
  629. */
  630. static String formatted (const String formatString, ... );
  631. //==============================================================================
  632. // Numeric conversions..
  633. /** Creates a string containing this signed 32-bit integer as a decimal number.
  634. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  635. */
  636. explicit String (int decimalInteger);
  637. /** Creates a string containing this unsigned 32-bit integer as a decimal number.
  638. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  639. */
  640. explicit String (unsigned int decimalInteger);
  641. /** Creates a string containing this signed 16-bit integer as a decimal number.
  642. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  643. */
  644. explicit String (short decimalInteger);
  645. /** Creates a string containing this unsigned 16-bit integer as a decimal number.
  646. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  647. */
  648. explicit String (unsigned short decimalInteger);
  649. /** Creates a string containing this signed 64-bit integer as a decimal number.
  650. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  651. */
  652. explicit String (int64 largeIntegerValue);
  653. /** Creates a string containing this unsigned 64-bit integer as a decimal number.
  654. @see getLargeIntValue, getFloatValue, getDoubleValue, toHexString
  655. */
  656. explicit String (uint64 largeIntegerValue);
  657. /** Creates a string containing this signed long integer as a decimal number.
  658. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  659. */
  660. explicit String (long decimalInteger);
  661. /** Creates a string containing this unsigned long integer as a decimal number.
  662. @see getIntValue, getFloatValue, getDoubleValue, toHexString
  663. */
  664. explicit String (unsigned long decimalInteger);
  665. /** Creates a string representing this floating-point number.
  666. @param floatValue the value to convert to a string
  667. @see getDoubleValue, getIntValue
  668. */
  669. explicit String (float floatValue);
  670. /** Creates a string representing this floating-point number.
  671. @param doubleValue the value to convert to a string
  672. @see getFloatValue, getIntValue
  673. */
  674. explicit String (double doubleValue);
  675. /** Creates a string representing this floating-point number.
  676. @param floatValue the value to convert to a string
  677. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  678. decimal places, and will not use exponent notation. If 0 or
  679. less, it will use exponent notation if necessary.
  680. @see getDoubleValue, getIntValue
  681. */
  682. String (float floatValue, int numberOfDecimalPlaces);
  683. /** Creates a string representing this floating-point number.
  684. @param doubleValue the value to convert to a string
  685. @param numberOfDecimalPlaces if this is > 0, it will format the number using that many
  686. decimal places, and will not use exponent notation. If 0 or
  687. less, it will use exponent notation if necessary.
  688. @see getFloatValue, getIntValue
  689. */
  690. String (double doubleValue, int numberOfDecimalPlaces);
  691. /** Reads the value of the string as a decimal number (up to 32 bits in size).
  692. @returns the value of the string as a 32 bit signed base-10 integer.
  693. @see getTrailingIntValue, getHexValue32, getHexValue64
  694. */
  695. int getIntValue() const noexcept;
  696. /** Reads the value of the string as a decimal number (up to 64 bits in size).
  697. @returns the value of the string as a 64 bit signed base-10 integer.
  698. */
  699. int64 getLargeIntValue() const noexcept;
  700. /** Parses a decimal number from the end of the string.
  701. This will look for a value at the end of the string.
  702. e.g. for "321 xyz654" it will return 654; for "2 3 4" it'll return 4.
  703. Negative numbers are not handled, so "xyz-5" returns 5.
  704. @see getIntValue
  705. */
  706. int getTrailingIntValue() const noexcept;
  707. /** Parses this string as a floating point number.
  708. @returns the value of the string as a 32-bit floating point value.
  709. @see getDoubleValue
  710. */
  711. float getFloatValue() const noexcept;
  712. /** Parses this string as a floating point number.
  713. @returns the value of the string as a 64-bit floating point value.
  714. @see getFloatValue
  715. */
  716. double getDoubleValue() const noexcept;
  717. /** Parses the string as a hexadecimal number.
  718. Non-hexadecimal characters in the string are ignored.
  719. If the string contains too many characters, then the lowest significant
  720. digits are returned, e.g. "ffff12345678" would produce 0x12345678.
  721. @returns a 32-bit number which is the value of the string in hex.
  722. */
  723. int getHexValue32() const noexcept;
  724. /** Parses the string as a hexadecimal number.
  725. Non-hexadecimal characters in the string are ignored.
  726. If the string contains too many characters, then the lowest significant
  727. digits are returned, e.g. "ffff1234567812345678" would produce 0x1234567812345678.
  728. @returns a 64-bit number which is the value of the string in hex.
  729. */
  730. int64 getHexValue64() const noexcept;
  731. /** Creates a string representing this 32-bit value in hexadecimal. */
  732. static String toHexString (int number);
  733. /** Creates a string representing this 64-bit value in hexadecimal. */
  734. static String toHexString (int64 number);
  735. /** Creates a string representing this 16-bit value in hexadecimal. */
  736. static String toHexString (short number);
  737. /** Creates a string containing a hex dump of a block of binary data.
  738. @param data the binary data to use as input
  739. @param size how many bytes of data to use
  740. @param groupSize how many bytes are grouped together before inserting a
  741. space into the output. e.g. group size 0 has no spaces,
  742. group size 1 looks like: "be a1 c2 ff", group size 2 looks
  743. like "bea1 c2ff".
  744. */
  745. static String toHexString (const void* data, int size, int groupSize = 1);
  746. //==============================================================================
  747. /** Returns the character pointer currently being used to store this string.
  748. Because it returns a reference to the string's internal data, the pointer
  749. that is returned must not be stored anywhere, as it can be deleted whenever the
  750. string changes.
  751. */
  752. inline CharPointer_UTF8 getCharPointer() const noexcept { return text; }
  753. /** Returns a pointer to a UTF-8 version of this string.
  754. Because it returns a reference to the string's internal data, the pointer
  755. that is returned must not be stored anywhere, as it can be deleted whenever the
  756. string changes.
  757. To find out how many bytes you need to store this string as UTF-8, you can call
  758. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  759. @see toRawUTF8, getCharPointer, toUTF16
  760. */
  761. CharPointer_UTF8 toUTF8() const;
  762. #ifdef CARLA_OS_WIN
  763. /** Convert string to UTF-16, Windows only */
  764. std::wstring toUTF16() const;
  765. #endif
  766. /** Returns a pointer to a UTF-8 version of this string.
  767. Because it returns a reference to the string's internal data, the pointer
  768. that is returned must not be stored anywhere, as it can be deleted whenever the
  769. string changes.
  770. To find out how many bytes you need to store this string as UTF-8, you can call
  771. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  772. @see getCharPointer, toUTF8, toUTF16
  773. */
  774. const char* toRawUTF8() const;
  775. /** */
  776. std::string toStdString() const;
  777. //==============================================================================
  778. /** Creates a String from a UTF-8 encoded buffer.
  779. If the size is < 0, it'll keep reading until it hits a zero.
  780. */
  781. static String fromUTF8 (const char* utf8buffer, int bufferSizeBytes = -1);
  782. /** Returns the number of bytes required to represent this string as UTF8.
  783. The number returned does NOT include the trailing zero.
  784. @see toUTF8, copyToUTF8
  785. */
  786. size_t getNumBytesAsUTF8() const noexcept;
  787. //==============================================================================
  788. /** Copies the string to a buffer as UTF-8 characters.
  789. Returns the number of bytes copied to the buffer, including the terminating null
  790. character.
  791. To find out how many bytes you need to store this string as UTF-8, you can call
  792. CharPointer_UTF8::getBytesRequiredFor (myString.getCharPointer())
  793. @param destBuffer the place to copy it to; if this is a null pointer, the method just
  794. returns the number of bytes required (including the terminating null character).
  795. @param maxBufferSizeBytes the size of the destination buffer, in bytes. If the string won't fit, it'll
  796. put in as many as it can while still allowing for a terminating null char at the
  797. end, and will return the number of bytes that were actually used.
  798. @see CharPointer_UTF8::writeWithDestByteLimit
  799. */
  800. size_t copyToUTF8 (CharPointer_UTF8::CharType* destBuffer, size_t maxBufferSizeBytes) const noexcept;
  801. //==============================================================================
  802. /** Increases the string's internally allocated storage.
  803. Although the string's contents won't be affected by this call, it will
  804. increase the amount of memory allocated internally for the string to grow into.
  805. If you're about to make a large number of calls to methods such
  806. as += or <<, it's more efficient to preallocate enough extra space
  807. beforehand, so that these methods won't have to keep resizing the string
  808. to append the extra characters.
  809. @param numBytesNeeded the number of bytes to allocate storage for. If this
  810. value is less than the currently allocated size, it will
  811. have no effect.
  812. */
  813. void preallocateBytes (size_t numBytesNeeded);
  814. /** Swaps the contents of this string with another one.
  815. This is a very fast operation, as no allocation or copying needs to be done.
  816. */
  817. void swapWith (String& other) noexcept;
  818. //==============================================================================
  819. #if 0 //def CARLA_OS_MAC
  820. /** OSX ONLY - Creates a String from an OSX CFString. */
  821. static String fromCFString (CFStringRef cfString);
  822. /** OSX ONLY - Converts this string to a CFString.
  823. Remember that you must use CFRelease() to free the returned string when you're
  824. finished with it.
  825. */
  826. CFStringRef toCFString() const;
  827. #endif
  828. #ifdef CARLA_OS_MAC
  829. /** OSX ONLY - Returns a copy of this string in which any decomposed unicode characters have
  830. been converted to their precomposed equivalents. */
  831. String convertToPrecomposedUnicode() const;
  832. #endif
  833. /** Returns the number of String objects which are currently sharing the same internal
  834. data as this one.
  835. */
  836. int getReferenceCount() const noexcept;
  837. private:
  838. //==============================================================================
  839. CharPointer_UTF8 text;
  840. //==============================================================================
  841. struct PreallocationBytes
  842. {
  843. explicit PreallocationBytes (size_t) noexcept;
  844. size_t numBytes;
  845. };
  846. explicit String (const PreallocationBytes&); // This constructor preallocates a certain amount of memory
  847. size_t getByteOffsetOfEnd() const noexcept;
  848. };
  849. //==============================================================================
  850. /** Concatenates two strings. */
  851. String operator+ (const char* string1, const String& string2);
  852. /** Concatenates two strings. */
  853. String operator+ (char string1, const String& string2);
  854. /** Concatenates two strings. */
  855. String operator+ (water_uchar string1, const String& string2);
  856. /** Concatenates two strings. */
  857. String operator+ (String string1, const String& string2);
  858. /** Concatenates two strings. */
  859. String operator+ (String string1, const char* string2);
  860. /** Concatenates two strings. */
  861. String operator+ (String string1, char characterToAppend);
  862. /** Concatenates two strings. */
  863. String operator+ (String string1, water_uchar characterToAppend);
  864. //==============================================================================
  865. /** Appends a character at the end of a string. */
  866. String& operator<< (String& string1, char characterToAppend);
  867. /** Appends a character at the end of a string. */
  868. String& operator<< (String& string1, water_uchar characterToAppend);
  869. /** Appends a string to the end of the first one. */
  870. String& operator<< (String& string1, const char* string2);
  871. /** Appends a string to the end of the first one. */
  872. String& operator<< (String& string1, const String& string2);
  873. /** Appends a string to the end of the first one. */
  874. String& operator<< (String& string1, StringRef string2);
  875. /** Appends a decimal number at the end of a string. */
  876. String& operator<< (String& string1, short number);
  877. /** Appends a decimal number at the end of a string. */
  878. String& operator<< (String& string1, int number);
  879. /** Appends a decimal number at the end of a string. */
  880. String& operator<< (String& string1, long number);
  881. /** Appends a decimal number at the end of a string. */
  882. String& operator<< (String& string1, int64 number);
  883. /** Appends a decimal number at the end of a string. */
  884. String& operator<< (String& string1, uint64 number);
  885. /** Appends a decimal number at the end of a string. */
  886. String& operator<< (String& string1, float number);
  887. /** Appends a decimal number at the end of a string. */
  888. String& operator<< (String& string1, double number);
  889. //==============================================================================
  890. /** Case-sensitive comparison of two strings. */
  891. bool operator== (const String& string1, const String& string2) noexcept;
  892. /** Case-sensitive comparison of two strings. */
  893. bool operator== (const String& string1, const char* string2) noexcept;
  894. /** Case-sensitive comparison of two strings. */
  895. bool operator== (const String& string1, const CharPointer_UTF8 string2) noexcept;
  896. /** Case-sensitive comparison of two strings. */
  897. bool operator!= (const String& string1, const String& string2) noexcept;
  898. /** Case-sensitive comparison of two strings. */
  899. bool operator!= (const String& string1, const char* string2) noexcept;
  900. /** Case-sensitive comparison of two strings. */
  901. bool operator!= (const String& string1, const CharPointer_UTF8 string2) noexcept;
  902. /** Case-sensitive comparison of two strings. */
  903. bool operator> (const String& string1, const String& string2) noexcept;
  904. /** Case-sensitive comparison of two strings. */
  905. bool operator< (const String& string1, const String& string2) noexcept;
  906. /** Case-sensitive comparison of two strings. */
  907. bool operator>= (const String& string1, const String& string2) noexcept;
  908. /** Case-sensitive comparison of two strings. */
  909. bool operator<= (const String& string1, const String& string2) noexcept;
  910. //==============================================================================
  911. /** This operator allows you to write a water String directly to std output streams.
  912. This is handy for writing strings to std::cout, std::cerr, etc.
  913. */
  914. template <class traits>
  915. std::basic_ostream <char, traits>& operator<< (std::basic_ostream <char, traits>& stream, const String& stringToWrite)
  916. {
  917. return stream << stringToWrite.toRawUTF8();
  918. }
  919. /** Writes a string to an OutputStream as UTF8. */
  920. OutputStream& operator<< (OutputStream& stream, const String& stringToWrite);
  921. /** Writes a string to an OutputStream as UTF8. */
  922. OutputStream& operator<< (OutputStream& stream, StringRef stringToWrite);
  923. //==============================================================================
  924. struct StartEndString {
  925. StartEndString (CharPointer_UTF8 s, CharPointer_UTF8 e) noexcept : start (s), end (e) {}
  926. operator String() const { return String (start, end); }
  927. CharPointer_UTF8 start, end;
  928. };
  929. }
  930. #include "StringRef.h"
  931. #endif // WATER_STRING_H_INCLUDED