The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

2404 lines
80KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-11 by Raw Material Software Ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the GNU General
  7. Public License (Version 2), as published by the Free Software Foundation.
  8. A copy of the license is included in the JUCE distribution, or can be found
  9. online at www.gnu.org/licenses.
  10. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  11. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  12. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  13. ------------------------------------------------------------------------------
  14. To release a closed-source product which uses JUCE, commercial licenses are
  15. available: visit www.rawmaterialsoftware.com/juce for more information.
  16. ==============================================================================
  17. */
  18. #if JUCE_MSVC
  19. #pragma warning (push)
  20. #pragma warning (disable: 4514 4996)
  21. #endif
  22. #include <locale>
  23. BEGIN_JUCE_NAMESPACE
  24. NewLine newLine;
  25. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  26. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  27. #endif
  28. #if JUCE_NATIVE_WCHAR_IS_UTF8
  29. typedef CharPointer_UTF8 CharPointer_wchar_t;
  30. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  31. typedef CharPointer_UTF16 CharPointer_wchar_t;
  32. #else
  33. typedef CharPointer_UTF32 CharPointer_wchar_t;
  34. #endif
  35. static inline CharPointer_wchar_t castToCharPointer_wchar_t (const void* t) noexcept
  36. {
  37. return CharPointer_wchar_t (static_cast <const CharPointer_wchar_t::CharType*> (t));
  38. }
  39. //==============================================================================
  40. class StringHolder
  41. {
  42. public:
  43. StringHolder()
  44. : refCount (0x3fffffff), allocatedNumBytes (sizeof (*text))
  45. {
  46. text[0] = 0;
  47. }
  48. typedef String::CharPointerType CharPointerType;
  49. typedef String::CharPointerType::CharType CharType;
  50. //==============================================================================
  51. static const CharPointerType createUninitialisedBytes (const size_t numBytes)
  52. {
  53. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) - sizeof (CharType) + numBytes]);
  54. s->refCount.value = 0;
  55. s->allocatedNumBytes = numBytes;
  56. return CharPointerType (s->text);
  57. }
  58. template <class CharPointer>
  59. static const CharPointerType createFromCharPointer (const CharPointer& text)
  60. {
  61. if (text.getAddress() == nullptr || text.isEmpty())
  62. return getEmpty();
  63. CharPointer t (text);
  64. size_t bytesNeeded = sizeof (CharType);
  65. while (! t.isEmpty())
  66. bytesNeeded += CharPointerType::getBytesRequiredFor (t.getAndAdvance());
  67. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  68. CharPointerType (dest).writeAll (text);
  69. return dest;
  70. }
  71. template <class CharPointer>
  72. static const CharPointerType createFromCharPointer (const CharPointer& text, size_t maxChars)
  73. {
  74. if (text.getAddress() == nullptr || text.isEmpty() || maxChars == 0)
  75. return getEmpty();
  76. CharPointer end (text);
  77. size_t numChars = 0;
  78. size_t bytesNeeded = sizeof (CharType);
  79. while (numChars < maxChars && ! end.isEmpty())
  80. {
  81. bytesNeeded += CharPointerType::getBytesRequiredFor (end.getAndAdvance());
  82. ++numChars;
  83. }
  84. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  85. CharPointerType (dest).writeWithCharLimit (text, (int) numChars + 1);
  86. return dest;
  87. }
  88. template <class CharPointer>
  89. static const CharPointerType createFromCharPointer (const CharPointer& start, const CharPointer& end)
  90. {
  91. if (start.getAddress() == nullptr || start.isEmpty())
  92. return getEmpty();
  93. CharPointer e (start);
  94. int numChars = 0;
  95. size_t bytesNeeded = sizeof (CharType);
  96. while (e < end && ! e.isEmpty())
  97. {
  98. bytesNeeded += CharPointerType::getBytesRequiredFor (e.getAndAdvance());
  99. ++numChars;
  100. }
  101. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  102. CharPointerType (dest).writeWithCharLimit (start, numChars + 1);
  103. return dest;
  104. }
  105. static const 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. static inline const CharPointerType getEmpty() noexcept
  112. {
  113. return CharPointerType (empty.text);
  114. }
  115. //==============================================================================
  116. static void retain (const CharPointerType& text) noexcept
  117. {
  118. ++(bufferFromText (text)->refCount);
  119. }
  120. static inline void release (StringHolder* const b) noexcept
  121. {
  122. if (--(b->refCount) == -1 && b != &empty)
  123. delete[] reinterpret_cast <char*> (b);
  124. }
  125. static void release (const CharPointerType& text) noexcept
  126. {
  127. release (bufferFromText (text));
  128. }
  129. //==============================================================================
  130. static CharPointerType makeUnique (const CharPointerType& text)
  131. {
  132. StringHolder* const b = bufferFromText (text);
  133. if (b->refCount.get() <= 0)
  134. return text;
  135. CharPointerType newText (createUninitialisedBytes (b->allocatedNumBytes));
  136. memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes);
  137. release (b);
  138. return newText;
  139. }
  140. static CharPointerType makeUniqueWithByteSize (const CharPointerType& text, size_t numBytes)
  141. {
  142. StringHolder* const b = bufferFromText (text);
  143. if (b->refCount.get() <= 0 && b->allocatedNumBytes >= numBytes)
  144. return text;
  145. CharPointerType newText (createUninitialisedBytes (jmax (b->allocatedNumBytes, numBytes)));
  146. memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes);
  147. release (b);
  148. return newText;
  149. }
  150. static size_t getAllocatedNumBytes (const CharPointerType& text) noexcept
  151. {
  152. return bufferFromText (text)->allocatedNumBytes;
  153. }
  154. //==============================================================================
  155. Atomic<int> refCount;
  156. size_t allocatedNumBytes;
  157. CharType text[1];
  158. static StringHolder empty;
  159. private:
  160. static inline StringHolder* bufferFromText (const CharPointerType& text) noexcept
  161. {
  162. // (Can't use offsetof() here because of warnings about this not being a POD)
  163. return reinterpret_cast <StringHolder*> (reinterpret_cast <char*> (text.getAddress())
  164. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  165. }
  166. void compileTimeChecks()
  167. {
  168. // Let me know if any of these assertions fail on your system!
  169. #if JUCE_NATIVE_WCHAR_IS_UTF8
  170. static_jassert (sizeof (wchar_t) == 1);
  171. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  172. static_jassert (sizeof (wchar_t) == 2);
  173. #elif JUCE_NATIVE_WCHAR_IS_UTF32
  174. static_jassert (sizeof (wchar_t) == 4);
  175. #else
  176. #error "native wchar_t size is unknown"
  177. #endif
  178. }
  179. };
  180. StringHolder StringHolder::empty;
  181. const String String::empty;
  182. //==============================================================================
  183. void String::preallocateBytes (const size_t numBytesNeeded)
  184. {
  185. text = StringHolder::makeUniqueWithByteSize (text, numBytesNeeded + sizeof (CharPointerType::CharType));
  186. }
  187. //==============================================================================
  188. String::String() noexcept
  189. : text (StringHolder::getEmpty())
  190. {
  191. }
  192. String::~String() noexcept
  193. {
  194. StringHolder::release (text);
  195. }
  196. String::String (const String& other) noexcept
  197. : text (other.text)
  198. {
  199. StringHolder::retain (text);
  200. }
  201. void String::swapWith (String& other) noexcept
  202. {
  203. std::swap (text, other.text);
  204. }
  205. String& String::operator= (const String& other) noexcept
  206. {
  207. StringHolder::retain (other.text);
  208. StringHolder::release (text.atomicSwap (other.text));
  209. return *this;
  210. }
  211. #if JUCE_COMPILER_SUPPORTS_MOVE_SEMANTICS
  212. String::String (String&& other) noexcept
  213. : text (other.text)
  214. {
  215. other.text = StringHolder::getEmpty();
  216. }
  217. String& String::operator= (String&& other) noexcept
  218. {
  219. std::swap (text, other.text);
  220. return *this;
  221. }
  222. #endif
  223. inline String::PreallocationBytes::PreallocationBytes (const size_t numBytes_) : numBytes (numBytes_) {}
  224. String::String (const PreallocationBytes& preallocationSize)
  225. : text (StringHolder::createUninitialisedBytes (preallocationSize.numBytes + sizeof (CharPointerType::CharType)))
  226. {
  227. }
  228. //==============================================================================
  229. String::String (const char* const t)
  230. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  231. {
  232. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  233. that contains values greater than 127. These can NOT be correctly converted to unicode
  234. because there's no way for the String class to know what encoding was used to
  235. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  236. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  237. string to the String class - so for example if your source data is actually UTF-8,
  238. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  239. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  240. you use UTF-8 with escape characters in your source code to represent extended characters,
  241. because there's no other way to represent these strings in a way that isn't dependent on
  242. the compiler, source code editor and platform.
  243. */
  244. jassert (t == nullptr || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  245. }
  246. String::String (const char* const t, const size_t maxChars)
  247. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  248. {
  249. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  250. that contains values greater than 127. These can NOT be correctly converted to unicode
  251. because there's no way for the String class to know what encoding was used to
  252. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  253. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  254. string to the String class - so for example if your source data is actually UTF-8,
  255. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  256. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  257. you use UTF-8 with escape characters in your source code to represent extended characters,
  258. because there's no other way to represent these strings in a way that isn't dependent on
  259. the compiler, source code editor and platform.
  260. */
  261. jassert (t == nullptr || CharPointer_ASCII::isValidString (t, (int) maxChars));
  262. }
  263. String::String (const wchar_t* const t) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t))) {}
  264. String::String (const CharPointer_UTF8& t) : text (StringHolder::createFromCharPointer (t)) {}
  265. String::String (const CharPointer_UTF16& t) : text (StringHolder::createFromCharPointer (t)) {}
  266. String::String (const CharPointer_UTF32& t) : text (StringHolder::createFromCharPointer (t)) {}
  267. String::String (const CharPointer_ASCII& t) : text (StringHolder::createFromCharPointer (t)) {}
  268. String::String (const CharPointer_UTF8& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  269. String::String (const CharPointer_UTF16& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  270. String::String (const CharPointer_UTF32& t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  271. String::String (const wchar_t* const t, size_t maxChars) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t), maxChars)) {}
  272. String::String (const CharPointer_UTF8& start, const CharPointer_UTF8& end) : text (StringHolder::createFromCharPointer (start, end)) {}
  273. String::String (const CharPointer_UTF16& start, const CharPointer_UTF16& end) : text (StringHolder::createFromCharPointer (start, end)) {}
  274. String::String (const CharPointer_UTF32& start, const CharPointer_UTF32& end) : text (StringHolder::createFromCharPointer (start, end)) {}
  275. String String::charToString (const juce_wchar character)
  276. {
  277. String result (PreallocationBytes (CharPointerType::getBytesRequiredFor (character)));
  278. CharPointerType t (result.text);
  279. t.write (character);
  280. t.writeNull();
  281. return result;
  282. }
  283. //==============================================================================
  284. namespace NumberToStringConverters
  285. {
  286. // pass in a pointer to the END of a buffer..
  287. char* numberToString (char* t, const int64 n) noexcept
  288. {
  289. *--t = 0;
  290. int64 v = (n >= 0) ? n : -n;
  291. do
  292. {
  293. *--t = (char) ('0' + (int) (v % 10));
  294. v /= 10;
  295. } while (v > 0);
  296. if (n < 0)
  297. *--t = '-';
  298. return t;
  299. }
  300. char* numberToString (char* t, uint64 v) noexcept
  301. {
  302. *--t = 0;
  303. do
  304. {
  305. *--t = (char) ('0' + (int) (v % 10));
  306. v /= 10;
  307. } while (v > 0);
  308. return t;
  309. }
  310. char* numberToString (char* t, const int n) noexcept
  311. {
  312. if (n == (int) 0x80000000) // (would cause an overflow)
  313. return numberToString (t, (int64) n);
  314. *--t = 0;
  315. int v = abs (n);
  316. do
  317. {
  318. *--t = (char) ('0' + (v % 10));
  319. v /= 10;
  320. } while (v > 0);
  321. if (n < 0)
  322. *--t = '-';
  323. return t;
  324. }
  325. char* numberToString (char* t, unsigned int v) noexcept
  326. {
  327. *--t = 0;
  328. do
  329. {
  330. *--t = (char) ('0' + (v % 10));
  331. v /= 10;
  332. } while (v > 0);
  333. return t;
  334. }
  335. char getDecimalPoint()
  336. {
  337. static char dp = (char)
  338. #if JUCE_VC7_OR_EARLIER
  339. std::_USE (std::locale(), std::numpunct <char>).decimal_point();
  340. #else
  341. std::use_facet <std::numpunct <char> > (std::locale()).decimal_point();
  342. #endif
  343. return dp;
  344. }
  345. char* doubleToString (char* buffer, const int numChars, double n, int numDecPlaces, size_t& len) noexcept
  346. {
  347. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  348. {
  349. char* const end = buffer + numChars;
  350. char* t = end;
  351. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  352. *--t = (char) 0;
  353. while (numDecPlaces >= 0 || v > 0)
  354. {
  355. if (numDecPlaces == 0)
  356. *--t = (char) getDecimalPoint();
  357. *--t = (char) ('0' + (v % 10));
  358. v /= 10;
  359. --numDecPlaces;
  360. }
  361. if (n < 0)
  362. *--t = '-';
  363. len = (size_t) (end - t - 1);
  364. return t;
  365. }
  366. else
  367. {
  368. len = (size_t) sprintf (buffer, "%.9g", n);
  369. return buffer;
  370. }
  371. }
  372. template <typename IntegerType>
  373. const String::CharPointerType createFromInteger (const IntegerType number)
  374. {
  375. char buffer [32];
  376. char* const end = buffer + numElementsInArray (buffer);
  377. char* const start = numberToString (end, number);
  378. return StringHolder::createFromFixedLength (start, (size_t) (end - start - 1));
  379. }
  380. const String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  381. {
  382. char buffer [48];
  383. size_t len;
  384. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  385. return StringHolder::createFromFixedLength (start, len);
  386. }
  387. }
  388. //==============================================================================
  389. String::String (const int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  390. String::String (const unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  391. String::String (const short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {}
  392. String::String (const unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {}
  393. String::String (const int64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  394. String::String (const uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  395. String::String (const float number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces)) {}
  396. String::String (const double number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces)) {}
  397. //==============================================================================
  398. int String::length() const noexcept
  399. {
  400. return (int) text.length();
  401. }
  402. size_t String::getByteOffsetOfEnd() const noexcept
  403. {
  404. return (size_t) (((char*) text.findTerminatingNull().getAddress()) - (char*) text.getAddress());
  405. }
  406. const juce_wchar String::operator[] (int index) const noexcept
  407. {
  408. jassert (index == 0 || (index > 0 && index <= (int) text.lengthUpTo ((size_t) index + 1)));
  409. return text [index];
  410. }
  411. int String::hashCode() const noexcept
  412. {
  413. CharPointerType t (text);
  414. int result = 0;
  415. while (! t.isEmpty())
  416. result = 31 * result + (int) t.getAndAdvance();
  417. return result;
  418. }
  419. int64 String::hashCode64() const noexcept
  420. {
  421. CharPointerType t (text);
  422. int64 result = 0;
  423. while (! t.isEmpty())
  424. result = 101 * result + t.getAndAdvance();
  425. return result;
  426. }
  427. //==============================================================================
  428. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; }
  429. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const char* const s2) noexcept { return s1.compare (s2) == 0; }
  430. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) == 0; }
  431. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF8& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  432. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF16& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  433. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF32& s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  434. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; }
  435. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const char* const s2) noexcept { return s1.compare (s2) != 0; }
  436. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const wchar_t* const s2) noexcept { return s1.compare (s2) != 0; }
  437. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF8& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  438. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF16& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  439. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF32& s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  440. JUCE_API bool JUCE_CALLTYPE operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; }
  441. JUCE_API bool JUCE_CALLTYPE operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; }
  442. JUCE_API bool JUCE_CALLTYPE operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; }
  443. JUCE_API bool JUCE_CALLTYPE operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; }
  444. bool String::equalsIgnoreCase (const wchar_t* const t) const noexcept
  445. {
  446. return t != nullptr ? text.compareIgnoreCase (castToCharPointer_wchar_t (t)) == 0
  447. : isEmpty();
  448. }
  449. bool String::equalsIgnoreCase (const char* const t) const noexcept
  450. {
  451. return t != nullptr ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  452. : isEmpty();
  453. }
  454. bool String::equalsIgnoreCase (const String& other) const noexcept
  455. {
  456. return text == other.text
  457. || text.compareIgnoreCase (other.text) == 0;
  458. }
  459. int String::compare (const String& other) const noexcept { return (text == other.text) ? 0 : text.compare (other.text); }
  460. int String::compare (const char* const other) const noexcept { return text.compare (CharPointer_UTF8 (other)); }
  461. int String::compare (const wchar_t* const other) const noexcept { return text.compare (castToCharPointer_wchar_t (other)); }
  462. int String::compareIgnoreCase (const String& other) const noexcept { return (text == other.text) ? 0 : text.compareIgnoreCase (other.text); }
  463. int String::compareLexicographically (const String& other) const noexcept
  464. {
  465. CharPointerType s1 (text);
  466. while (! (s1.isEmpty() || s1.isLetterOrDigit()))
  467. ++s1;
  468. CharPointerType s2 (other.text);
  469. while (! (s2.isEmpty() || s2.isLetterOrDigit()))
  470. ++s2;
  471. return s1.compareIgnoreCase (s2);
  472. }
  473. //==============================================================================
  474. void String::append (const String& textToAppend, size_t maxCharsToTake)
  475. {
  476. appendCharPointer (textToAppend.text, maxCharsToTake);
  477. }
  478. String& String::operator+= (const wchar_t* const t)
  479. {
  480. appendCharPointer (castToCharPointer_wchar_t (t));
  481. return *this;
  482. }
  483. String& String::operator+= (const char* const t)
  484. {
  485. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  486. that contains values greater than 127. These can NOT be correctly converted to unicode
  487. because there's no way for the String class to know what encoding was used to
  488. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  489. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  490. string to the String class - so for example if your source data is actually UTF-8,
  491. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  492. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  493. you use UTF-8 with escape characters in your source code to represent extended characters,
  494. because there's no other way to represent these strings in a way that isn't dependent on
  495. the compiler, source code editor and platform.
  496. */
  497. jassert (t == nullptr || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  498. appendCharPointer (CharPointer_ASCII (t));
  499. return *this;
  500. }
  501. String& String::operator+= (const String& other)
  502. {
  503. if (isEmpty())
  504. return operator= (other);
  505. appendCharPointer (other.text);
  506. return *this;
  507. }
  508. String& String::operator+= (const char ch)
  509. {
  510. const char asString[] = { ch, 0 };
  511. return operator+= (asString);
  512. }
  513. String& String::operator+= (const wchar_t ch)
  514. {
  515. const wchar_t asString[] = { ch, 0 };
  516. return operator+= (asString);
  517. }
  518. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  519. String& String::operator+= (const juce_wchar ch)
  520. {
  521. const juce_wchar asString[] = { ch, 0 };
  522. appendCharPointer (CharPointer_UTF32 (asString));
  523. return *this;
  524. }
  525. #endif
  526. String& String::operator+= (const int number)
  527. {
  528. char buffer [16];
  529. char* const end = buffer + numElementsInArray (buffer);
  530. char* const start = NumberToStringConverters::numberToString (end, number);
  531. const int numExtraChars = (int) (end - start);
  532. if (numExtraChars > 0)
  533. {
  534. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  535. const size_t newBytesNeeded = sizeof (CharPointerType::CharType) + byteOffsetOfNull
  536. + sizeof (CharPointerType::CharType) * numExtraChars;
  537. text = StringHolder::makeUniqueWithByteSize (text, newBytesNeeded);
  538. CharPointerType newEnd (addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull));
  539. newEnd.writeWithCharLimit (CharPointer_ASCII (start), numExtraChars);
  540. }
  541. return *this;
  542. }
  543. //==============================================================================
  544. JUCE_API String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  545. {
  546. String s (string1);
  547. return s += string2;
  548. }
  549. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* const string1, const String& string2)
  550. {
  551. String s (string1);
  552. return s += string2;
  553. }
  554. JUCE_API String JUCE_CALLTYPE operator+ (const char s1, const String& s2) { return String::charToString ((juce_wchar) (uint8) s1) + s2; }
  555. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t s1, const String& s2) { return String::charToString (s1) + s2; }
  556. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  557. JUCE_API String JUCE_CALLTYPE operator+ (const juce_wchar s1, const String& s2) { return String::charToString (s1) + s2; }
  558. #endif
  559. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const String& s2) { return s1 += s2; }
  560. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char* const s2) { return s1 += s2; }
  561. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t* s2) { return s1 += s2; }
  562. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char s2) { return s1 += s2; }
  563. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t s2) { return s1 += s2; }
  564. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  565. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const juce_wchar s2) { return s1 += s2; }
  566. #endif
  567. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char s2) { return s1 += s2; }
  568. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t s2) { return s1 += s2; }
  569. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  570. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const juce_wchar s2) { return s1 += s2; }
  571. #endif
  572. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char* const s2) { return s1 += s2; }
  573. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t* const s2) { return s1 += s2; }
  574. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const String& s2) { return s1 += s2; }
  575. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const short number) { return s1 += (int) number; }
  576. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const int number) { return s1 += number; }
  577. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const long number) { return s1 += (int) number; }
  578. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const float number) { return s1 += String (number); }
  579. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const double number) { return s1 += String (number); }
  580. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  581. {
  582. const int numBytes = text.getNumBytesAsUTF8();
  583. #if (JUCE_STRING_UTF_TYPE == 8)
  584. stream.write (text.getCharPointer().getAddress(), numBytes);
  585. #else
  586. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  587. // if lots of large, persistent strings were to be written to streams).
  588. HeapBlock<char> temp (numBytes + 1);
  589. CharPointer_UTF8 (temp).writeAll (text.getCharPointer());
  590. stream.write (temp, numBytes);
  591. #endif
  592. return stream;
  593. }
  594. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const NewLine&)
  595. {
  596. return string1 += NewLine::getDefault();
  597. }
  598. //==============================================================================
  599. int String::indexOfChar (const juce_wchar character) const noexcept
  600. {
  601. return text.indexOf (character);
  602. }
  603. int String::indexOfChar (const int startIndex, const juce_wchar character) const noexcept
  604. {
  605. CharPointerType t (text);
  606. for (int i = 0; ! t.isEmpty(); ++i)
  607. {
  608. if (i >= startIndex)
  609. {
  610. if (t.getAndAdvance() == character)
  611. return i;
  612. }
  613. else
  614. {
  615. ++t;
  616. }
  617. }
  618. return -1;
  619. }
  620. int String::lastIndexOfChar (const juce_wchar character) const noexcept
  621. {
  622. CharPointerType t (text);
  623. int last = -1;
  624. for (int i = 0; ! t.isEmpty(); ++i)
  625. if (t.getAndAdvance() == character)
  626. last = i;
  627. return last;
  628. }
  629. int String::indexOfAnyOf (const String& charactersToLookFor, const int startIndex, const bool ignoreCase) const noexcept
  630. {
  631. CharPointerType t (text);
  632. for (int i = 0; ! t.isEmpty(); ++i)
  633. {
  634. if (i >= startIndex)
  635. {
  636. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  637. return i;
  638. }
  639. else
  640. {
  641. ++t;
  642. }
  643. }
  644. return -1;
  645. }
  646. int String::indexOf (const String& other) const noexcept
  647. {
  648. return other.isEmpty() ? 0 : text.indexOf (other.text);
  649. }
  650. int String::indexOfIgnoreCase (const String& other) const noexcept
  651. {
  652. return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text);
  653. }
  654. int String::indexOf (const int startIndex, const String& other) const noexcept
  655. {
  656. if (other.isEmpty())
  657. return -1;
  658. CharPointerType t (text);
  659. for (int i = startIndex; --i >= 0;)
  660. {
  661. if (t.isEmpty())
  662. return -1;
  663. ++t;
  664. }
  665. int found = t.indexOf (other.text);
  666. if (found >= 0)
  667. found += startIndex;
  668. return found;
  669. }
  670. int String::indexOfIgnoreCase (const int startIndex, const String& other) const noexcept
  671. {
  672. if (other.isEmpty())
  673. return -1;
  674. CharPointerType t (text);
  675. for (int i = startIndex; --i >= 0;)
  676. {
  677. if (t.isEmpty())
  678. return -1;
  679. ++t;
  680. }
  681. int found = CharacterFunctions::indexOfIgnoreCase (t, other.text);
  682. if (found >= 0)
  683. found += startIndex;
  684. return found;
  685. }
  686. int String::lastIndexOf (const String& other) const noexcept
  687. {
  688. if (other.isNotEmpty())
  689. {
  690. const int len = other.length();
  691. int i = length() - len;
  692. if (i >= 0)
  693. {
  694. CharPointerType n (text + i);
  695. while (i >= 0)
  696. {
  697. if (n.compareUpTo (other.text, len) == 0)
  698. return i;
  699. --n;
  700. --i;
  701. }
  702. }
  703. }
  704. return -1;
  705. }
  706. int String::lastIndexOfIgnoreCase (const String& other) const noexcept
  707. {
  708. if (other.isNotEmpty())
  709. {
  710. const int len = other.length();
  711. int i = length() - len;
  712. if (i >= 0)
  713. {
  714. CharPointerType n (text + i);
  715. while (i >= 0)
  716. {
  717. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  718. return i;
  719. --n;
  720. --i;
  721. }
  722. }
  723. }
  724. return -1;
  725. }
  726. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const noexcept
  727. {
  728. CharPointerType t (text);
  729. int last = -1;
  730. for (int i = 0; ! t.isEmpty(); ++i)
  731. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  732. last = i;
  733. return last;
  734. }
  735. bool String::contains (const String& other) const noexcept
  736. {
  737. return indexOf (other) >= 0;
  738. }
  739. bool String::containsChar (const juce_wchar character) const noexcept
  740. {
  741. return text.indexOf (character) >= 0;
  742. }
  743. bool String::containsIgnoreCase (const String& t) const noexcept
  744. {
  745. return indexOfIgnoreCase (t) >= 0;
  746. }
  747. int String::indexOfWholeWord (const String& word) const noexcept
  748. {
  749. if (word.isNotEmpty())
  750. {
  751. CharPointerType t (text);
  752. const int wordLen = word.length();
  753. const int end = (int) t.length() - wordLen;
  754. for (int i = 0; i <= end; ++i)
  755. {
  756. if (t.compareUpTo (word.text, wordLen) == 0
  757. && (i == 0 || ! (t - 1).isLetterOrDigit())
  758. && ! (t + wordLen).isLetterOrDigit())
  759. return i;
  760. ++t;
  761. }
  762. }
  763. return -1;
  764. }
  765. int String::indexOfWholeWordIgnoreCase (const String& word) const noexcept
  766. {
  767. if (word.isNotEmpty())
  768. {
  769. CharPointerType t (text);
  770. const int wordLen = word.length();
  771. const int end = (int) t.length() - wordLen;
  772. for (int i = 0; i <= end; ++i)
  773. {
  774. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  775. && (i == 0 || ! (t - 1).isLetterOrDigit())
  776. && ! (t + wordLen).isLetterOrDigit())
  777. return i;
  778. ++t;
  779. }
  780. }
  781. return -1;
  782. }
  783. bool String::containsWholeWord (const String& wordToLookFor) const noexcept
  784. {
  785. return indexOfWholeWord (wordToLookFor) >= 0;
  786. }
  787. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const noexcept
  788. {
  789. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  790. }
  791. //==============================================================================
  792. template <typename CharPointer>
  793. struct WildCardMatcher
  794. {
  795. static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  796. {
  797. for (;;)
  798. {
  799. const juce_wchar wc = wildcard.getAndAdvance();
  800. const juce_wchar tc = *test;
  801. if (wc == tc
  802. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc))
  803. || (wc == '?' && tc != 0))
  804. {
  805. if (wc == 0)
  806. return true;
  807. ++test;
  808. }
  809. else
  810. {
  811. return wc == '*' && (wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase));
  812. }
  813. }
  814. }
  815. static bool matchesAnywhere (const CharPointer& wildcard, CharPointer test, const bool ignoreCase) noexcept
  816. {
  817. while (! test.isEmpty())
  818. {
  819. if (matches (wildcard, test, ignoreCase))
  820. return true;
  821. ++test;
  822. }
  823. return false;
  824. }
  825. };
  826. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const noexcept
  827. {
  828. return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase);
  829. }
  830. //==============================================================================
  831. String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  832. {
  833. if (numberOfTimesToRepeat <= 0)
  834. return empty;
  835. String result (PreallocationBytes (stringToRepeat.getByteOffsetOfEnd() * numberOfTimesToRepeat));
  836. CharPointerType n (result.text);
  837. while (--numberOfTimesToRepeat >= 0)
  838. n.writeAll (stringToRepeat.text);
  839. return result;
  840. }
  841. String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  842. {
  843. jassert (padCharacter != 0);
  844. int extraChars = minimumLength;
  845. CharPointerType end (text);
  846. while (! end.isEmpty())
  847. {
  848. --extraChars;
  849. ++end;
  850. }
  851. if (extraChars <= 0 || padCharacter == 0)
  852. return *this;
  853. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  854. String result (PreallocationBytes (currentByteSize + extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  855. CharPointerType n (result.text);
  856. while (--extraChars >= 0)
  857. n.write (padCharacter);
  858. n.writeAll (text);
  859. return result;
  860. }
  861. String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  862. {
  863. jassert (padCharacter != 0);
  864. int extraChars = minimumLength;
  865. CharPointerType end (text);
  866. while (! end.isEmpty())
  867. {
  868. --extraChars;
  869. ++end;
  870. }
  871. if (extraChars <= 0 || padCharacter == 0)
  872. return *this;
  873. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  874. String result (PreallocationBytes (currentByteSize + extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  875. CharPointerType n (result.text);
  876. n.writeAll (text);
  877. while (--extraChars >= 0)
  878. n.write (padCharacter);
  879. n.writeNull();
  880. return result;
  881. }
  882. //==============================================================================
  883. String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  884. {
  885. if (index < 0)
  886. {
  887. // a negative index to replace from?
  888. jassertfalse;
  889. index = 0;
  890. }
  891. if (numCharsToReplace < 0)
  892. {
  893. // replacing a negative number of characters?
  894. numCharsToReplace = 0;
  895. jassertfalse;
  896. }
  897. int i = 0;
  898. CharPointerType insertPoint (text);
  899. while (i < index)
  900. {
  901. if (insertPoint.isEmpty())
  902. {
  903. // replacing beyond the end of the string?
  904. jassertfalse;
  905. return *this + stringToInsert;
  906. }
  907. ++insertPoint;
  908. ++i;
  909. }
  910. CharPointerType startOfRemainder (insertPoint);
  911. i = 0;
  912. while (i < numCharsToReplace && ! startOfRemainder.isEmpty())
  913. {
  914. ++startOfRemainder;
  915. ++i;
  916. }
  917. if (insertPoint == text && startOfRemainder.isEmpty())
  918. return stringToInsert;
  919. const size_t initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress());
  920. const size_t newStringBytes = stringToInsert.getByteOffsetOfEnd();
  921. const size_t remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress());
  922. const size_t newTotalBytes = initialBytes + newStringBytes + remainderBytes;
  923. if (newTotalBytes <= 0)
  924. return String::empty;
  925. String result (PreallocationBytes ((size_t) newTotalBytes));
  926. char* dest = (char*) result.text.getAddress();
  927. memcpy (dest, text.getAddress(), initialBytes);
  928. dest += initialBytes;
  929. memcpy (dest, stringToInsert.text.getAddress(), newStringBytes);
  930. dest += newStringBytes;
  931. memcpy (dest, startOfRemainder.getAddress(), remainderBytes);
  932. dest += remainderBytes;
  933. CharPointerType ((CharPointerType::CharType*) dest).writeNull();
  934. return result;
  935. }
  936. String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  937. {
  938. const int stringToReplaceLen = stringToReplace.length();
  939. const int stringToInsertLen = stringToInsert.length();
  940. int i = 0;
  941. String result (*this);
  942. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  943. : result.indexOf (i, stringToReplace))) >= 0)
  944. {
  945. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  946. i += stringToInsertLen;
  947. }
  948. return result;
  949. }
  950. class StringCreationHelper
  951. {
  952. public:
  953. StringCreationHelper (const size_t initialBytes)
  954. : source (nullptr), dest (nullptr), allocatedBytes (initialBytes), bytesWritten (0)
  955. {
  956. result.preallocateBytes (allocatedBytes);
  957. dest = result.getCharPointer();
  958. }
  959. StringCreationHelper (const String::CharPointerType& source_)
  960. : source (source_), dest (nullptr), allocatedBytes (StringHolder::getAllocatedNumBytes (source)), bytesWritten (0)
  961. {
  962. result.preallocateBytes (allocatedBytes);
  963. dest = result.getCharPointer();
  964. }
  965. void write (juce_wchar c)
  966. {
  967. bytesWritten += String::CharPointerType::getBytesRequiredFor (c);
  968. if (bytesWritten > allocatedBytes)
  969. {
  970. allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16);
  971. const size_t destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress());
  972. result.preallocateBytes (allocatedBytes);
  973. dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset);
  974. }
  975. dest.write (c);
  976. }
  977. String result;
  978. String::CharPointerType source;
  979. private:
  980. String::CharPointerType dest;
  981. size_t allocatedBytes, bytesWritten;
  982. };
  983. String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  984. {
  985. if (! containsChar (charToReplace))
  986. return *this;
  987. StringCreationHelper builder (text);
  988. for (;;)
  989. {
  990. juce_wchar c = builder.source.getAndAdvance();
  991. if (c == charToReplace)
  992. c = charToInsert;
  993. builder.write (c);
  994. if (c == 0)
  995. break;
  996. }
  997. return builder.result;
  998. }
  999. String String::replaceCharacters (const String& charactersToReplace, const String& charactersToInsertInstead) const
  1000. {
  1001. StringCreationHelper builder (text);
  1002. for (;;)
  1003. {
  1004. juce_wchar c = builder.source.getAndAdvance();
  1005. const int index = charactersToReplace.indexOfChar (c);
  1006. if (index >= 0)
  1007. c = charactersToInsertInstead [index];
  1008. builder.write (c);
  1009. if (c == 0)
  1010. break;
  1011. }
  1012. return builder.result;
  1013. }
  1014. //==============================================================================
  1015. bool String::startsWith (const String& other) const noexcept
  1016. {
  1017. return text.compareUpTo (other.text, other.length()) == 0;
  1018. }
  1019. bool String::startsWithIgnoreCase (const String& other) const noexcept
  1020. {
  1021. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  1022. }
  1023. bool String::startsWithChar (const juce_wchar character) const noexcept
  1024. {
  1025. jassert (character != 0); // strings can't contain a null character!
  1026. return *text == character;
  1027. }
  1028. bool String::endsWithChar (const juce_wchar character) const noexcept
  1029. {
  1030. jassert (character != 0); // strings can't contain a null character!
  1031. if (text.isEmpty())
  1032. return false;
  1033. CharPointerType t (text.findTerminatingNull());
  1034. return *--t == character;
  1035. }
  1036. bool String::endsWith (const String& other) const noexcept
  1037. {
  1038. CharPointerType end (text.findTerminatingNull());
  1039. CharPointerType otherEnd (other.text.findTerminatingNull());
  1040. while (end > text && otherEnd > other.text)
  1041. {
  1042. --end;
  1043. --otherEnd;
  1044. if (*end != *otherEnd)
  1045. return false;
  1046. }
  1047. return otherEnd == other.text;
  1048. }
  1049. bool String::endsWithIgnoreCase (const String& other) const noexcept
  1050. {
  1051. CharPointerType end (text.findTerminatingNull());
  1052. CharPointerType otherEnd (other.text.findTerminatingNull());
  1053. while (end > text && otherEnd > other.text)
  1054. {
  1055. --end;
  1056. --otherEnd;
  1057. if (end.toLowerCase() != otherEnd.toLowerCase())
  1058. return false;
  1059. }
  1060. return otherEnd == other.text;
  1061. }
  1062. //==============================================================================
  1063. String String::toUpperCase() const
  1064. {
  1065. StringCreationHelper builder (text);
  1066. for (;;)
  1067. {
  1068. const juce_wchar c = builder.source.toUpperCase();
  1069. ++(builder.source);
  1070. builder.write (c);
  1071. if (c == 0)
  1072. break;
  1073. }
  1074. return builder.result;
  1075. }
  1076. String String::toLowerCase() const
  1077. {
  1078. StringCreationHelper builder (text);
  1079. for (;;)
  1080. {
  1081. const juce_wchar c = builder.source.toLowerCase();
  1082. ++(builder.source);
  1083. builder.write (c);
  1084. if (c == 0)
  1085. break;
  1086. }
  1087. return builder.result;
  1088. }
  1089. //==============================================================================
  1090. juce_wchar String::getLastCharacter() const noexcept
  1091. {
  1092. return isEmpty() ? juce_wchar() : text [length() - 1];
  1093. }
  1094. String String::substring (int start, const int end) const
  1095. {
  1096. if (start < 0)
  1097. start = 0;
  1098. if (end <= start)
  1099. return empty;
  1100. int i = 0;
  1101. CharPointerType t1 (text);
  1102. while (i < start)
  1103. {
  1104. if (t1.isEmpty())
  1105. return empty;
  1106. ++i;
  1107. ++t1;
  1108. }
  1109. CharPointerType t2 (t1);
  1110. while (i < end)
  1111. {
  1112. if (t2.isEmpty())
  1113. {
  1114. if (start == 0)
  1115. return *this;
  1116. break;
  1117. }
  1118. ++i;
  1119. ++t2;
  1120. }
  1121. return String (t1, t2);
  1122. }
  1123. String String::substring (int start) const
  1124. {
  1125. if (start <= 0)
  1126. return *this;
  1127. CharPointerType t (text);
  1128. while (--start >= 0)
  1129. {
  1130. if (t.isEmpty())
  1131. return empty;
  1132. ++t;
  1133. }
  1134. return String (t);
  1135. }
  1136. String String::dropLastCharacters (const int numberToDrop) const
  1137. {
  1138. return String (text, (size_t) jmax (0, length() - numberToDrop));
  1139. }
  1140. String String::getLastCharacters (const int numCharacters) const
  1141. {
  1142. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  1143. }
  1144. String String::fromFirstOccurrenceOf (const String& sub,
  1145. const bool includeSubString,
  1146. const bool ignoreCase) const
  1147. {
  1148. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1149. : indexOf (sub);
  1150. if (i < 0)
  1151. return empty;
  1152. return substring (includeSubString ? i : i + sub.length());
  1153. }
  1154. String String::fromLastOccurrenceOf (const String& sub,
  1155. const bool includeSubString,
  1156. const bool ignoreCase) const
  1157. {
  1158. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1159. : lastIndexOf (sub);
  1160. if (i < 0)
  1161. return *this;
  1162. return substring (includeSubString ? i : i + sub.length());
  1163. }
  1164. String String::upToFirstOccurrenceOf (const String& sub,
  1165. const bool includeSubString,
  1166. const bool ignoreCase) const
  1167. {
  1168. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1169. : indexOf (sub);
  1170. if (i < 0)
  1171. return *this;
  1172. return substring (0, includeSubString ? i + sub.length() : i);
  1173. }
  1174. String String::upToLastOccurrenceOf (const String& sub,
  1175. const bool includeSubString,
  1176. const bool ignoreCase) const
  1177. {
  1178. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1179. : lastIndexOf (sub);
  1180. if (i < 0)
  1181. return *this;
  1182. return substring (0, includeSubString ? i + sub.length() : i);
  1183. }
  1184. bool String::isQuotedString() const
  1185. {
  1186. const String trimmed (trimStart());
  1187. return trimmed[0] == '"'
  1188. || trimmed[0] == '\'';
  1189. }
  1190. String String::unquoted() const
  1191. {
  1192. const int len = length();
  1193. if (len == 0)
  1194. return empty;
  1195. const juce_wchar lastChar = text [len - 1];
  1196. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  1197. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  1198. return substring (dropAtStart, len - dropAtEnd);
  1199. }
  1200. String String::quoted (const juce_wchar quoteCharacter) const
  1201. {
  1202. if (isEmpty())
  1203. return charToString (quoteCharacter) + quoteCharacter;
  1204. String t (*this);
  1205. if (! t.startsWithChar (quoteCharacter))
  1206. t = charToString (quoteCharacter) + t;
  1207. if (! t.endsWithChar (quoteCharacter))
  1208. t += quoteCharacter;
  1209. return t;
  1210. }
  1211. //==============================================================================
  1212. static String::CharPointerType findTrimmedEnd (const String::CharPointerType& start, String::CharPointerType end)
  1213. {
  1214. while (end > start)
  1215. {
  1216. if (! (--end).isWhitespace())
  1217. {
  1218. ++end;
  1219. break;
  1220. }
  1221. }
  1222. return end;
  1223. }
  1224. String String::trim() const
  1225. {
  1226. if (isNotEmpty())
  1227. {
  1228. CharPointerType start (text.findEndOfWhitespace());
  1229. const CharPointerType end (start.findTerminatingNull());
  1230. CharPointerType trimmedEnd (findTrimmedEnd (start, end));
  1231. if (trimmedEnd <= start)
  1232. return empty;
  1233. else if (text < start || trimmedEnd < end)
  1234. return String (start, trimmedEnd);
  1235. }
  1236. return *this;
  1237. }
  1238. String String::trimStart() const
  1239. {
  1240. if (isNotEmpty())
  1241. {
  1242. const CharPointerType t (text.findEndOfWhitespace());
  1243. if (t != text)
  1244. return String (t);
  1245. }
  1246. return *this;
  1247. }
  1248. String String::trimEnd() const
  1249. {
  1250. if (isNotEmpty())
  1251. {
  1252. const CharPointerType end (text.findTerminatingNull());
  1253. CharPointerType trimmedEnd (findTrimmedEnd (text, end));
  1254. if (trimmedEnd < end)
  1255. return String (text, trimmedEnd);
  1256. }
  1257. return *this;
  1258. }
  1259. String String::trimCharactersAtStart (const String& charactersToTrim) const
  1260. {
  1261. CharPointerType t (text);
  1262. while (charactersToTrim.containsChar (*t))
  1263. ++t;
  1264. return t == text ? *this : String (t);
  1265. }
  1266. String String::trimCharactersAtEnd (const String& charactersToTrim) const
  1267. {
  1268. if (isNotEmpty())
  1269. {
  1270. const CharPointerType end (text.findTerminatingNull());
  1271. CharPointerType trimmedEnd (end);
  1272. while (trimmedEnd > text)
  1273. {
  1274. if (! charactersToTrim.containsChar (*--trimmedEnd))
  1275. {
  1276. ++trimmedEnd;
  1277. break;
  1278. }
  1279. }
  1280. if (trimmedEnd < end)
  1281. return String (text, trimmedEnd);
  1282. }
  1283. return *this;
  1284. }
  1285. //==============================================================================
  1286. String String::retainCharacters (const String& charactersToRetain) const
  1287. {
  1288. if (isEmpty())
  1289. return empty;
  1290. StringCreationHelper builder (text);
  1291. for (;;)
  1292. {
  1293. juce_wchar c = builder.source.getAndAdvance();
  1294. if (charactersToRetain.containsChar (c))
  1295. builder.write (c);
  1296. if (c == 0)
  1297. break;
  1298. }
  1299. builder.write (0);
  1300. return builder.result;
  1301. }
  1302. String String::removeCharacters (const String& charactersToRemove) const
  1303. {
  1304. if (isEmpty())
  1305. return empty;
  1306. StringCreationHelper builder (text);
  1307. for (;;)
  1308. {
  1309. juce_wchar c = builder.source.getAndAdvance();
  1310. if (! charactersToRemove.containsChar (c))
  1311. builder.write (c);
  1312. if (c == 0)
  1313. break;
  1314. }
  1315. return builder.result;
  1316. }
  1317. String String::initialSectionContainingOnly (const String& permittedCharacters) const
  1318. {
  1319. CharPointerType t (text);
  1320. while (! t.isEmpty())
  1321. {
  1322. if (! permittedCharacters.containsChar (*t))
  1323. return String (text, t);
  1324. ++t;
  1325. }
  1326. return *this;
  1327. }
  1328. String String::initialSectionNotContaining (const String& charactersToStopAt) const
  1329. {
  1330. CharPointerType t (text);
  1331. while (! t.isEmpty())
  1332. {
  1333. if (charactersToStopAt.containsChar (*t))
  1334. return String (text, t);
  1335. ++t;
  1336. }
  1337. return *this;
  1338. }
  1339. bool String::containsOnly (const String& chars) const noexcept
  1340. {
  1341. CharPointerType t (text);
  1342. while (! t.isEmpty())
  1343. if (! chars.containsChar (t.getAndAdvance()))
  1344. return false;
  1345. return true;
  1346. }
  1347. bool String::containsAnyOf (const String& chars) const noexcept
  1348. {
  1349. CharPointerType t (text);
  1350. while (! t.isEmpty())
  1351. if (chars.containsChar (t.getAndAdvance()))
  1352. return true;
  1353. return false;
  1354. }
  1355. bool String::containsNonWhitespaceChars() const noexcept
  1356. {
  1357. CharPointerType t (text);
  1358. while (! t.isEmpty())
  1359. {
  1360. if (! t.isWhitespace())
  1361. return true;
  1362. ++t;
  1363. }
  1364. return false;
  1365. }
  1366. // Note! The format parameter here MUST NOT be a reference, otherwise MS's va_start macro fails to work (but still compiles).
  1367. String String::formatted (const String pf, ... )
  1368. {
  1369. size_t bufferSize = 256;
  1370. for (;;)
  1371. {
  1372. va_list args;
  1373. va_start (args, pf);
  1374. #if JUCE_WINDOWS
  1375. HeapBlock <wchar_t> temp (bufferSize);
  1376. const int num = (int) _vsnwprintf (temp.getData(), bufferSize - 1, pf.toWideCharPointer(), args);
  1377. #elif JUCE_ANDROID
  1378. HeapBlock <char> temp (bufferSize);
  1379. const int num = (int) vsnprintf (temp.getData(), bufferSize - 1, pf.toUTF8(), args);
  1380. #else
  1381. HeapBlock <wchar_t> temp (bufferSize);
  1382. const int num = (int) vswprintf (temp.getData(), bufferSize - 1, pf.toWideCharPointer(), args);
  1383. #endif
  1384. va_end (args);
  1385. if (num > 0)
  1386. return String (temp);
  1387. bufferSize += 256;
  1388. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  1389. break; // returns -1 because of an error rather than because it needs more space.
  1390. }
  1391. return empty;
  1392. }
  1393. //==============================================================================
  1394. int String::getIntValue() const noexcept
  1395. {
  1396. return text.getIntValue32();
  1397. }
  1398. int String::getTrailingIntValue() const noexcept
  1399. {
  1400. int n = 0;
  1401. int mult = 1;
  1402. CharPointerType t (text.findTerminatingNull());
  1403. while (--t >= text)
  1404. {
  1405. if (! t.isDigit())
  1406. {
  1407. if (*t == '-')
  1408. n = -n;
  1409. break;
  1410. }
  1411. n += mult * (*t - '0');
  1412. mult *= 10;
  1413. }
  1414. return n;
  1415. }
  1416. int64 String::getLargeIntValue() const noexcept
  1417. {
  1418. return text.getIntValue64();
  1419. }
  1420. float String::getFloatValue() const noexcept
  1421. {
  1422. return (float) getDoubleValue();
  1423. }
  1424. double String::getDoubleValue() const noexcept
  1425. {
  1426. return text.getDoubleValue();
  1427. }
  1428. static const char hexDigits[] = "0123456789abcdef";
  1429. template <typename Type>
  1430. struct HexConverter
  1431. {
  1432. static String hexToString (Type v)
  1433. {
  1434. char buffer[32];
  1435. char* const end = buffer + 32;
  1436. char* t = end;
  1437. *--t = 0;
  1438. do
  1439. {
  1440. *--t = hexDigits [(int) (v & 15)];
  1441. v >>= 4;
  1442. } while (v != 0);
  1443. return String (t, (size_t) (end - t) - 1);
  1444. }
  1445. static Type stringToHex (String::CharPointerType t) noexcept
  1446. {
  1447. Type result = 0;
  1448. while (! t.isEmpty())
  1449. {
  1450. const int hexValue = CharacterFunctions::getHexDigitValue (t.getAndAdvance());
  1451. if (hexValue >= 0)
  1452. result = (result << 4) | hexValue;
  1453. }
  1454. return result;
  1455. }
  1456. };
  1457. String String::toHexString (const int number)
  1458. {
  1459. return HexConverter <unsigned int>::hexToString ((unsigned int) number);
  1460. }
  1461. String String::toHexString (const int64 number)
  1462. {
  1463. return HexConverter <uint64>::hexToString ((uint64) number);
  1464. }
  1465. String String::toHexString (const short number)
  1466. {
  1467. return toHexString ((int) (unsigned short) number);
  1468. }
  1469. String String::toHexString (const void* const d, const int size, const int groupSize)
  1470. {
  1471. if (size <= 0)
  1472. return empty;
  1473. int numChars = (size * 2) + 2;
  1474. if (groupSize > 0)
  1475. numChars += size / groupSize;
  1476. String s (PreallocationBytes (sizeof (CharPointerType::CharType) * (size_t) numChars));
  1477. const unsigned char* data = static_cast <const unsigned char*> (d);
  1478. CharPointerType dest (s.text);
  1479. for (int i = 0; i < size; ++i)
  1480. {
  1481. const unsigned char nextByte = *data++;
  1482. dest.write ((juce_wchar) hexDigits [nextByte >> 4]);
  1483. dest.write ((juce_wchar) hexDigits [nextByte & 0xf]);
  1484. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  1485. dest.write ((juce_wchar) ' ');
  1486. }
  1487. dest.writeNull();
  1488. return s;
  1489. }
  1490. int String::getHexValue32() const noexcept
  1491. {
  1492. return HexConverter<int>::stringToHex (text);
  1493. }
  1494. int64 String::getHexValue64() const noexcept
  1495. {
  1496. return HexConverter<int64>::stringToHex (text);
  1497. }
  1498. //==============================================================================
  1499. String String::createStringFromData (const void* const data_, const int size)
  1500. {
  1501. const uint8* const data = static_cast <const uint8*> (data_);
  1502. if (size <= 0 || data == nullptr)
  1503. {
  1504. return empty;
  1505. }
  1506. else if (size == 1)
  1507. {
  1508. return charToString ((juce_wchar) data[0]);
  1509. }
  1510. else if ((data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkBE2)
  1511. || (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkLE1 && data[1] == (uint8) CharPointer_UTF16::byteOrderMarkLE2))
  1512. {
  1513. const bool bigEndian = (data[0] == (uint8) CharPointer_UTF16::byteOrderMarkBE1);
  1514. const int numChars = size / 2 - 1;
  1515. StringCreationHelper builder ((size_t) numChars);
  1516. const uint16* const src = (const uint16*) (data + 2);
  1517. if (bigEndian)
  1518. {
  1519. for (int i = 0; i < numChars; ++i)
  1520. builder.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  1521. }
  1522. else
  1523. {
  1524. for (int i = 0; i < numChars; ++i)
  1525. builder.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  1526. }
  1527. builder.write (0);
  1528. return builder.result;
  1529. }
  1530. else
  1531. {
  1532. const uint8* start = data;
  1533. const uint8* end = data + size;
  1534. if (size >= 3
  1535. && data[0] == (uint8) CharPointer_UTF8::byteOrderMark1
  1536. && data[1] == (uint8) CharPointer_UTF8::byteOrderMark2
  1537. && data[2] == (uint8) CharPointer_UTF8::byteOrderMark3)
  1538. start += 3;
  1539. return String (CharPointer_UTF8 ((const char*) start),
  1540. CharPointer_UTF8 ((const char*) end));
  1541. }
  1542. }
  1543. //==============================================================================
  1544. static const juce_wchar emptyChar = 0;
  1545. template <class CharPointerType_Src, class CharPointerType_Dest>
  1546. struct StringEncodingConverter
  1547. {
  1548. static CharPointerType_Dest convert (const String& s)
  1549. {
  1550. String& source = const_cast <String&> (s);
  1551. typedef typename CharPointerType_Dest::CharType DestChar;
  1552. if (source.isEmpty())
  1553. return CharPointerType_Dest (reinterpret_cast <const DestChar*> (&emptyChar));
  1554. CharPointerType_Src text (source.getCharPointer());
  1555. const size_t extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text);
  1556. const size_t endOffset = (text.sizeInBytes() + 3) & ~3; // the new string must be word-aligned or many Windows
  1557. // functions will fail to read it correctly!
  1558. source.preallocateBytes (endOffset + extraBytesNeeded);
  1559. text = source.getCharPointer();
  1560. void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset);
  1561. const CharPointerType_Dest extraSpace (static_cast <DestChar*> (newSpace));
  1562. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  1563. const int bytesToClear = jmin ((int) extraBytesNeeded, 4);
  1564. zeromem (addBytesToPointer (newSpace, (int) (extraBytesNeeded - bytesToClear)), (size_t) bytesToClear);
  1565. #endif
  1566. CharPointerType_Dest (extraSpace).writeAll (text);
  1567. return extraSpace;
  1568. }
  1569. };
  1570. template <>
  1571. struct StringEncodingConverter <CharPointer_UTF8, CharPointer_UTF8>
  1572. {
  1573. static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 ((CharPointer_UTF8::CharType*) source.getCharPointer().getAddress()); }
  1574. };
  1575. template <>
  1576. struct StringEncodingConverter <CharPointer_UTF16, CharPointer_UTF16>
  1577. {
  1578. static CharPointer_UTF16 convert (const String& source) noexcept { return CharPointer_UTF16 ((CharPointer_UTF16::CharType*) source.getCharPointer().getAddress()); }
  1579. };
  1580. template <>
  1581. struct StringEncodingConverter <CharPointer_UTF32, CharPointer_UTF32>
  1582. {
  1583. static CharPointer_UTF32 convert (const String& source) noexcept { return CharPointer_UTF32 ((CharPointer_UTF32::CharType*) source.getCharPointer().getAddress()); }
  1584. };
  1585. CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF8 >::convert (*this); }
  1586. CharPointer_UTF16 String::toUTF16() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF16>::convert (*this); }
  1587. CharPointer_UTF32 String::toUTF32() const { return StringEncodingConverter <CharPointerType, CharPointer_UTF32>::convert (*this); }
  1588. const wchar_t* String::toWideCharPointer() const
  1589. {
  1590. return StringEncodingConverter <CharPointerType, CharPointer_wchar_t>::convert (*this).getAddress();
  1591. }
  1592. //==============================================================================
  1593. template <class CharPointerType_Src, class CharPointerType_Dest>
  1594. struct StringCopier
  1595. {
  1596. static int copyToBuffer (const CharPointerType_Src& source, typename CharPointerType_Dest::CharType* const buffer, const int maxBufferSizeBytes)
  1597. {
  1598. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  1599. if (buffer == nullptr)
  1600. return (int) (CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType));
  1601. return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes);
  1602. }
  1603. };
  1604. int String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, const int maxBufferSizeBytes) const noexcept
  1605. {
  1606. return StringCopier <CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1607. }
  1608. int String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, int maxBufferSizeBytes) const noexcept
  1609. {
  1610. return StringCopier <CharPointerType, CharPointer_UTF16>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1611. }
  1612. int String::copyToUTF32 (CharPointer_UTF32::CharType* const buffer, int maxBufferSizeBytes) const noexcept
  1613. {
  1614. return StringCopier <CharPointerType, CharPointer_UTF32>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1615. }
  1616. //==============================================================================
  1617. int String::getNumBytesAsUTF8() const noexcept
  1618. {
  1619. return (int) CharPointer_UTF8::getBytesRequiredFor (text);
  1620. }
  1621. String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  1622. {
  1623. if (buffer != nullptr)
  1624. {
  1625. if (bufferSizeBytes < 0)
  1626. return String (CharPointer_UTF8 (buffer));
  1627. else if (bufferSizeBytes > 0)
  1628. return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes));
  1629. }
  1630. return String::empty;
  1631. }
  1632. #if JUCE_MSVC
  1633. #pragma warning (pop)
  1634. #endif
  1635. //==============================================================================
  1636. String::Concatenator::Concatenator (String& stringToAppendTo)
  1637. : result (stringToAppendTo),
  1638. nextIndex (stringToAppendTo.length())
  1639. {
  1640. }
  1641. String::Concatenator::~Concatenator()
  1642. {
  1643. }
  1644. void String::Concatenator::append (const String& s)
  1645. {
  1646. const int len = s.length();
  1647. if (len > 0)
  1648. {
  1649. size_t extraBytes = s.getCharPointer().sizeInBytes();
  1650. result.preallocateBytes (nextIndex + extraBytes);
  1651. CharPointerType (result.text + nextIndex).writeAll (s.text);
  1652. nextIndex += len;
  1653. }
  1654. }
  1655. //==============================================================================
  1656. //==============================================================================
  1657. #if JUCE_UNIT_TESTS
  1658. class StringTests : public UnitTest
  1659. {
  1660. public:
  1661. StringTests() : UnitTest ("String class") {}
  1662. template <class CharPointerType>
  1663. struct TestUTFConversion
  1664. {
  1665. static void test (UnitTest& test)
  1666. {
  1667. String s (createRandomWideCharString());
  1668. typename CharPointerType::CharType buffer [300];
  1669. memset (buffer, 0xff, sizeof (buffer));
  1670. CharPointerType (buffer).writeAll (s.toUTF32());
  1671. test.expectEquals (String (CharPointerType (buffer)), s);
  1672. memset (buffer, 0xff, sizeof (buffer));
  1673. CharPointerType (buffer).writeAll (s.toUTF16());
  1674. test.expectEquals (String (CharPointerType (buffer)), s);
  1675. memset (buffer, 0xff, sizeof (buffer));
  1676. CharPointerType (buffer).writeAll (s.toUTF8());
  1677. test.expectEquals (String (CharPointerType (buffer)), s);
  1678. }
  1679. };
  1680. static String createRandomWideCharString()
  1681. {
  1682. juce_wchar buffer[50] = { 0 };
  1683. Random r;
  1684. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  1685. {
  1686. if (r.nextBool())
  1687. {
  1688. do
  1689. {
  1690. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  1691. }
  1692. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  1693. }
  1694. else
  1695. buffer[i] = (juce_wchar) (1 + r.nextInt (0xff));
  1696. }
  1697. return CharPointer_UTF32 (buffer);
  1698. }
  1699. void runTest()
  1700. {
  1701. {
  1702. beginTest ("Basics");
  1703. expect (String().length() == 0);
  1704. expect (String() == String::empty);
  1705. String s1, s2 ("abcd");
  1706. expect (s1.isEmpty() && ! s1.isNotEmpty());
  1707. expect (s2.isNotEmpty() && ! s2.isEmpty());
  1708. expect (s2.length() == 4);
  1709. s1 = "abcd";
  1710. expect (s2 == s1 && s1 == s2);
  1711. expect (s1 == "abcd" && s1 == L"abcd");
  1712. expect (String ("abcd") == String (L"abcd"));
  1713. expect (String ("abcdefg", 4) == L"abcd");
  1714. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  1715. expect (String::charToString ('x') == "x");
  1716. expect (String::charToString (0) == String::empty);
  1717. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  1718. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  1719. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  1720. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  1721. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  1722. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  1723. expectEquals (s1.indexOf (String::empty), 0);
  1724. expectEquals (s1.indexOfIgnoreCase (String::empty), 0);
  1725. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  1726. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  1727. expect (s1.containsChar ('a'));
  1728. expect (! s1.containsChar ('x'));
  1729. expect (! s1.containsChar (0));
  1730. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  1731. }
  1732. {
  1733. beginTest ("Operations");
  1734. String s ("012345678");
  1735. expect (s.hashCode() != 0);
  1736. expect (s.hashCode64() != 0);
  1737. expect (s.hashCode() != (s + s).hashCode());
  1738. expect (s.hashCode64() != (s + s).hashCode64());
  1739. expect (s.compare (String ("012345678")) == 0);
  1740. expect (s.compare (String ("012345679")) < 0);
  1741. expect (s.compare (String ("012345676")) > 0);
  1742. expect (s.substring (2, 3) == String::charToString (s[2]));
  1743. expect (s.substring (0, 1) == String::charToString (s[0]));
  1744. expect (s.getLastCharacter() == s [s.length() - 1]);
  1745. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  1746. expect (s.substring (0, 3) == L"012");
  1747. expect (s.substring (0, 100) == s);
  1748. expect (s.substring (-1, 100) == s);
  1749. expect (s.substring (3) == "345678");
  1750. expect (s.indexOf (L"45") == 4);
  1751. expect (String ("444445").indexOf ("45") == 4);
  1752. expect (String ("444445").lastIndexOfChar ('4') == 4);
  1753. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  1754. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  1755. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  1756. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  1757. expect (s.indexOfChar (L'4') == 4);
  1758. expect (s + s == "012345678012345678");
  1759. expect (s.startsWith (s));
  1760. expect (s.startsWith (s.substring (0, 4)));
  1761. expect (s.startsWith (s.dropLastCharacters (4)));
  1762. expect (s.endsWith (s.substring (5)));
  1763. expect (s.endsWith (s));
  1764. expect (s.contains (s.substring (3, 6)));
  1765. expect (s.contains (s.substring (3)));
  1766. expect (s.startsWithChar (s[0]));
  1767. expect (s.endsWithChar (s.getLastCharacter()));
  1768. expect (s [s.length()] == 0);
  1769. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  1770. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  1771. String s2 ("123");
  1772. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  1773. s2 += "xyz";
  1774. expect (s2 == "1234567890xyz");
  1775. beginTest ("Numeric conversions");
  1776. expect (String::empty.getIntValue() == 0);
  1777. expect (String::empty.getDoubleValue() == 0.0);
  1778. expect (String::empty.getFloatValue() == 0.0f);
  1779. expect (s.getIntValue() == 12345678);
  1780. expect (s.getLargeIntValue() == (int64) 12345678);
  1781. expect (s.getDoubleValue() == 12345678.0);
  1782. expect (s.getFloatValue() == 12345678.0f);
  1783. expect (String (-1234).getIntValue() == -1234);
  1784. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  1785. expect (String (-1234.56).getDoubleValue() == -1234.56);
  1786. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  1787. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  1788. expect (s.getHexValue32() == 0x12345678);
  1789. expect (s.getHexValue64() == (int64) 0x12345678);
  1790. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  1791. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  1792. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  1793. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  1794. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  1795. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  1796. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  1797. beginTest ("Subsections");
  1798. String s3;
  1799. s3 = "abcdeFGHIJ";
  1800. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  1801. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  1802. expect (s3.containsIgnoreCase (s3.substring (3)));
  1803. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  1804. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  1805. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  1806. expect (s3.containsAnyOf (L"zzzFs"));
  1807. expect (s3.startsWith ("abcd"));
  1808. expect (s3.startsWithIgnoreCase (L"abCD"));
  1809. expect (s3.startsWith (String::empty));
  1810. expect (s3.startsWithChar ('a'));
  1811. expect (s3.endsWith (String ("HIJ")));
  1812. expect (s3.endsWithIgnoreCase (L"Hij"));
  1813. expect (s3.endsWith (String::empty));
  1814. expect (s3.endsWithChar (L'J'));
  1815. expect (s3.indexOf ("HIJ") == 7);
  1816. expect (s3.indexOf (L"HIJK") == -1);
  1817. expect (s3.indexOfIgnoreCase ("hij") == 7);
  1818. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  1819. String s4 (s3);
  1820. s4.append (String ("xyz123"), 3);
  1821. expect (s4 == s3 + "xyz");
  1822. expect (String (1234) < String (1235));
  1823. expect (String (1235) > String (1234));
  1824. expect (String (1234) >= String (1234));
  1825. expect (String (1234) <= String (1234));
  1826. expect (String (1235) >= String (1234));
  1827. expect (String (1234) <= String (1235));
  1828. String s5 ("word word2 word3");
  1829. expect (s5.containsWholeWord (String ("word2")));
  1830. expect (s5.indexOfWholeWord ("word2") == 5);
  1831. expect (s5.containsWholeWord (L"word"));
  1832. expect (s5.containsWholeWord ("word3"));
  1833. expect (s5.containsWholeWord (s5));
  1834. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  1835. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  1836. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  1837. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  1838. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  1839. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  1840. expect (s5.containsNonWhitespaceChars());
  1841. expect (s5.containsOnly ("ordw23 "));
  1842. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  1843. expect (s5.matchesWildcard (L"wor*", false));
  1844. expect (s5.matchesWildcard ("wOr*", true));
  1845. expect (s5.matchesWildcard (L"*word3", true));
  1846. expect (s5.matchesWildcard ("*word?", true));
  1847. expect (s5.matchesWildcard (L"Word*3", true));
  1848. expectEquals (s5.fromFirstOccurrenceOf (String::empty, true, false), s5);
  1849. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  1850. expectEquals (s5.fromFirstOccurrenceOf (L"word2", true, false), s5.substring (5));
  1851. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  1852. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  1853. expectEquals (s5.fromFirstOccurrenceOf (L"Word2", false, true), s5.getLastCharacters (6));
  1854. expectEquals (s5.fromLastOccurrenceOf (String::empty, true, false), s5);
  1855. expectEquals (s5.fromLastOccurrenceOf (L"wordx", true, false), s5);
  1856. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  1857. expectEquals (s5.fromLastOccurrenceOf (L"worD", true, true), s5.getLastCharacters (5));
  1858. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  1859. expectEquals (s5.fromLastOccurrenceOf (L"worD", false, true), s5.getLastCharacters (1));
  1860. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  1861. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  1862. expectEquals (s5.upToFirstOccurrenceOf (L"word2", true, false), s5.substring (0, 10));
  1863. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  1864. expectEquals (s5.upToFirstOccurrenceOf (L"word2", false, false), s5.substring (0, 5));
  1865. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  1866. expectEquals (s5.upToLastOccurrenceOf (String::empty, true, false), s5);
  1867. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  1868. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  1869. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  1870. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  1871. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  1872. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  1873. expectEquals (s5.replace ("word", L"xyz", false), String ("xyz xyz2 xyz3"));
  1874. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  1875. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  1876. expect (s5.replace ("Word", "", true) == " 2 3");
  1877. expectEquals (s5.replace ("Word2", L"xyz", true), String ("word xyz word3"));
  1878. expect (s5.replaceCharacter (L'w', 'x') != s5);
  1879. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  1880. expect (s5.replaceCharacters ("wo", "xy") != s5);
  1881. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo"), s5);
  1882. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  1883. expect (s5.retainCharacters (String::empty).isEmpty());
  1884. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  1885. expectEquals (s5.removeCharacters (String::empty), s5);
  1886. expect (s5.initialSectionContainingOnly ("word") == L"word");
  1887. expect (String ("word").initialSectionContainingOnly ("word") == L"word");
  1888. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  1889. expectEquals (s5.initialSectionNotContaining (String (";[:'/")), s5);
  1890. expect (! s5.isQuotedString());
  1891. expect (s5.quoted().isQuotedString());
  1892. expect (! s5.quoted().unquoted().isQuotedString());
  1893. expect (! String ("x'").isQuotedString());
  1894. expect (String ("'x").isQuotedString());
  1895. String s6 (" \t xyz \t\r\n");
  1896. expectEquals (s6.trim(), String ("xyz"));
  1897. expect (s6.trim().trim() == "xyz");
  1898. expectEquals (s5.trim(), s5);
  1899. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  1900. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  1901. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  1902. expect (s6.trimStart() != s6.trimEnd());
  1903. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  1904. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  1905. }
  1906. {
  1907. beginTest ("UTF conversions");
  1908. TestUTFConversion <CharPointer_UTF32>::test (*this);
  1909. TestUTFConversion <CharPointer_UTF8>::test (*this);
  1910. TestUTFConversion <CharPointer_UTF16>::test (*this);
  1911. }
  1912. {
  1913. beginTest ("StringArray");
  1914. StringArray s;
  1915. for (int i = 5; --i >= 0;)
  1916. s.add (String (i));
  1917. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  1918. s.remove (2);
  1919. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  1920. expectEquals (s.joinIntoString (String::empty), String ("4310"));
  1921. s.clear();
  1922. expectEquals (s.joinIntoString ("x"), String::empty);
  1923. }
  1924. }
  1925. };
  1926. static StringTests stringUnitTests;
  1927. #endif
  1928. END_JUCE_NAMESPACE