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.

1203 lines
54KB

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