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.

2439 lines
84KB

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