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.

2042 lines
65KB

  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. #include "String.h"
  21. #include "NewLine.h"
  22. #include "../maths/MathsFunctions.h"
  23. #include "../memory/HeapBlock.h"
  24. #include "../streams/OutputStream.h"
  25. #include "CarlaJuceUtils.hpp"
  26. #include <locale>
  27. #include <iostream>
  28. #ifdef CARLA_OS_MAC
  29. // FIXME
  30. // # import <CoreData/CoreData.h>
  31. #endif
  32. // #import <Carbon/UnicodeConverter.h>
  33. namespace water {
  34. NewLine newLine;
  35. //==============================================================================
  36. // (Mirrors the structure of StringHolder, but without the atomic member, so can be statically constructed)
  37. struct EmptyString
  38. {
  39. int refCount;
  40. size_t allocatedBytes;
  41. String::CharPointerType::CharType text;
  42. };
  43. static const EmptyString emptyString = { 0x3fffffff, sizeof (String::CharPointerType::CharType), 0 };
  44. //==============================================================================
  45. class StringHolder
  46. {
  47. public:
  48. StringHolder() WATER_DELETED_FUNCTION;
  49. typedef String::CharPointerType CharPointerType;
  50. typedef String::CharPointerType::CharType CharType;
  51. //==============================================================================
  52. static CharPointerType createUninitialisedBytes (size_t numBytes)
  53. {
  54. numBytes = (numBytes + 3) & ~(size_t) 3;
  55. StringHolder* const s = reinterpret_cast<StringHolder*> (new char [sizeof (StringHolder) - sizeof (CharType) + numBytes]);
  56. s->refCount.value = 0;
  57. s->allocatedNumBytes = numBytes;
  58. return CharPointerType (s->text);
  59. }
  60. template <class CharPointer>
  61. static CharPointerType createFromCharPointer (const CharPointer text)
  62. {
  63. if (text.getAddress() == nullptr || text.isEmpty())
  64. return CharPointerType (&(emptyString.text));
  65. const size_t bytesNeeded = sizeof (CharType) + CharPointerType::getBytesRequiredFor (text);
  66. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  67. CharPointerType (dest).writeAll (text);
  68. return dest;
  69. }
  70. template <class CharPointer>
  71. static CharPointerType createFromCharPointer (const CharPointer text, size_t maxChars)
  72. {
  73. if (text.getAddress() == nullptr || text.isEmpty() || maxChars == 0)
  74. return CharPointerType (&(emptyString.text));
  75. CharPointer end (text);
  76. size_t numChars = 0;
  77. size_t bytesNeeded = sizeof (CharType);
  78. while (numChars < maxChars && ! end.isEmpty())
  79. {
  80. bytesNeeded += CharPointerType::getBytesRequiredFor (end.getAndAdvance());
  81. ++numChars;
  82. }
  83. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  84. CharPointerType (dest).writeWithCharLimit (text, (int) numChars + 1);
  85. return dest;
  86. }
  87. template <class CharPointer>
  88. static CharPointerType createFromCharPointer (const CharPointer start, const CharPointer end)
  89. {
  90. if (start.getAddress() == nullptr || start.isEmpty())
  91. return CharPointerType (&(emptyString.text));
  92. CharPointer e (start);
  93. int numChars = 0;
  94. size_t bytesNeeded = sizeof (CharType);
  95. while (e < end && ! e.isEmpty())
  96. {
  97. bytesNeeded += CharPointerType::getBytesRequiredFor (e.getAndAdvance());
  98. ++numChars;
  99. }
  100. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  101. CharPointerType (dest).writeWithCharLimit (start, numChars + 1);
  102. return dest;
  103. }
  104. static CharPointerType createFromCharPointer (const CharPointerType start, const CharPointerType end)
  105. {
  106. if (start.getAddress() == nullptr || start.isEmpty())
  107. return CharPointerType (&(emptyString.text));
  108. const size_t numBytes = (size_t) (reinterpret_cast<const char*> (end.getAddress())
  109. - reinterpret_cast<const char*> (start.getAddress()));
  110. const CharPointerType dest (createUninitialisedBytes (numBytes + sizeof (CharType)));
  111. memcpy (dest.getAddress(), start, numBytes);
  112. dest.getAddress()[numBytes / sizeof (CharType)] = 0;
  113. return dest;
  114. }
  115. static CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  116. {
  117. const CharPointerType dest (createUninitialisedBytes (numChars * sizeof (CharType) + sizeof (CharType)));
  118. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  119. return dest;
  120. }
  121. //==============================================================================
  122. static void retain (const CharPointerType text) noexcept
  123. {
  124. StringHolder* const b = bufferFromText (text);
  125. if (b != (StringHolder*) &emptyString)
  126. ++(b->refCount);
  127. }
  128. static inline void release (StringHolder* const b) noexcept
  129. {
  130. if (b != (StringHolder*) &emptyString)
  131. if (--(b->refCount) == -1)
  132. delete[] reinterpret_cast<char*> (b);
  133. }
  134. static void release (const CharPointerType text) noexcept
  135. {
  136. release (bufferFromText (text));
  137. }
  138. static inline int getReferenceCount (const CharPointerType text) noexcept
  139. {
  140. return bufferFromText (text)->refCount.get() + 1;
  141. }
  142. //==============================================================================
  143. static CharPointerType makeUniqueWithByteSize (const CharPointerType text, size_t numBytes)
  144. {
  145. StringHolder* const b = bufferFromText (text);
  146. if (b == (StringHolder*) &emptyString)
  147. {
  148. CharPointerType newText (createUninitialisedBytes (numBytes));
  149. newText.writeNull();
  150. return newText;
  151. }
  152. if (b->allocatedNumBytes >= numBytes && b->refCount.get() <= 0)
  153. return text;
  154. CharPointerType newText (createUninitialisedBytes (jmax (b->allocatedNumBytes, numBytes)));
  155. memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes);
  156. release (b);
  157. return newText;
  158. }
  159. static size_t getAllocatedNumBytes (const CharPointerType text) noexcept
  160. {
  161. return bufferFromText (text)->allocatedNumBytes;
  162. }
  163. //==============================================================================
  164. Atomic<int> refCount;
  165. size_t allocatedNumBytes;
  166. CharType text[1];
  167. private:
  168. static inline StringHolder* bufferFromText (const CharPointerType text) noexcept
  169. {
  170. // (Can't use offsetof() here because of warnings about this not being a POD)
  171. return reinterpret_cast<StringHolder*> (reinterpret_cast<char*> (text.getAddress())
  172. - (reinterpret_cast<size_t> (reinterpret_cast<StringHolder*> (1)->text) - 1));
  173. }
  174. };
  175. //==============================================================================
  176. String::String() noexcept : text (&(emptyString.text))
  177. {
  178. }
  179. String::~String() noexcept
  180. {
  181. StringHolder::release (text);
  182. }
  183. String::String (const String& other) noexcept : text (other.text)
  184. {
  185. StringHolder::retain (text);
  186. }
  187. void String::swapWith (String& other) noexcept
  188. {
  189. std::swap (text, other.text);
  190. }
  191. void String::clear() noexcept
  192. {
  193. StringHolder::release (text);
  194. text = &(emptyString.text);
  195. }
  196. String& String::operator= (const String& other) noexcept
  197. {
  198. StringHolder::retain (other.text);
  199. StringHolder::release (text.atomicSwap (other.text));
  200. return *this;
  201. }
  202. #if WATER_COMPILER_SUPPORTS_MOVE_SEMANTICS
  203. String::String (String&& other) noexcept : text (other.text)
  204. {
  205. other.text = &(emptyString.text);
  206. }
  207. String& String::operator= (String&& other) noexcept
  208. {
  209. std::swap (text, other.text);
  210. return *this;
  211. }
  212. #endif
  213. inline String::PreallocationBytes::PreallocationBytes (const size_t num) noexcept : numBytes (num) {}
  214. String::String (const PreallocationBytes& preallocationSize)
  215. : text (StringHolder::createUninitialisedBytes (preallocationSize.numBytes + sizeof (CharPointerType::CharType)))
  216. {
  217. }
  218. void String::preallocateBytes (const size_t numBytesNeeded)
  219. {
  220. text = StringHolder::makeUniqueWithByteSize (text, numBytesNeeded + sizeof (CharPointerType::CharType));
  221. }
  222. int String::getReferenceCount() const noexcept
  223. {
  224. return StringHolder::getReferenceCount (text);
  225. }
  226. //==============================================================================
  227. String::String (const char* const t)
  228. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t)))
  229. {
  230. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  231. that contains values greater than 127. These can NOT be correctly converted to unicode
  232. because there's no way for the String class to know what encoding was used to
  233. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  234. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  235. string to the String class - so for example if your source data is actually UTF-8,
  236. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  237. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  238. you use UTF-8 with escape characters in your source code to represent extended characters,
  239. because there's no other way to represent these strings in a way that isn't dependent on
  240. the compiler, source code editor and platform.
  241. */
  242. CARLA_SAFE_ASSERT (t == nullptr || CharPointer_UTF8::isValidString (t, std::numeric_limits<int>::max()));
  243. }
  244. String::String (const char* const t, const size_t maxChars)
  245. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t), maxChars))
  246. {
  247. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  248. that contains values greater than 127. These can NOT be correctly converted to unicode
  249. because there's no way for the String class to know what encoding was used to
  250. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  251. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  252. string to the String class - so for example if your source data is actually UTF-8,
  253. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  254. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  255. you use UTF-8 with escape characters in your source code to represent extended characters,
  256. because there's no other way to represent these strings in a way that isn't dependent on
  257. the compiler, source code editor and platform.
  258. */
  259. CARLA_SAFE_ASSERT (t == nullptr || CharPointer_UTF8::isValidString (t, (int) maxChars));
  260. }
  261. String::String (const CharPointer_UTF8 t) : text (StringHolder::createFromCharPointer (t)) {}
  262. String::String (const CharPointer_UTF8 t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  263. String::String (const CharPointer_UTF8 start, const CharPointer_UTF8 end) : text (StringHolder::createFromCharPointer (start, end)) {}
  264. String::String (const std::string& s) : text (StringHolder::createFromFixedLength (s.data(), s.size())) {}
  265. String::String (StringRef s) : text (StringHolder::createFromCharPointer (s.text)) {}
  266. String String::charToString (const water_uchar character)
  267. {
  268. String result (PreallocationBytes (CharPointerType::getBytesRequiredFor (character)));
  269. CharPointerType t (result.text);
  270. t.write (character);
  271. t.writeNull();
  272. return result;
  273. }
  274. //==============================================================================
  275. namespace NumberToStringConverters
  276. {
  277. static char* numberToString (char* t, uint64 v) noexcept
  278. {
  279. return printDigits (t, v);
  280. }
  281. static char* numberToString (char* t, const int n) noexcept
  282. {
  283. if (n >= 0)
  284. return printDigits (t, static_cast<unsigned int> (n));
  285. // NB: this needs to be careful not to call -std::numeric_limits<int>::min(),
  286. // which has undefined behaviour
  287. t = printDigits (t, static_cast<unsigned int> (-(n + 1)) + 1);
  288. *--t = '-';
  289. return t;
  290. }
  291. static char* numberToString (char* t, const unsigned int v) noexcept
  292. {
  293. return printDigits (t, v);
  294. }
  295. static char* numberToString (char* t, const long n) noexcept
  296. {
  297. if (n >= 0)
  298. return printDigits (t, static_cast<unsigned long> (n));
  299. t = printDigits (t, static_cast<unsigned long> (-(n + 1)) + 1);
  300. *--t = '-';
  301. return t;
  302. }
  303. static char* numberToString (char* t, const unsigned long v) noexcept
  304. {
  305. return printDigits (t, v);
  306. }
  307. struct StackArrayStream : public std::basic_streambuf<char, std::char_traits<char> >
  308. {
  309. explicit StackArrayStream (char* d)
  310. {
  311. static const std::locale classicLocale (std::locale::classic());
  312. imbue (classicLocale);
  313. setp (d, d + charsNeededForDouble);
  314. }
  315. size_t writeDouble (double n, int numDecPlaces)
  316. {
  317. {
  318. std::ostream o (this);
  319. if (numDecPlaces > 0)
  320. o.precision ((std::streamsize) numDecPlaces);
  321. o << n;
  322. }
  323. return (size_t) (pptr() - pbase());
  324. }
  325. };
  326. static char* doubleToString (char* buffer, const int numChars, double n, int numDecPlaces, size_t& len) noexcept
  327. {
  328. if (numDecPlaces > 0 && numDecPlaces < 7 && n > -1.0e20 && n < 1.0e20)
  329. {
  330. char* const end = buffer + numChars;
  331. char* t = end;
  332. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  333. *--t = (char) 0;
  334. while (numDecPlaces >= 0 || v > 0)
  335. {
  336. if (numDecPlaces == 0)
  337. *--t = '.';
  338. *--t = (char) ('0' + (v % 10));
  339. v /= 10;
  340. --numDecPlaces;
  341. }
  342. if (n < 0)
  343. *--t = '-';
  344. len = (size_t) (end - t - 1);
  345. return t;
  346. }
  347. StackArrayStream strm (buffer);
  348. len = strm.writeDouble (n, numDecPlaces);
  349. jassert (len <= charsNeededForDouble);
  350. return buffer;
  351. }
  352. template <typename IntegerType>
  353. static String::CharPointerType createFromInteger (const IntegerType number)
  354. {
  355. char buffer [charsNeededForInt];
  356. char* const end = buffer + numElementsInArray (buffer);
  357. char* const start = numberToString (end, number);
  358. return StringHolder::createFromFixedLength (start, (size_t) (end - start - 1));
  359. }
  360. static String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  361. {
  362. char buffer [charsNeededForDouble];
  363. size_t len;
  364. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  365. return StringHolder::createFromFixedLength (start, len);
  366. }
  367. }
  368. //==============================================================================
  369. String::String (const int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  370. String::String (const unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  371. String::String (const short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {}
  372. String::String (const unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {}
  373. String::String (const int64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  374. String::String (const uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  375. String::String (const long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  376. String::String (const unsigned long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  377. String::String (const float number) : text (NumberToStringConverters::createFromDouble ((double) number, 0)) {}
  378. String::String (const double number) : text (NumberToStringConverters::createFromDouble (number, 0)) {}
  379. String::String (const float number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces)) {}
  380. String::String (const double number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces)) {}
  381. //==============================================================================
  382. int String::length() const noexcept
  383. {
  384. return (int) text.length();
  385. }
  386. static size_t findByteOffsetOfEnd (String::CharPointerType text) noexcept
  387. {
  388. return (size_t) (((char*) text.findTerminatingNull().getAddress()) - (char*) text.getAddress());
  389. }
  390. size_t String::getByteOffsetOfEnd() const noexcept
  391. {
  392. return findByteOffsetOfEnd (text);
  393. }
  394. water_uchar String::operator[] (int index) const noexcept
  395. {
  396. jassert (index == 0 || (index > 0 && index <= (int) text.lengthUpTo ((size_t) index + 1)));
  397. return text [index];
  398. }
  399. //==============================================================================
  400. bool operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; }
  401. bool operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; }
  402. bool operator== (const String& s1, const char* s2) noexcept { return s1.compare (s2) == 0; }
  403. bool operator!= (const String& s1, const char* s2) noexcept { return s1.compare (s2) != 0; }
  404. bool operator== (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) == 0; }
  405. bool operator!= (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) != 0; }
  406. bool operator== (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  407. bool operator!= (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  408. bool operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; }
  409. bool operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; }
  410. bool operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; }
  411. bool operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; }
  412. bool String::equalsIgnoreCase (const char* const t) const noexcept
  413. {
  414. return t != nullptr ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  415. : isEmpty();
  416. }
  417. bool String::equalsIgnoreCase (StringRef t) const noexcept
  418. {
  419. return text.compareIgnoreCase (t.text) == 0;
  420. }
  421. bool String::equalsIgnoreCase (const String& other) const noexcept
  422. {
  423. return text == other.text
  424. || text.compareIgnoreCase (other.text) == 0;
  425. }
  426. int String::compare (const String& other) const noexcept { return (text == other.text) ? 0 : text.compare (other.text); }
  427. int String::compare (const char* const other) const noexcept { return text.compare (CharPointer_UTF8 (other)); }
  428. int String::compareIgnoreCase (const String& other) const noexcept { return (text == other.text) ? 0 : text.compareIgnoreCase (other.text); }
  429. static int stringCompareRight (String::CharPointerType s1, String::CharPointerType s2) noexcept
  430. {
  431. for (int bias = 0;;)
  432. {
  433. const water_uchar c1 = s1.getAndAdvance();
  434. const bool isDigit1 = CharacterFunctions::isDigit (c1);
  435. const water_uchar c2 = s2.getAndAdvance();
  436. const bool isDigit2 = CharacterFunctions::isDigit (c2);
  437. if (! (isDigit1 || isDigit2)) return bias;
  438. if (! isDigit1) return -1;
  439. if (! isDigit2) return 1;
  440. if (c1 != c2 && bias == 0)
  441. bias = c1 < c2 ? -1 : 1;
  442. jassert (c1 != 0 && c2 != 0);
  443. }
  444. }
  445. static int stringCompareLeft (String::CharPointerType s1, String::CharPointerType s2) noexcept
  446. {
  447. for (;;)
  448. {
  449. const water_uchar c1 = s1.getAndAdvance();
  450. const bool isDigit1 = CharacterFunctions::isDigit (c1);
  451. const water_uchar c2 = s2.getAndAdvance();
  452. const bool isDigit2 = CharacterFunctions::isDigit (c2);
  453. if (! (isDigit1 || isDigit2)) return 0;
  454. if (! isDigit1) return -1;
  455. if (! isDigit2) return 1;
  456. if (c1 < c2) return -1;
  457. if (c1 > c2) return 1;
  458. }
  459. }
  460. static int naturalStringCompare (String::CharPointerType s1, String::CharPointerType s2, bool isCaseSensitive) noexcept
  461. {
  462. bool firstLoop = true;
  463. for (;;)
  464. {
  465. const bool hasSpace1 = s1.isWhitespace();
  466. const bool hasSpace2 = s2.isWhitespace();
  467. if ((! firstLoop) && (hasSpace1 ^ hasSpace2))
  468. return hasSpace2 ? 1 : -1;
  469. firstLoop = false;
  470. if (hasSpace1) s1 = s1.findEndOfWhitespace();
  471. if (hasSpace2) s2 = s2.findEndOfWhitespace();
  472. if (s1.isDigit() && s2.isDigit())
  473. {
  474. const int result = (*s1 == '0' || *s2 == '0') ? stringCompareLeft (s1, s2)
  475. : stringCompareRight (s1, s2);
  476. if (result != 0)
  477. return result;
  478. }
  479. water_uchar c1 = s1.getAndAdvance();
  480. water_uchar c2 = s2.getAndAdvance();
  481. if (c1 != c2 && ! isCaseSensitive)
  482. {
  483. c1 = CharacterFunctions::toUpperCase (c1);
  484. c2 = CharacterFunctions::toUpperCase (c2);
  485. }
  486. if (c1 == c2)
  487. {
  488. if (c1 == 0)
  489. return 0;
  490. }
  491. else
  492. {
  493. const bool isAlphaNum1 = CharacterFunctions::isLetterOrDigit (c1);
  494. const bool isAlphaNum2 = CharacterFunctions::isLetterOrDigit (c2);
  495. if (isAlphaNum2 && ! isAlphaNum1) return -1;
  496. if (isAlphaNum1 && ! isAlphaNum2) return 1;
  497. return c1 < c2 ? -1 : 1;
  498. }
  499. jassert (c1 != 0 && c2 != 0);
  500. }
  501. }
  502. int String::compareNatural (StringRef other, bool isCaseSensitive) const noexcept
  503. {
  504. return naturalStringCompare (getCharPointer(), other.text, isCaseSensitive);
  505. }
  506. //==============================================================================
  507. void String::append (const String& textToAppend, size_t maxCharsToTake)
  508. {
  509. appendCharPointer (this == &textToAppend ? String (textToAppend).text
  510. : textToAppend.text, maxCharsToTake);
  511. }
  512. void String::appendCharPointer (const CharPointerType textToAppend)
  513. {
  514. appendCharPointer (textToAppend, textToAppend.findTerminatingNull());
  515. }
  516. void String::appendCharPointer (const CharPointerType startOfTextToAppend,
  517. const CharPointerType endOfTextToAppend)
  518. {
  519. jassert (startOfTextToAppend.getAddress() != nullptr && endOfTextToAppend.getAddress() != nullptr);
  520. const int extraBytesNeeded = getAddressDifference (endOfTextToAppend.getAddress(),
  521. startOfTextToAppend.getAddress());
  522. jassert (extraBytesNeeded >= 0);
  523. if (extraBytesNeeded > 0)
  524. {
  525. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  526. preallocateBytes (byteOffsetOfNull + (size_t) extraBytesNeeded);
  527. CharPointerType::CharType* const newStringStart = addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull);
  528. memcpy (newStringStart, startOfTextToAppend.getAddress(), (size_t) extraBytesNeeded);
  529. CharPointerType (addBytesToPointer (newStringStart, extraBytesNeeded)).writeNull();
  530. }
  531. }
  532. String& String::operator+= (const char* const t)
  533. {
  534. appendCharPointer (CharPointer_UTF8 (t)); // (using UTF8 here triggers a faster code-path than ascii)
  535. return *this;
  536. }
  537. String& String::operator+= (const String& other)
  538. {
  539. if (isEmpty())
  540. return operator= (other);
  541. if (this == &other)
  542. return operator+= (String (*this));
  543. appendCharPointer (other.text);
  544. return *this;
  545. }
  546. String& String::operator+= (StringRef other)
  547. {
  548. return operator+= (String (other));
  549. }
  550. String& String::operator+= (const char ch)
  551. {
  552. const char asString[] = { ch, 0 };
  553. return operator+= (asString);
  554. }
  555. String& String::operator+= (const water_uchar ch)
  556. {
  557. return operator+= (charToString(ch));
  558. }
  559. namespace StringHelpers
  560. {
  561. template <typename T>
  562. inline String& operationAddAssign (String& str, const T number)
  563. {
  564. char buffer [(sizeof(T) * 8) / 2];
  565. char* end = buffer + numElementsInArray (buffer);
  566. char* start = NumberToStringConverters::numberToString (end, number);
  567. str.appendCharPointer (String::CharPointerType (start), String::CharPointerType (end));
  568. return str;
  569. }
  570. }
  571. String& String::operator+= (const int number) { return StringHelpers::operationAddAssign<int> (*this, number); }
  572. String& String::operator+= (const int64 number) { return StringHelpers::operationAddAssign<int64> (*this, number); }
  573. String& String::operator+= (const uint64 number) { return StringHelpers::operationAddAssign<uint64> (*this, number); }
  574. //==============================================================================
  575. String operator+ (const char* const s1, const String& s2) { String s (s1); return s += s2; }
  576. String operator+ (const char s1, const String& s2) { return String::charToString ((water_uchar) (uint8) s1) + s2; }
  577. String operator+ (String s1, const String& s2) { return s1 += s2; }
  578. String operator+ (String s1, const char* const s2) { return s1 += s2; }
  579. String operator+ (String s1, const char s2) { return s1 += s2; }
  580. String operator+ (const water_uchar s1, const String& s2) { return String::charToString (s1) + s2; }
  581. String operator+ (String s1, const water_uchar s2) { return s1 += s2; }
  582. String& operator<< (String& s1, const water_uchar s2) { return s1 += s2; }
  583. String& operator<< (String& s1, const char s2) { return s1 += s2; }
  584. String& operator<< (String& s1, const char* const s2) { return s1 += s2; }
  585. String& operator<< (String& s1, const String& s2) { return s1 += s2; }
  586. String& operator<< (String& s1, StringRef s2) { return s1 += s2; }
  587. String& operator<< (String& s1, const int number) { return s1 += number; }
  588. String& operator<< (String& s1, const short number) { return s1 += (int) number; }
  589. String& operator<< (String& s1, const unsigned short number) { return s1 += (uint64) number; }
  590. String& operator<< (String& s1, const long number) { return s1 += String (number); }
  591. String& operator<< (String& s1, const unsigned long number) { return s1 += String (number); }
  592. String& operator<< (String& s1, const int64 number) { return s1 += String (number); }
  593. String& operator<< (String& s1, const uint64 number) { return s1 += String (number); }
  594. String& operator<< (String& s1, const float number) { return s1 += String (number); }
  595. String& operator<< (String& s1, const double number) { return s1 += String (number); }
  596. OutputStream& operator<< (OutputStream& stream, const String& text)
  597. {
  598. return operator<< (stream, StringRef (text));
  599. }
  600. OutputStream& operator<< (OutputStream& stream, StringRef text)
  601. {
  602. const size_t numBytes = CharPointer_UTF8::getBytesRequiredFor (text.text);
  603. stream.write (text.text.getAddress(), numBytes);
  604. return stream;
  605. }
  606. //==============================================================================
  607. int String::indexOfChar (const water_uchar character) const noexcept
  608. {
  609. return text.indexOf (character);
  610. }
  611. int String::indexOfChar (const int startIndex, const water_uchar character) const noexcept
  612. {
  613. CharPointerType t (text);
  614. for (int i = 0; ! t.isEmpty(); ++i)
  615. {
  616. if (i >= startIndex)
  617. {
  618. if (t.getAndAdvance() == character)
  619. return i;
  620. }
  621. else
  622. {
  623. ++t;
  624. }
  625. }
  626. return -1;
  627. }
  628. int String::lastIndexOfChar (const water_uchar character) const noexcept
  629. {
  630. CharPointerType t (text);
  631. int last = -1;
  632. for (int i = 0; ! t.isEmpty(); ++i)
  633. if (t.getAndAdvance() == character)
  634. last = i;
  635. return last;
  636. }
  637. int String::indexOfAnyOf (StringRef charactersToLookFor, const int startIndex, const bool ignoreCase) const noexcept
  638. {
  639. CharPointerType t (text);
  640. for (int i = 0; ! t.isEmpty(); ++i)
  641. {
  642. if (i >= startIndex)
  643. {
  644. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  645. return i;
  646. }
  647. else
  648. {
  649. ++t;
  650. }
  651. }
  652. return -1;
  653. }
  654. int String::indexOf (StringRef other) const noexcept
  655. {
  656. return other.isEmpty() ? 0 : text.indexOf (other.text);
  657. }
  658. int String::indexOfIgnoreCase (StringRef other) const noexcept
  659. {
  660. return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text);
  661. }
  662. int String::indexOf (const int startIndex, StringRef other) const noexcept
  663. {
  664. if (other.isEmpty())
  665. return -1;
  666. CharPointerType t (text);
  667. for (int i = startIndex; --i >= 0;)
  668. {
  669. if (t.isEmpty())
  670. return -1;
  671. ++t;
  672. }
  673. int found = t.indexOf (other.text);
  674. if (found >= 0)
  675. found += startIndex;
  676. return found;
  677. }
  678. int String::indexOfIgnoreCase (const int startIndex, StringRef other) const noexcept
  679. {
  680. if (other.isEmpty())
  681. return -1;
  682. CharPointerType t (text);
  683. for (int i = startIndex; --i >= 0;)
  684. {
  685. if (t.isEmpty())
  686. return -1;
  687. ++t;
  688. }
  689. int found = CharacterFunctions::indexOfIgnoreCase (t, other.text);
  690. if (found >= 0)
  691. found += startIndex;
  692. return found;
  693. }
  694. int String::lastIndexOf (StringRef other) const noexcept
  695. {
  696. if (other.isNotEmpty())
  697. {
  698. const int len = other.length();
  699. int i = length() - len;
  700. if (i >= 0)
  701. {
  702. for (CharPointerType n (text + i); i >= 0; --i)
  703. {
  704. if (n.compareUpTo (other.text, len) == 0)
  705. return i;
  706. --n;
  707. }
  708. }
  709. }
  710. return -1;
  711. }
  712. int String::lastIndexOfIgnoreCase (StringRef other) const noexcept
  713. {
  714. if (other.isNotEmpty())
  715. {
  716. const int len = other.length();
  717. int i = length() - len;
  718. if (i >= 0)
  719. {
  720. for (CharPointerType n (text + i); i >= 0; --i)
  721. {
  722. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  723. return i;
  724. --n;
  725. }
  726. }
  727. }
  728. return -1;
  729. }
  730. int String::lastIndexOfAnyOf (StringRef charactersToLookFor, const bool ignoreCase) const noexcept
  731. {
  732. CharPointerType t (text);
  733. int last = -1;
  734. for (int i = 0; ! t.isEmpty(); ++i)
  735. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  736. last = i;
  737. return last;
  738. }
  739. bool String::contains (StringRef other) const noexcept
  740. {
  741. return indexOf (other) >= 0;
  742. }
  743. bool String::containsChar (const water_uchar character) const noexcept
  744. {
  745. return text.indexOf (character) >= 0;
  746. }
  747. bool String::containsIgnoreCase (StringRef t) const noexcept
  748. {
  749. return indexOfIgnoreCase (t) >= 0;
  750. }
  751. int String::indexOfWholeWord (StringRef word) const noexcept
  752. {
  753. if (word.isNotEmpty())
  754. {
  755. CharPointerType t (text);
  756. const int wordLen = word.length();
  757. const int end = (int) t.length() - wordLen;
  758. for (int i = 0; i <= end; ++i)
  759. {
  760. if (t.compareUpTo (word.text, wordLen) == 0
  761. && (i == 0 || ! (t - 1).isLetterOrDigit())
  762. && ! (t + wordLen).isLetterOrDigit())
  763. return i;
  764. ++t;
  765. }
  766. }
  767. return -1;
  768. }
  769. int String::indexOfWholeWordIgnoreCase (StringRef word) const noexcept
  770. {
  771. if (word.isNotEmpty())
  772. {
  773. CharPointerType t (text);
  774. const int wordLen = word.length();
  775. const int end = (int) t.length() - wordLen;
  776. for (int i = 0; i <= end; ++i)
  777. {
  778. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  779. && (i == 0 || ! (t - 1).isLetterOrDigit())
  780. && ! (t + wordLen).isLetterOrDigit())
  781. return i;
  782. ++t;
  783. }
  784. }
  785. return -1;
  786. }
  787. bool String::containsWholeWord (StringRef wordToLookFor) const noexcept
  788. {
  789. return indexOfWholeWord (wordToLookFor) >= 0;
  790. }
  791. bool String::containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept
  792. {
  793. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  794. }
  795. //==============================================================================
  796. template <typename CharPointer>
  797. struct WildCardMatcher
  798. {
  799. static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  800. {
  801. for (;;)
  802. {
  803. const water_uchar wc = wildcard.getAndAdvance();
  804. if (wc == '*')
  805. return wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase);
  806. if (! characterMatches (wc, test.getAndAdvance(), ignoreCase))
  807. return false;
  808. if (wc == 0)
  809. return true;
  810. }
  811. }
  812. static bool characterMatches (const water_uchar wc, const water_uchar tc, const bool ignoreCase) noexcept
  813. {
  814. return (wc == tc) || (wc == '?' && tc != 0)
  815. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc));
  816. }
  817. static bool matchesAnywhere (const CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  818. {
  819. for (; ! test.isEmpty(); ++test)
  820. if (matches (wildcard, test, ignoreCase))
  821. return true;
  822. return false;
  823. }
  824. };
  825. bool String::matchesWildcard (StringRef wildcard, const bool ignoreCase) const noexcept
  826. {
  827. return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase);
  828. }
  829. //==============================================================================
  830. String String::repeatedString (StringRef stringToRepeat, int numberOfTimesToRepeat)
  831. {
  832. if (numberOfTimesToRepeat <= 0)
  833. return String();
  834. String result (PreallocationBytes (findByteOffsetOfEnd (stringToRepeat) * (size_t) numberOfTimesToRepeat));
  835. CharPointerType n (result.text);
  836. while (--numberOfTimesToRepeat >= 0)
  837. n.writeAll (stringToRepeat.text);
  838. return result;
  839. }
  840. String String::paddedLeft (const water_uchar padCharacter, int minimumLength) const
  841. {
  842. jassert (padCharacter != 0);
  843. int extraChars = minimumLength;
  844. CharPointerType end (text);
  845. while (! end.isEmpty())
  846. {
  847. --extraChars;
  848. ++end;
  849. }
  850. if (extraChars <= 0 || padCharacter == 0)
  851. return *this;
  852. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  853. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  854. CharPointerType n (result.text);
  855. while (--extraChars >= 0)
  856. n.write (padCharacter);
  857. n.writeAll (text);
  858. return result;
  859. }
  860. String String::paddedRight (const water_uchar padCharacter, int minimumLength) const
  861. {
  862. CARLA_SAFE_ASSERT_RETURN (padCharacter != 0, *this);
  863. int extraChars = minimumLength;
  864. CharPointerType end (text);
  865. while (! end.isEmpty())
  866. {
  867. --extraChars;
  868. ++end;
  869. }
  870. if (extraChars <= 0 || padCharacter == 0)
  871. return *this;
  872. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  873. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  874. CharPointerType n (result.text);
  875. n.writeAll (text);
  876. while (--extraChars >= 0)
  877. n.write (padCharacter);
  878. n.writeNull();
  879. return result;
  880. }
  881. //==============================================================================
  882. String String::replaceSection (int index, int numCharsToReplace, StringRef stringToInsert) const
  883. {
  884. if (index < 0)
  885. {
  886. // a negative index to replace from?
  887. jassertfalse;
  888. index = 0;
  889. }
  890. if (numCharsToReplace < 0)
  891. {
  892. // replacing a negative number of characters?
  893. numCharsToReplace = 0;
  894. jassertfalse;
  895. }
  896. CharPointerType insertPoint (text);
  897. for (int i = 0; i < index; ++i)
  898. {
  899. if (insertPoint.isEmpty())
  900. {
  901. // replacing beyond the end of the string?
  902. jassertfalse;
  903. return *this + stringToInsert;
  904. }
  905. ++insertPoint;
  906. }
  907. CharPointerType startOfRemainder (insertPoint);
  908. for (int i = 0; i < numCharsToReplace && ! startOfRemainder.isEmpty(); ++i)
  909. ++startOfRemainder;
  910. if (insertPoint == text && startOfRemainder.isEmpty())
  911. return stringToInsert.text;
  912. const size_t initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress());
  913. const size_t newStringBytes = findByteOffsetOfEnd (stringToInsert);
  914. const size_t remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress());
  915. const size_t newTotalBytes = initialBytes + newStringBytes + remainderBytes;
  916. if (newTotalBytes <= 0)
  917. return String();
  918. String result (PreallocationBytes ((size_t) newTotalBytes));
  919. char* dest = (char*) result.text.getAddress();
  920. memcpy (dest, text.getAddress(), initialBytes);
  921. dest += initialBytes;
  922. memcpy (dest, stringToInsert.text.getAddress(), newStringBytes);
  923. dest += newStringBytes;
  924. memcpy (dest, startOfRemainder.getAddress(), remainderBytes);
  925. dest += remainderBytes;
  926. CharPointerType ((CharPointerType::CharType*) dest).writeNull();
  927. return result;
  928. }
  929. String String::replace (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  930. {
  931. const int stringToReplaceLen = stringToReplace.length();
  932. const int stringToInsertLen = stringToInsert.length();
  933. int i = 0;
  934. String result (*this);
  935. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  936. : result.indexOf (i, stringToReplace))) >= 0)
  937. {
  938. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  939. i += stringToInsertLen;
  940. }
  941. return result;
  942. }
  943. class StringCreationHelper
  944. {
  945. public:
  946. StringCreationHelper (const size_t initialBytes)
  947. : source (nullptr), dest (nullptr), allocatedBytes (initialBytes), bytesWritten (0)
  948. {
  949. result.preallocateBytes (allocatedBytes);
  950. dest = result.getCharPointer();
  951. }
  952. StringCreationHelper (const String::CharPointerType s)
  953. : source (s), dest (nullptr), allocatedBytes (StringHolder::getAllocatedNumBytes (s)), bytesWritten (0)
  954. {
  955. result.preallocateBytes (allocatedBytes);
  956. dest = result.getCharPointer();
  957. }
  958. void write (water_uchar c)
  959. {
  960. bytesWritten += String::CharPointerType::getBytesRequiredFor (c);
  961. if (bytesWritten > allocatedBytes)
  962. {
  963. allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16);
  964. const size_t destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress());
  965. result.preallocateBytes (allocatedBytes);
  966. dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset);
  967. }
  968. dest.write (c);
  969. }
  970. String result;
  971. String::CharPointerType source;
  972. private:
  973. String::CharPointerType dest;
  974. size_t allocatedBytes, bytesWritten;
  975. };
  976. String String::replaceCharacter (const water_uchar charToReplace, const water_uchar charToInsert) const
  977. {
  978. if (! containsChar (charToReplace))
  979. return *this;
  980. StringCreationHelper builder (text);
  981. for (;;)
  982. {
  983. water_uchar c = builder.source.getAndAdvance();
  984. if (c == charToReplace)
  985. c = charToInsert;
  986. builder.write (c);
  987. if (c == 0)
  988. break;
  989. }
  990. return builder.result;
  991. }
  992. String String::replaceCharacters (StringRef charactersToReplace, StringRef charactersToInsertInstead) const
  993. {
  994. // Each character in the first string must have a matching one in the
  995. // second, so the two strings must be the same length.
  996. jassert (charactersToReplace.length() == charactersToInsertInstead.length());
  997. StringCreationHelper builder (text);
  998. for (;;)
  999. {
  1000. water_uchar c = builder.source.getAndAdvance();
  1001. const int index = charactersToReplace.text.indexOf (c);
  1002. if (index >= 0)
  1003. c = charactersToInsertInstead [index];
  1004. builder.write (c);
  1005. if (c == 0)
  1006. break;
  1007. }
  1008. return builder.result;
  1009. }
  1010. //==============================================================================
  1011. bool String::startsWith (StringRef other) const noexcept
  1012. {
  1013. return text.compareUpTo (other.text, other.length()) == 0;
  1014. }
  1015. bool String::startsWithIgnoreCase (StringRef other) const noexcept
  1016. {
  1017. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  1018. }
  1019. bool String::startsWithChar (const water_uchar character) const noexcept
  1020. {
  1021. // strings can't contain a null character!
  1022. CARLA_SAFE_ASSERT_RETURN (character != 0, false);
  1023. return *text == character;
  1024. }
  1025. bool String::endsWithChar (const water_uchar character) const noexcept
  1026. {
  1027. // strings can't contain a null character!
  1028. CARLA_SAFE_ASSERT_RETURN (character != 0, false);
  1029. if (text.isEmpty())
  1030. return false;
  1031. CharPointerType t (text.findTerminatingNull());
  1032. return *--t == character;
  1033. }
  1034. bool String::endsWith (StringRef other) const noexcept
  1035. {
  1036. CharPointerType end (text.findTerminatingNull());
  1037. CharPointerType otherEnd (other.text.findTerminatingNull());
  1038. while (end > text && otherEnd > other.text)
  1039. {
  1040. --end;
  1041. --otherEnd;
  1042. if (*end != *otherEnd)
  1043. return false;
  1044. }
  1045. return otherEnd == other.text;
  1046. }
  1047. bool String::endsWithIgnoreCase (StringRef other) const noexcept
  1048. {
  1049. CharPointerType end (text.findTerminatingNull());
  1050. CharPointerType otherEnd (other.text.findTerminatingNull());
  1051. while (end > text && otherEnd > other.text)
  1052. {
  1053. --end;
  1054. --otherEnd;
  1055. if (end.toLowerCase() != otherEnd.toLowerCase())
  1056. return false;
  1057. }
  1058. return otherEnd == other.text;
  1059. }
  1060. //==============================================================================
  1061. String String::toUpperCase() const
  1062. {
  1063. StringCreationHelper builder (text);
  1064. for (;;)
  1065. {
  1066. const water_uchar c = builder.source.toUpperCase();
  1067. builder.write (c);
  1068. if (c == 0)
  1069. break;
  1070. ++(builder.source);
  1071. }
  1072. return builder.result;
  1073. }
  1074. String String::toLowerCase() const
  1075. {
  1076. StringCreationHelper builder (text);
  1077. for (;;)
  1078. {
  1079. const water_uchar c = builder.source.toLowerCase();
  1080. builder.write (c);
  1081. if (c == 0)
  1082. break;
  1083. ++(builder.source);
  1084. }
  1085. return builder.result;
  1086. }
  1087. //==============================================================================
  1088. water_uchar String::getLastCharacter() const noexcept
  1089. {
  1090. return isEmpty() ? water_uchar() : text [length() - 1];
  1091. }
  1092. String String::substring (int start, const int end) const
  1093. {
  1094. if (start < 0)
  1095. start = 0;
  1096. if (end <= start)
  1097. return String();
  1098. int i = 0;
  1099. CharPointerType t1 (text);
  1100. while (i < start)
  1101. {
  1102. if (t1.isEmpty())
  1103. return String();
  1104. ++i;
  1105. ++t1;
  1106. }
  1107. CharPointerType t2 (t1);
  1108. while (i < end)
  1109. {
  1110. if (t2.isEmpty())
  1111. {
  1112. if (start == 0)
  1113. return *this;
  1114. break;
  1115. }
  1116. ++i;
  1117. ++t2;
  1118. }
  1119. return String (t1, t2);
  1120. }
  1121. String String::substring (int start) const
  1122. {
  1123. if (start <= 0)
  1124. return *this;
  1125. CharPointerType t (text);
  1126. while (--start >= 0)
  1127. {
  1128. if (t.isEmpty())
  1129. return String();
  1130. ++t;
  1131. }
  1132. return String (t);
  1133. }
  1134. String String::dropLastCharacters (const int numberToDrop) const
  1135. {
  1136. return String (text, (size_t) jmax (0, length() - numberToDrop));
  1137. }
  1138. String String::getLastCharacters (const int numCharacters) const
  1139. {
  1140. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  1141. }
  1142. String String::fromFirstOccurrenceOf (StringRef sub,
  1143. const bool includeSubString,
  1144. const bool ignoreCase) const
  1145. {
  1146. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1147. : indexOf (sub);
  1148. if (i < 0)
  1149. return String();
  1150. return substring (includeSubString ? i : i + sub.length());
  1151. }
  1152. String String::fromLastOccurrenceOf (StringRef sub,
  1153. const bool includeSubString,
  1154. const bool ignoreCase) const
  1155. {
  1156. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1157. : lastIndexOf (sub);
  1158. if (i < 0)
  1159. return *this;
  1160. return substring (includeSubString ? i : i + sub.length());
  1161. }
  1162. String String::upToFirstOccurrenceOf (StringRef sub,
  1163. const bool includeSubString,
  1164. const bool ignoreCase) const
  1165. {
  1166. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1167. : indexOf (sub);
  1168. if (i < 0)
  1169. return *this;
  1170. return substring (0, includeSubString ? i + sub.length() : i);
  1171. }
  1172. String String::upToLastOccurrenceOf (StringRef sub,
  1173. const bool includeSubString,
  1174. const bool ignoreCase) const
  1175. {
  1176. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1177. : lastIndexOf (sub);
  1178. if (i < 0)
  1179. return *this;
  1180. return substring (0, includeSubString ? i + sub.length() : i);
  1181. }
  1182. bool String::isQuotedString() const
  1183. {
  1184. const water_uchar trimmedStart = trimStart()[0];
  1185. return trimmedStart == '"'
  1186. || trimmedStart == '\'';
  1187. }
  1188. String String::unquoted() const
  1189. {
  1190. const int len = length();
  1191. if (len == 0)
  1192. return String();
  1193. const water_uchar lastChar = text [len - 1];
  1194. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  1195. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  1196. return substring (dropAtStart, len - dropAtEnd);
  1197. }
  1198. String String::quoted (water_uchar quoteCharacter) const
  1199. {
  1200. if (isEmpty())
  1201. return charToString (quoteCharacter) + quoteCharacter;
  1202. String t (*this);
  1203. if (! t.startsWithChar (quoteCharacter))
  1204. t = charToString (quoteCharacter) + t;
  1205. if (! t.endsWithChar (quoteCharacter))
  1206. t += quoteCharacter;
  1207. return t;
  1208. }
  1209. //==============================================================================
  1210. static String::CharPointerType findTrimmedEnd (const String::CharPointerType start,
  1211. String::CharPointerType end)
  1212. {
  1213. while (end > start)
  1214. {
  1215. if (! (--end).isWhitespace())
  1216. {
  1217. ++end;
  1218. break;
  1219. }
  1220. }
  1221. return end;
  1222. }
  1223. String String::trim() const
  1224. {
  1225. if (isNotEmpty())
  1226. {
  1227. CharPointerType start (text.findEndOfWhitespace());
  1228. const CharPointerType end (start.findTerminatingNull());
  1229. CharPointerType trimmedEnd (findTrimmedEnd (start, end));
  1230. if (trimmedEnd <= start)
  1231. return String();
  1232. if (text < start || trimmedEnd < end)
  1233. return String (start, trimmedEnd);
  1234. }
  1235. return *this;
  1236. }
  1237. String String::trimStart() const
  1238. {
  1239. if (isNotEmpty())
  1240. {
  1241. const CharPointerType t (text.findEndOfWhitespace());
  1242. if (t != text)
  1243. return String (t);
  1244. }
  1245. return *this;
  1246. }
  1247. String String::trimEnd() const
  1248. {
  1249. if (isNotEmpty())
  1250. {
  1251. const CharPointerType end (text.findTerminatingNull());
  1252. CharPointerType trimmedEnd (findTrimmedEnd (text, end));
  1253. if (trimmedEnd < end)
  1254. return String (text, trimmedEnd);
  1255. }
  1256. return *this;
  1257. }
  1258. String String::trimCharactersAtStart (StringRef charactersToTrim) const
  1259. {
  1260. CharPointerType t (text);
  1261. while (charactersToTrim.text.indexOf (*t) >= 0)
  1262. ++t;
  1263. return t == text ? *this : String (t);
  1264. }
  1265. String String::trimCharactersAtEnd (StringRef charactersToTrim) const
  1266. {
  1267. if (isNotEmpty())
  1268. {
  1269. const CharPointerType end (text.findTerminatingNull());
  1270. CharPointerType trimmedEnd (end);
  1271. while (trimmedEnd > text)
  1272. {
  1273. if (charactersToTrim.text.indexOf (*--trimmedEnd) < 0)
  1274. {
  1275. ++trimmedEnd;
  1276. break;
  1277. }
  1278. }
  1279. if (trimmedEnd < end)
  1280. return String (text, trimmedEnd);
  1281. }
  1282. return *this;
  1283. }
  1284. //==============================================================================
  1285. String String::retainCharacters (StringRef charactersToRetain) const
  1286. {
  1287. if (isEmpty())
  1288. return String();
  1289. StringCreationHelper builder (text);
  1290. for (;;)
  1291. {
  1292. water_uchar c = builder.source.getAndAdvance();
  1293. if (charactersToRetain.text.indexOf (c) >= 0)
  1294. builder.write (c);
  1295. if (c == 0)
  1296. break;
  1297. }
  1298. builder.write (0);
  1299. return builder.result;
  1300. }
  1301. String String::removeCharacters (StringRef charactersToRemove) const
  1302. {
  1303. if (isEmpty())
  1304. return String();
  1305. StringCreationHelper builder (text);
  1306. for (;;)
  1307. {
  1308. water_uchar c = builder.source.getAndAdvance();
  1309. if (charactersToRemove.text.indexOf (c) < 0)
  1310. builder.write (c);
  1311. if (c == 0)
  1312. break;
  1313. }
  1314. return builder.result;
  1315. }
  1316. String String::initialSectionContainingOnly (StringRef permittedCharacters) const
  1317. {
  1318. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1319. if (permittedCharacters.text.indexOf (*t) < 0)
  1320. return String (text, t);
  1321. return *this;
  1322. }
  1323. String String::initialSectionNotContaining (StringRef charactersToStopAt) const
  1324. {
  1325. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1326. if (charactersToStopAt.text.indexOf (*t) >= 0)
  1327. return String (text, t);
  1328. return *this;
  1329. }
  1330. bool String::containsOnly (StringRef chars) const noexcept
  1331. {
  1332. for (CharPointerType t (text); ! t.isEmpty();)
  1333. if (chars.text.indexOf (t.getAndAdvance()) < 0)
  1334. return false;
  1335. return true;
  1336. }
  1337. bool String::containsAnyOf (StringRef chars) const noexcept
  1338. {
  1339. for (CharPointerType t (text); ! t.isEmpty();)
  1340. if (chars.text.indexOf (t.getAndAdvance()) >= 0)
  1341. return true;
  1342. return false;
  1343. }
  1344. bool String::containsNonWhitespaceChars() const noexcept
  1345. {
  1346. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1347. if (! t.isWhitespace())
  1348. return true;
  1349. return false;
  1350. }
  1351. //=====================================================================================================================
  1352. static String getStringFromWindows1252Codepage (const char* data, size_t num)
  1353. {
  1354. HeapBlock<char> unicode;
  1355. CARLA_SAFE_ASSERT_RETURN(unicode.malloc(num + 1), String());
  1356. for (size_t i = 0; i < num; ++i)
  1357. unicode[i] = CharacterFunctions::getUnicodeCharFromWindows1252Codepage ((uint8) data[i]);
  1358. unicode[num] = 0;
  1359. return CharPointer_UTF8 (unicode);
  1360. }
  1361. String String::createStringFromData (const void* const unknownData, int size)
  1362. {
  1363. const uint8* const data = static_cast<const uint8*> (unknownData);
  1364. if (size <= 0 || data == nullptr)
  1365. return String();
  1366. if (size == 1)
  1367. return charToString ((water_uchar) data[0]);
  1368. const char* start = (const char*) data;
  1369. if (size >= 3 && CharPointer_UTF8::isByteOrderMark (data))
  1370. {
  1371. start += 3;
  1372. size -= 3;
  1373. }
  1374. if (CharPointer_UTF8::isValidString (start, size))
  1375. return String (CharPointer_UTF8 (start),
  1376. CharPointer_UTF8 (start + size));
  1377. return getStringFromWindows1252Codepage (start, (size_t) size);
  1378. }
  1379. // Note! The format parameter here MUST NOT be a reference, otherwise MS's va_start macro fails to work (but still compiles).
  1380. String String::formatted (const String pf, ... )
  1381. {
  1382. size_t bufferSize = 256;
  1383. HeapBlock<char> temp;
  1384. CARLA_SAFE_ASSERT_RETURN(temp.malloc(bufferSize), String());
  1385. for (;;)
  1386. {
  1387. va_list args;
  1388. va_start (args, pf);
  1389. // FIXME - needed?
  1390. temp.clear (bufferSize);
  1391. const int num = vsnprintf (temp.getData(), bufferSize - 1, pf.toRawUTF8(), args);
  1392. va_end (args);
  1393. if (num > 0)
  1394. return String (temp);
  1395. bufferSize += 256;
  1396. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vsnprintf repeatedly
  1397. break; // returns -1 because of an error rather than because it needs more space.
  1398. }
  1399. return String();
  1400. }
  1401. //==============================================================================
  1402. int String::getIntValue() const noexcept { return text.getIntValue32(); }
  1403. int64 String::getLargeIntValue() const noexcept { return text.getIntValue64(); }
  1404. float String::getFloatValue() const noexcept { return (float) getDoubleValue(); }
  1405. double String::getDoubleValue() const noexcept { return text.getDoubleValue(); }
  1406. int String::getTrailingIntValue() const noexcept
  1407. {
  1408. int n = 0;
  1409. int mult = 1;
  1410. CharPointerType t (text.findTerminatingNull());
  1411. while (--t >= text)
  1412. {
  1413. if (! t.isDigit())
  1414. {
  1415. if (*t == '-')
  1416. n = -n;
  1417. break;
  1418. }
  1419. n += mult * (*t - '0');
  1420. mult *= 10;
  1421. }
  1422. return n;
  1423. }
  1424. static const char hexDigits[] = "0123456789abcdef";
  1425. template <typename Type>
  1426. static String hexToString (Type v)
  1427. {
  1428. String::CharPointerType::CharType buffer[32];
  1429. String::CharPointerType::CharType* const end = buffer + numElementsInArray (buffer) - 1;
  1430. String::CharPointerType::CharType* t = end;
  1431. *t = 0;
  1432. do
  1433. {
  1434. *--t = hexDigits [(int) (v & 15)];
  1435. v >>= 4;
  1436. } while (v != 0);
  1437. return String (String::CharPointerType (t),
  1438. String::CharPointerType (end));
  1439. }
  1440. String String::toHexString (int number) { return hexToString ((unsigned int) number); }
  1441. String String::toHexString (int64 number) { return hexToString ((uint64) number); }
  1442. String String::toHexString (short number) { return toHexString ((int) (unsigned short) number); }
  1443. String String::toHexString (const void* const d, const int size, const int groupSize)
  1444. {
  1445. if (size <= 0)
  1446. return String();
  1447. int numChars = (size * 2) + 2;
  1448. if (groupSize > 0)
  1449. numChars += size / groupSize;
  1450. String s (PreallocationBytes (sizeof (CharPointerType::CharType) * (size_t) numChars));
  1451. const unsigned char* data = static_cast<const unsigned char*> (d);
  1452. CharPointerType dest (s.text);
  1453. for (int i = 0; i < size; ++i)
  1454. {
  1455. const unsigned char nextByte = *data++;
  1456. dest.write ((water_uchar) hexDigits [nextByte >> 4]);
  1457. dest.write ((water_uchar) hexDigits [nextByte & 0xf]);
  1458. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  1459. dest.write ((water_uchar) ' ');
  1460. }
  1461. dest.writeNull();
  1462. return s;
  1463. }
  1464. int String::getHexValue32() const noexcept { return CharacterFunctions::HexParser<int> ::parse (text); }
  1465. int64 String::getHexValue64() const noexcept { return CharacterFunctions::HexParser<int64>::parse (text); }
  1466. //==============================================================================
  1467. static const water_uchar emptyChar = 0;
  1468. template <class CharPointerType_Src, class CharPointerType_Dest>
  1469. struct StringEncodingConverter
  1470. {
  1471. static CharPointerType_Dest convert (const String& s)
  1472. {
  1473. String& source = const_cast<String&> (s);
  1474. typedef typename CharPointerType_Dest::CharType DestChar;
  1475. if (source.isEmpty())
  1476. return CharPointerType_Dest (reinterpret_cast<const DestChar*> (&emptyChar));
  1477. CharPointerType_Src text (source.getCharPointer());
  1478. const size_t extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text) + sizeof (typename CharPointerType_Dest::CharType);
  1479. const size_t endOffset = (text.sizeInBytes() + 3) & ~3u; // the new string must be word-aligned or many Windows
  1480. // functions will fail to read it correctly!
  1481. source.preallocateBytes (endOffset + extraBytesNeeded);
  1482. text = source.getCharPointer();
  1483. void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset);
  1484. const CharPointerType_Dest extraSpace (static_cast<DestChar*> (newSpace));
  1485. #ifdef DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  1486. const size_t bytesToClear = (size_t) jmin ((int) extraBytesNeeded, 4);
  1487. zeromem (addBytesToPointer (newSpace, extraBytesNeeded - bytesToClear), bytesToClear);
  1488. #endif
  1489. CharPointerType_Dest (extraSpace).writeAll (text);
  1490. return extraSpace;
  1491. }
  1492. };
  1493. template <>
  1494. struct StringEncodingConverter<CharPointer_UTF8, CharPointer_UTF8>
  1495. {
  1496. static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 ((CharPointer_UTF8::CharType*) source.getCharPointer().getAddress()); }
  1497. };
  1498. CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF8 >::convert (*this); }
  1499. const char* String::toRawUTF8() const
  1500. {
  1501. return toUTF8().getAddress();
  1502. }
  1503. std::string String::toStdString() const
  1504. {
  1505. return std::string (toRawUTF8());
  1506. }
  1507. //==============================================================================
  1508. template <class CharPointerType_Src, class CharPointerType_Dest>
  1509. struct StringCopier
  1510. {
  1511. static size_t copyToBuffer (const CharPointerType_Src source, typename CharPointerType_Dest::CharType* const buffer, const size_t maxBufferSizeBytes)
  1512. {
  1513. jassert (((ssize_t) maxBufferSizeBytes) >= 0); // keep this value positive!
  1514. if (buffer == nullptr)
  1515. return CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType);
  1516. return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes);
  1517. }
  1518. };
  1519. size_t String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1520. {
  1521. return StringCopier<CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1522. }
  1523. //==============================================================================
  1524. size_t String::getNumBytesAsUTF8() const noexcept
  1525. {
  1526. return CharPointer_UTF8::getBytesRequiredFor (text);
  1527. }
  1528. String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  1529. {
  1530. if (buffer != nullptr)
  1531. {
  1532. if (bufferSizeBytes < 0)
  1533. return String (CharPointer_UTF8 (buffer));
  1534. if (bufferSizeBytes > 0)
  1535. {
  1536. jassert (CharPointer_UTF8::isValidString (buffer, bufferSizeBytes));
  1537. return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes));
  1538. }
  1539. }
  1540. return String();
  1541. }
  1542. #ifdef CARLA_OS_MAC
  1543. String String::convertToPrecomposedUnicode() const
  1544. {
  1545. #if 0
  1546. UnicodeMapping map;
  1547. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  1548. kUnicodeNoSubset,
  1549. kTextEncodingDefaultFormat);
  1550. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  1551. kUnicodeCanonicalCompVariant,
  1552. kTextEncodingDefaultFormat);
  1553. map.mappingVersion = kUnicodeUseLatestMapping;
  1554. UnicodeToTextInfo conversionInfo = 0;
  1555. String result;
  1556. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  1557. {
  1558. const size_t bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (getCharPointer());
  1559. HeapBlock<char> tempOut;
  1560. tempOut.calloc (bytesNeeded + 4);
  1561. ByteCount bytesRead = 0;
  1562. ByteCount outputBufferSize = 0;
  1563. if (ConvertFromUnicodeToText (conversionInfo,
  1564. bytesNeeded, (ConstUniCharArrayPtr) toUTF16().getAddress(),
  1565. kUnicodeDefaultDirectionMask,
  1566. 0, 0, 0, 0,
  1567. bytesNeeded, &bytesRead,
  1568. &outputBufferSize, tempOut) == noErr)
  1569. {
  1570. result = String (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  1571. }
  1572. DisposeUnicodeToTextInfo (&conversionInfo);
  1573. }
  1574. return result;
  1575. #else
  1576. return *this;
  1577. #endif
  1578. }
  1579. #endif
  1580. //==============================================================================
  1581. StringRef::StringRef() noexcept : text ((const String::CharPointerType::CharType*) "\0\0\0")
  1582. {
  1583. }
  1584. StringRef::StringRef (const char* stringLiteral) noexcept
  1585. : text (stringLiteral)
  1586. {
  1587. jassert (stringLiteral != nullptr); // This must be a valid string literal, not a null pointer!!
  1588. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  1589. that contains values greater than 127. These can NOT be correctly converted to unicode
  1590. because there's no way for the String class to know what encoding was used to
  1591. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  1592. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  1593. string to the StringRef class - so for example if your source data is actually UTF-8,
  1594. you'd call StringRef (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  1595. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  1596. you use UTF-8 with escape characters in your source code to represent extended characters,
  1597. because there's no other way to represent these strings in a way that isn't dependent on
  1598. the compiler, source code editor and platform.
  1599. */
  1600. jassert (CharPointer_UTF8::isValidString (stringLiteral, std::numeric_limits<int>::max()));
  1601. }
  1602. StringRef::StringRef (String::CharPointerType stringLiteral) noexcept : text (stringLiteral)
  1603. {
  1604. jassert (stringLiteral.getAddress() != nullptr); // This must be a valid string literal, not a null pointer!!
  1605. }
  1606. StringRef::StringRef (const String& string) noexcept : text (string.getCharPointer()) {}
  1607. }
  1608. //==============================================================================