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.

2961 lines
106KB

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