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.

2691 lines
94KB

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