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.

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