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.

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