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.

2729 lines
96KB

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