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.

2019 lines
65KB

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