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.

2397 lines
83KB

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