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.

2414 lines
82KB

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