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.

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