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.

2419 lines
82KB

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