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.

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