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.

2018 lines
64KB

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