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.

2960 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 = reinterpret_cast<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 reinterpret_cast<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 int64 number) { return StringHelpers::operationAddAssign<int64> (*this, number); }
  667. String& String::operator+= (const uint64 number) { return StringHelpers::operationAddAssign<uint64> (*this, number); }
  668. //==============================================================================
  669. JUCE_API String JUCE_CALLTYPE operator+ (const char* s1, const String& s2) { String s (s1); return s += s2; }
  670. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* s1, const String& s2) { String s (s1); return s += s2; }
  671. JUCE_API String JUCE_CALLTYPE operator+ (char s1, const String& s2) { return String::charToString ((juce_wchar) (uint8) s1) + s2; }
  672. JUCE_API String JUCE_CALLTYPE operator+ (wchar_t s1, const String& s2) { return String::charToString (s1) + s2; }
  673. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const String& s2) { return s1 += s2; }
  674. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char* s2) { return s1 += s2; }
  675. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t* s2) { return s1 += s2; }
  676. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const std::string& s2) { return s1 += s2.c_str(); }
  677. JUCE_API String JUCE_CALLTYPE operator+ (String s1, char s2) { return s1 += s2; }
  678. JUCE_API String JUCE_CALLTYPE operator+ (String s1, wchar_t s2) { return s1 += s2; }
  679. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  680. JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar s1, const String& s2) { return String::charToString (s1) + s2; }
  681. JUCE_API String JUCE_CALLTYPE operator+ (String s1, juce_wchar s2) { return s1 += s2; }
  682. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, juce_wchar s2) { return s1 += s2; }
  683. #endif
  684. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, char s2) { return s1 += s2; }
  685. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, wchar_t s2) { return s1 += s2; }
  686. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char* s2) { return s1 += s2; }
  687. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t* s2) { return s1 += s2; }
  688. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const String& s2) { return s1 += s2; }
  689. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, StringRef s2) { return s1 += s2; }
  690. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const std::string& s2) { return s1 += s2.c_str(); }
  691. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, uint8 number) { return s1 += (int) number; }
  692. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, short number) { return s1 += (int) number; }
  693. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, int number) { return s1 += number; }
  694. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, long number) { return s1 += String (number); }
  695. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, unsigned long number) { return s1 += String (number); }
  696. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, int64 number) { return s1 += String (number); }
  697. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, uint64 number) { return s1 += String (number); }
  698. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, float number) { return s1 += String (number); }
  699. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, double number) { return s1 += String (number); }
  700. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  701. {
  702. return operator<< (stream, StringRef (text));
  703. }
  704. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, StringRef text)
  705. {
  706. auto numBytes = CharPointer_UTF8::getBytesRequiredFor (text.text);
  707. #if (JUCE_STRING_UTF_TYPE == 8)
  708. stream.write (text.text.getAddress(), numBytes);
  709. #else
  710. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  711. // if lots of large, persistent strings were to be written to streams).
  712. HeapBlock<char> temp (numBytes + 1);
  713. CharPointer_UTF8 (temp).writeAll (text.text);
  714. stream.write (temp, numBytes);
  715. #endif
  716. return stream;
  717. }
  718. //==============================================================================
  719. int String::indexOfChar (juce_wchar character) const noexcept
  720. {
  721. return text.indexOf (character);
  722. }
  723. int String::indexOfChar (int startIndex, juce_wchar character) const noexcept
  724. {
  725. auto t = text;
  726. for (int i = 0; ! t.isEmpty(); ++i)
  727. {
  728. if (i >= startIndex)
  729. {
  730. if (t.getAndAdvance() == character)
  731. return i;
  732. }
  733. else
  734. {
  735. ++t;
  736. }
  737. }
  738. return -1;
  739. }
  740. int String::lastIndexOfChar (juce_wchar character) const noexcept
  741. {
  742. auto t = text;
  743. int last = -1;
  744. for (int i = 0; ! t.isEmpty(); ++i)
  745. if (t.getAndAdvance() == character)
  746. last = i;
  747. return last;
  748. }
  749. int String::indexOfAnyOf (StringRef charactersToLookFor, int startIndex, bool ignoreCase) const noexcept
  750. {
  751. auto t = text;
  752. for (int i = 0; ! t.isEmpty(); ++i)
  753. {
  754. if (i >= startIndex)
  755. {
  756. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  757. return i;
  758. }
  759. else
  760. {
  761. ++t;
  762. }
  763. }
  764. return -1;
  765. }
  766. int String::indexOf (StringRef other) const noexcept
  767. {
  768. return other.isEmpty() ? 0 : text.indexOf (other.text);
  769. }
  770. int String::indexOfIgnoreCase (StringRef other) const noexcept
  771. {
  772. return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text);
  773. }
  774. int String::indexOf (int startIndex, StringRef other) const noexcept
  775. {
  776. if (other.isEmpty())
  777. return -1;
  778. auto t = text;
  779. for (int i = startIndex; --i >= 0;)
  780. {
  781. if (t.isEmpty())
  782. return -1;
  783. ++t;
  784. }
  785. auto found = t.indexOf (other.text);
  786. return found >= 0 ? found + startIndex : found;
  787. }
  788. int String::indexOfIgnoreCase (const int startIndex, StringRef other) const noexcept
  789. {
  790. if (other.isEmpty())
  791. return -1;
  792. auto t = text;
  793. for (int i = startIndex; --i >= 0;)
  794. {
  795. if (t.isEmpty())
  796. return -1;
  797. ++t;
  798. }
  799. auto found = CharacterFunctions::indexOfIgnoreCase (t, other.text);
  800. return found >= 0 ? found + startIndex : found;
  801. }
  802. int String::lastIndexOf (StringRef other) const noexcept
  803. {
  804. if (other.isNotEmpty())
  805. {
  806. auto len = other.length();
  807. int i = length() - len;
  808. if (i >= 0)
  809. {
  810. for (auto n = text + i; i >= 0; --i)
  811. {
  812. if (n.compareUpTo (other.text, len) == 0)
  813. return i;
  814. --n;
  815. }
  816. }
  817. }
  818. return -1;
  819. }
  820. int String::lastIndexOfIgnoreCase (StringRef other) const noexcept
  821. {
  822. if (other.isNotEmpty())
  823. {
  824. auto len = other.length();
  825. int i = length() - len;
  826. if (i >= 0)
  827. {
  828. for (auto n = text + i; i >= 0; --i)
  829. {
  830. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  831. return i;
  832. --n;
  833. }
  834. }
  835. }
  836. return -1;
  837. }
  838. int String::lastIndexOfAnyOf (StringRef charactersToLookFor, const bool ignoreCase) const noexcept
  839. {
  840. auto t = text;
  841. int last = -1;
  842. for (int i = 0; ! t.isEmpty(); ++i)
  843. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  844. last = i;
  845. return last;
  846. }
  847. bool String::contains (StringRef other) const noexcept
  848. {
  849. return indexOf (other) >= 0;
  850. }
  851. bool String::containsChar (const juce_wchar character) const noexcept
  852. {
  853. return text.indexOf (character) >= 0;
  854. }
  855. bool String::containsIgnoreCase (StringRef t) const noexcept
  856. {
  857. return indexOfIgnoreCase (t) >= 0;
  858. }
  859. int String::indexOfWholeWord (StringRef word) const noexcept
  860. {
  861. if (word.isNotEmpty())
  862. {
  863. auto t = text;
  864. auto wordLen = word.length();
  865. auto end = (int) t.length() - wordLen;
  866. for (int i = 0; i <= end; ++i)
  867. {
  868. if (t.compareUpTo (word.text, wordLen) == 0
  869. && (i == 0 || ! (t - 1).isLetterOrDigit())
  870. && ! (t + wordLen).isLetterOrDigit())
  871. return i;
  872. ++t;
  873. }
  874. }
  875. return -1;
  876. }
  877. int String::indexOfWholeWordIgnoreCase (StringRef word) const noexcept
  878. {
  879. if (word.isNotEmpty())
  880. {
  881. auto t = text;
  882. auto wordLen = word.length();
  883. auto end = (int) t.length() - wordLen;
  884. for (int i = 0; i <= end; ++i)
  885. {
  886. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  887. && (i == 0 || ! (t - 1).isLetterOrDigit())
  888. && ! (t + wordLen).isLetterOrDigit())
  889. return i;
  890. ++t;
  891. }
  892. }
  893. return -1;
  894. }
  895. bool String::containsWholeWord (StringRef wordToLookFor) const noexcept
  896. {
  897. return indexOfWholeWord (wordToLookFor) >= 0;
  898. }
  899. bool String::containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept
  900. {
  901. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  902. }
  903. //==============================================================================
  904. template <typename CharPointer>
  905. struct WildCardMatcher
  906. {
  907. static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  908. {
  909. for (;;)
  910. {
  911. auto wc = wildcard.getAndAdvance();
  912. if (wc == '*')
  913. return wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase);
  914. if (! characterMatches (wc, test.getAndAdvance(), ignoreCase))
  915. return false;
  916. if (wc == 0)
  917. return true;
  918. }
  919. }
  920. static bool characterMatches (const juce_wchar wc, const juce_wchar tc, const bool ignoreCase) noexcept
  921. {
  922. return (wc == tc) || (wc == '?' && tc != 0)
  923. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc));
  924. }
  925. static bool matchesAnywhere (const CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  926. {
  927. for (; ! test.isEmpty(); ++test)
  928. if (matches (wildcard, test, ignoreCase))
  929. return true;
  930. return false;
  931. }
  932. };
  933. bool String::matchesWildcard (StringRef wildcard, const bool ignoreCase) const noexcept
  934. {
  935. return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase);
  936. }
  937. //==============================================================================
  938. String String::repeatedString (StringRef stringToRepeat, int numberOfTimesToRepeat)
  939. {
  940. if (numberOfTimesToRepeat <= 0)
  941. return {};
  942. String result (PreallocationBytes (findByteOffsetOfEnd (stringToRepeat) * (size_t) numberOfTimesToRepeat));
  943. auto n = result.text;
  944. while (--numberOfTimesToRepeat >= 0)
  945. n.writeAll (stringToRepeat.text);
  946. return result;
  947. }
  948. String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  949. {
  950. jassert (padCharacter != 0);
  951. auto extraChars = minimumLength;
  952. auto end = text;
  953. while (! end.isEmpty())
  954. {
  955. --extraChars;
  956. ++end;
  957. }
  958. if (extraChars <= 0 || padCharacter == 0)
  959. return *this;
  960. auto currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  961. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  962. auto n = result.text;
  963. while (--extraChars >= 0)
  964. n.write (padCharacter);
  965. n.writeAll (text);
  966. return result;
  967. }
  968. String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  969. {
  970. jassert (padCharacter != 0);
  971. auto extraChars = minimumLength;
  972. CharPointerType end (text);
  973. while (! end.isEmpty())
  974. {
  975. --extraChars;
  976. ++end;
  977. }
  978. if (extraChars <= 0 || padCharacter == 0)
  979. return *this;
  980. auto currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  981. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  982. auto n = result.text;
  983. n.writeAll (text);
  984. while (--extraChars >= 0)
  985. n.write (padCharacter);
  986. n.writeNull();
  987. return result;
  988. }
  989. //==============================================================================
  990. String String::replaceSection (int index, int numCharsToReplace, StringRef stringToInsert) const
  991. {
  992. if (index < 0)
  993. {
  994. // a negative index to replace from?
  995. jassertfalse;
  996. index = 0;
  997. }
  998. if (numCharsToReplace < 0)
  999. {
  1000. // replacing a negative number of characters?
  1001. numCharsToReplace = 0;
  1002. jassertfalse;
  1003. }
  1004. auto insertPoint = text;
  1005. for (int i = 0; i < index; ++i)
  1006. {
  1007. if (insertPoint.isEmpty())
  1008. {
  1009. // replacing beyond the end of the string?
  1010. jassertfalse;
  1011. return *this + stringToInsert;
  1012. }
  1013. ++insertPoint;
  1014. }
  1015. auto startOfRemainder = insertPoint;
  1016. for (int i = 0; i < numCharsToReplace && ! startOfRemainder.isEmpty(); ++i)
  1017. ++startOfRemainder;
  1018. if (insertPoint == text && startOfRemainder.isEmpty())
  1019. return stringToInsert.text;
  1020. auto initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress());
  1021. auto newStringBytes = findByteOffsetOfEnd (stringToInsert);
  1022. auto remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress());
  1023. auto newTotalBytes = initialBytes + newStringBytes + remainderBytes;
  1024. if (newTotalBytes <= 0)
  1025. return {};
  1026. String result (PreallocationBytes ((size_t) newTotalBytes));
  1027. auto* dest = (char*) result.text.getAddress();
  1028. memcpy (dest, text.getAddress(), initialBytes);
  1029. dest += initialBytes;
  1030. memcpy (dest, stringToInsert.text.getAddress(), newStringBytes);
  1031. dest += newStringBytes;
  1032. memcpy (dest, startOfRemainder.getAddress(), remainderBytes);
  1033. dest += remainderBytes;
  1034. CharPointerType ((CharPointerType::CharType*) dest).writeNull();
  1035. return result;
  1036. }
  1037. String String::replace (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  1038. {
  1039. auto stringToReplaceLen = stringToReplace.length();
  1040. auto stringToInsertLen = stringToInsert.length();
  1041. int i = 0;
  1042. String result (*this);
  1043. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  1044. : result.indexOf (i, stringToReplace))) >= 0)
  1045. {
  1046. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  1047. i += stringToInsertLen;
  1048. }
  1049. return result;
  1050. }
  1051. String String::replaceFirstOccurrenceOf (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  1052. {
  1053. auto stringToReplaceLen = stringToReplace.length();
  1054. auto index = ignoreCase ? indexOfIgnoreCase (stringToReplace)
  1055. : indexOf (stringToReplace);
  1056. if (index >= 0)
  1057. return replaceSection (index, stringToReplaceLen, stringToInsert);
  1058. return *this;
  1059. }
  1060. struct StringCreationHelper
  1061. {
  1062. StringCreationHelper (size_t initialBytes) : allocatedBytes (initialBytes)
  1063. {
  1064. result.preallocateBytes (allocatedBytes);
  1065. dest = result.getCharPointer();
  1066. }
  1067. StringCreationHelper (const String::CharPointerType s)
  1068. : source (s), allocatedBytes (StringHolder::getAllocatedNumBytes (s))
  1069. {
  1070. result.preallocateBytes (allocatedBytes);
  1071. dest = result.getCharPointer();
  1072. }
  1073. void write (juce_wchar c)
  1074. {
  1075. bytesWritten += String::CharPointerType::getBytesRequiredFor (c);
  1076. if (bytesWritten > allocatedBytes)
  1077. {
  1078. allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16);
  1079. auto destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress());
  1080. result.preallocateBytes (allocatedBytes);
  1081. dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset);
  1082. }
  1083. dest.write (c);
  1084. }
  1085. String result;
  1086. String::CharPointerType source { nullptr }, dest { nullptr };
  1087. size_t allocatedBytes, bytesWritten = 0;
  1088. };
  1089. String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  1090. {
  1091. if (! containsChar (charToReplace))
  1092. return *this;
  1093. StringCreationHelper builder (text);
  1094. for (;;)
  1095. {
  1096. auto c = builder.source.getAndAdvance();
  1097. if (c == charToReplace)
  1098. c = charToInsert;
  1099. builder.write (c);
  1100. if (c == 0)
  1101. break;
  1102. }
  1103. return std::move (builder.result);
  1104. }
  1105. String String::replaceCharacters (StringRef charactersToReplace, StringRef charactersToInsertInstead) const
  1106. {
  1107. // Each character in the first string must have a matching one in the
  1108. // second, so the two strings must be the same length.
  1109. jassert (charactersToReplace.length() == charactersToInsertInstead.length());
  1110. StringCreationHelper builder (text);
  1111. for (;;)
  1112. {
  1113. auto c = builder.source.getAndAdvance();
  1114. auto index = charactersToReplace.text.indexOf (c);
  1115. if (index >= 0)
  1116. c = charactersToInsertInstead [index];
  1117. builder.write (c);
  1118. if (c == 0)
  1119. break;
  1120. }
  1121. return std::move (builder.result);
  1122. }
  1123. //==============================================================================
  1124. bool String::startsWith (StringRef other) const noexcept
  1125. {
  1126. return text.compareUpTo (other.text, other.length()) == 0;
  1127. }
  1128. bool String::startsWithIgnoreCase (StringRef other) const noexcept
  1129. {
  1130. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  1131. }
  1132. bool String::startsWithChar (const juce_wchar character) const noexcept
  1133. {
  1134. jassert (character != 0); // strings can't contain a null character!
  1135. return *text == character;
  1136. }
  1137. bool String::endsWithChar (const juce_wchar character) const noexcept
  1138. {
  1139. jassert (character != 0); // strings can't contain a null character!
  1140. if (text.isEmpty())
  1141. return false;
  1142. auto t = text.findTerminatingNull();
  1143. return *--t == character;
  1144. }
  1145. bool String::endsWith (StringRef other) const noexcept
  1146. {
  1147. auto end = text.findTerminatingNull();
  1148. auto otherEnd = other.text.findTerminatingNull();
  1149. while (end > text && otherEnd > other.text)
  1150. {
  1151. --end;
  1152. --otherEnd;
  1153. if (*end != *otherEnd)
  1154. return false;
  1155. }
  1156. return otherEnd == other.text;
  1157. }
  1158. bool String::endsWithIgnoreCase (StringRef other) const noexcept
  1159. {
  1160. auto end = text.findTerminatingNull();
  1161. auto otherEnd = other.text.findTerminatingNull();
  1162. while (end > text && otherEnd > other.text)
  1163. {
  1164. --end;
  1165. --otherEnd;
  1166. if (end.toLowerCase() != otherEnd.toLowerCase())
  1167. return false;
  1168. }
  1169. return otherEnd == other.text;
  1170. }
  1171. //==============================================================================
  1172. String String::toUpperCase() const
  1173. {
  1174. StringCreationHelper builder (text);
  1175. for (;;)
  1176. {
  1177. auto c = builder.source.toUpperCase();
  1178. builder.write (c);
  1179. if (c == 0)
  1180. break;
  1181. ++(builder.source);
  1182. }
  1183. return std::move (builder.result);
  1184. }
  1185. String String::toLowerCase() const
  1186. {
  1187. StringCreationHelper builder (text);
  1188. for (;;)
  1189. {
  1190. auto c = builder.source.toLowerCase();
  1191. builder.write (c);
  1192. if (c == 0)
  1193. break;
  1194. ++(builder.source);
  1195. }
  1196. return std::move (builder.result);
  1197. }
  1198. //==============================================================================
  1199. juce_wchar String::getLastCharacter() const noexcept
  1200. {
  1201. return isEmpty() ? juce_wchar() : text [length() - 1];
  1202. }
  1203. String String::substring (int start, const int end) const
  1204. {
  1205. if (start < 0)
  1206. start = 0;
  1207. if (end <= start)
  1208. return {};
  1209. int i = 0;
  1210. auto t1 = text;
  1211. while (i < start)
  1212. {
  1213. if (t1.isEmpty())
  1214. return {};
  1215. ++i;
  1216. ++t1;
  1217. }
  1218. auto t2 = t1;
  1219. while (i < end)
  1220. {
  1221. if (t2.isEmpty())
  1222. {
  1223. if (start == 0)
  1224. return *this;
  1225. break;
  1226. }
  1227. ++i;
  1228. ++t2;
  1229. }
  1230. return String (t1, t2);
  1231. }
  1232. String String::substring (int start) const
  1233. {
  1234. if (start <= 0)
  1235. return *this;
  1236. auto t = text;
  1237. while (--start >= 0)
  1238. {
  1239. if (t.isEmpty())
  1240. return {};
  1241. ++t;
  1242. }
  1243. return String (t);
  1244. }
  1245. String String::dropLastCharacters (const int numberToDrop) const
  1246. {
  1247. return String (text, (size_t) jmax (0, length() - numberToDrop));
  1248. }
  1249. String String::getLastCharacters (const int numCharacters) const
  1250. {
  1251. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  1252. }
  1253. String String::fromFirstOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1254. {
  1255. auto i = ignoreCase ? indexOfIgnoreCase (sub)
  1256. : indexOf (sub);
  1257. if (i < 0)
  1258. return {};
  1259. return substring (includeSubString ? i : i + sub.length());
  1260. }
  1261. String String::fromLastOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1262. {
  1263. auto i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1264. : lastIndexOf (sub);
  1265. if (i < 0)
  1266. return *this;
  1267. return substring (includeSubString ? i : i + sub.length());
  1268. }
  1269. String String::upToFirstOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1270. {
  1271. auto i = ignoreCase ? indexOfIgnoreCase (sub)
  1272. : indexOf (sub);
  1273. if (i < 0)
  1274. return *this;
  1275. return substring (0, includeSubString ? i + sub.length() : i);
  1276. }
  1277. String String::upToLastOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1278. {
  1279. auto i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1280. : lastIndexOf (sub);
  1281. if (i < 0)
  1282. return *this;
  1283. return substring (0, includeSubString ? i + sub.length() : i);
  1284. }
  1285. static bool isQuoteCharacter (juce_wchar c) noexcept
  1286. {
  1287. return c == '"' || c == '\'';
  1288. }
  1289. bool String::isQuotedString() const
  1290. {
  1291. return isQuoteCharacter (*text.findEndOfWhitespace());
  1292. }
  1293. String String::unquoted() const
  1294. {
  1295. if (! isQuoteCharacter (*text))
  1296. return *this;
  1297. auto len = length();
  1298. return substring (1, len - (isQuoteCharacter (text[len - 1]) ? 1 : 0));
  1299. }
  1300. String String::quoted (juce_wchar quoteCharacter) const
  1301. {
  1302. if (isEmpty())
  1303. return charToString (quoteCharacter) + quoteCharacter;
  1304. String t (*this);
  1305. if (! t.startsWithChar (quoteCharacter))
  1306. t = charToString (quoteCharacter) + t;
  1307. if (! t.endsWithChar (quoteCharacter))
  1308. t += quoteCharacter;
  1309. return t;
  1310. }
  1311. //==============================================================================
  1312. static String::CharPointerType findTrimmedEnd (const String::CharPointerType start,
  1313. String::CharPointerType end)
  1314. {
  1315. while (end > start)
  1316. {
  1317. if (! (--end).isWhitespace())
  1318. {
  1319. ++end;
  1320. break;
  1321. }
  1322. }
  1323. return end;
  1324. }
  1325. String String::trim() const
  1326. {
  1327. if (isNotEmpty())
  1328. {
  1329. auto start = text.findEndOfWhitespace();
  1330. auto end = start.findTerminatingNull();
  1331. auto trimmedEnd = findTrimmedEnd (start, end);
  1332. if (trimmedEnd <= start)
  1333. return {};
  1334. if (text < start || trimmedEnd < end)
  1335. return String (start, trimmedEnd);
  1336. }
  1337. return *this;
  1338. }
  1339. String String::trimStart() const
  1340. {
  1341. if (isNotEmpty())
  1342. {
  1343. auto t = text.findEndOfWhitespace();
  1344. if (t != text)
  1345. return String (t);
  1346. }
  1347. return *this;
  1348. }
  1349. String String::trimEnd() const
  1350. {
  1351. if (isNotEmpty())
  1352. {
  1353. auto end = text.findTerminatingNull();
  1354. auto trimmedEnd = findTrimmedEnd (text, end);
  1355. if (trimmedEnd < end)
  1356. return String (text, trimmedEnd);
  1357. }
  1358. return *this;
  1359. }
  1360. String String::trimCharactersAtStart (StringRef charactersToTrim) const
  1361. {
  1362. auto t = text;
  1363. while (charactersToTrim.text.indexOf (*t) >= 0)
  1364. ++t;
  1365. return t == text ? *this : String (t);
  1366. }
  1367. String String::trimCharactersAtEnd (StringRef charactersToTrim) const
  1368. {
  1369. if (isNotEmpty())
  1370. {
  1371. auto end = text.findTerminatingNull();
  1372. auto trimmedEnd = end;
  1373. while (trimmedEnd > text)
  1374. {
  1375. if (charactersToTrim.text.indexOf (*--trimmedEnd) < 0)
  1376. {
  1377. ++trimmedEnd;
  1378. break;
  1379. }
  1380. }
  1381. if (trimmedEnd < end)
  1382. return String (text, trimmedEnd);
  1383. }
  1384. return *this;
  1385. }
  1386. //==============================================================================
  1387. String String::retainCharacters (StringRef charactersToRetain) const
  1388. {
  1389. if (isEmpty())
  1390. return {};
  1391. StringCreationHelper builder (text);
  1392. for (;;)
  1393. {
  1394. auto c = builder.source.getAndAdvance();
  1395. if (charactersToRetain.text.indexOf (c) >= 0)
  1396. builder.write (c);
  1397. if (c == 0)
  1398. break;
  1399. }
  1400. builder.write (0);
  1401. return std::move (builder.result);
  1402. }
  1403. String String::removeCharacters (StringRef charactersToRemove) const
  1404. {
  1405. if (isEmpty())
  1406. return {};
  1407. StringCreationHelper builder (text);
  1408. for (;;)
  1409. {
  1410. auto c = builder.source.getAndAdvance();
  1411. if (charactersToRemove.text.indexOf (c) < 0)
  1412. builder.write (c);
  1413. if (c == 0)
  1414. break;
  1415. }
  1416. return std::move (builder.result);
  1417. }
  1418. String String::initialSectionContainingOnly (StringRef permittedCharacters) const
  1419. {
  1420. for (auto t = text; ! t.isEmpty(); ++t)
  1421. if (permittedCharacters.text.indexOf (*t) < 0)
  1422. return String (text, t);
  1423. return *this;
  1424. }
  1425. String String::initialSectionNotContaining (StringRef charactersToStopAt) const
  1426. {
  1427. for (auto t = text; ! t.isEmpty(); ++t)
  1428. if (charactersToStopAt.text.indexOf (*t) >= 0)
  1429. return String (text, t);
  1430. return *this;
  1431. }
  1432. bool String::containsOnly (StringRef chars) const noexcept
  1433. {
  1434. for (auto t = text; ! t.isEmpty();)
  1435. if (chars.text.indexOf (t.getAndAdvance()) < 0)
  1436. return false;
  1437. return true;
  1438. }
  1439. bool String::containsAnyOf (StringRef chars) const noexcept
  1440. {
  1441. for (auto t = text; ! t.isEmpty();)
  1442. if (chars.text.indexOf (t.getAndAdvance()) >= 0)
  1443. return true;
  1444. return false;
  1445. }
  1446. bool String::containsNonWhitespaceChars() const noexcept
  1447. {
  1448. for (auto t = text; ! t.isEmpty(); ++t)
  1449. if (! t.isWhitespace())
  1450. return true;
  1451. return false;
  1452. }
  1453. String String::formattedRaw (const char* pf, ...)
  1454. {
  1455. size_t bufferSize = 256;
  1456. for (;;)
  1457. {
  1458. va_list args;
  1459. va_start (args, pf);
  1460. #if JUCE_WINDOWS
  1461. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  1462. #endif
  1463. #if JUCE_ANDROID
  1464. HeapBlock<char> temp (bufferSize);
  1465. int num = (int) vsnprintf (temp.get(), bufferSize - 1, pf, args);
  1466. if (num >= static_cast<int> (bufferSize))
  1467. num = -1;
  1468. #else
  1469. String wideCharVersion (pf);
  1470. HeapBlock<wchar_t> temp (bufferSize);
  1471. const int num = (int)
  1472. #if JUCE_WINDOWS
  1473. _vsnwprintf
  1474. #else
  1475. vswprintf
  1476. #endif
  1477. (temp.get(), bufferSize - 1, wideCharVersion.toWideCharPointer(), args);
  1478. #endif
  1479. #if JUCE_WINDOWS
  1480. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  1481. #endif
  1482. va_end (args);
  1483. if (num > 0)
  1484. return String (temp.get());
  1485. bufferSize += 256;
  1486. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  1487. break; // returns -1 because of an error rather than because it needs more space.
  1488. }
  1489. return {};
  1490. }
  1491. //==============================================================================
  1492. int String::getIntValue() const noexcept { return text.getIntValue32(); }
  1493. int64 String::getLargeIntValue() const noexcept { return text.getIntValue64(); }
  1494. float String::getFloatValue() const noexcept { return (float) getDoubleValue(); }
  1495. double String::getDoubleValue() const noexcept { return text.getDoubleValue(); }
  1496. int String::getTrailingIntValue() const noexcept
  1497. {
  1498. int n = 0;
  1499. int mult = 1;
  1500. auto t = text.findTerminatingNull();
  1501. while (--t >= text)
  1502. {
  1503. if (! t.isDigit())
  1504. {
  1505. if (*t == '-')
  1506. n = -n;
  1507. break;
  1508. }
  1509. n += (int) (((juce_wchar) mult) * (*t - '0'));
  1510. mult *= 10;
  1511. }
  1512. return n;
  1513. }
  1514. static const char hexDigits[] = "0123456789abcdef";
  1515. template <typename Type>
  1516. static String hexToString (Type v)
  1517. {
  1518. String::CharPointerType::CharType buffer[32];
  1519. auto* end = buffer + numElementsInArray (buffer) - 1;
  1520. auto* t = end;
  1521. *t = 0;
  1522. do
  1523. {
  1524. *--t = hexDigits [(int) (v & 15)];
  1525. v = static_cast<Type> (v >> 4);
  1526. } while (v != 0);
  1527. return String (String::CharPointerType (t),
  1528. String::CharPointerType (end));
  1529. }
  1530. String String::createHex (uint8 n) { return hexToString (n); }
  1531. String String::createHex (uint16 n) { return hexToString (n); }
  1532. String String::createHex (uint32 n) { return hexToString (n); }
  1533. String String::createHex (uint64 n) { return hexToString (n); }
  1534. String String::toHexString (const void* const d, const int size, const int groupSize)
  1535. {
  1536. if (size <= 0)
  1537. return {};
  1538. int numChars = (size * 2) + 2;
  1539. if (groupSize > 0)
  1540. numChars += size / groupSize;
  1541. String s (PreallocationBytes ((size_t) numChars * sizeof (CharPointerType::CharType)));
  1542. auto* data = static_cast<const unsigned char*> (d);
  1543. auto dest = s.text;
  1544. for (int i = 0; i < size; ++i)
  1545. {
  1546. const unsigned char nextByte = *data++;
  1547. dest.write ((juce_wchar) hexDigits [nextByte >> 4]);
  1548. dest.write ((juce_wchar) hexDigits [nextByte & 0xf]);
  1549. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  1550. dest.write ((juce_wchar) ' ');
  1551. }
  1552. dest.writeNull();
  1553. return s;
  1554. }
  1555. int String::getHexValue32() const noexcept { return CharacterFunctions::HexParser<int> ::parse (text); }
  1556. int64 String::getHexValue64() const noexcept { return CharacterFunctions::HexParser<int64>::parse (text); }
  1557. //==============================================================================
  1558. static String getStringFromWindows1252Codepage (const char* data, size_t num)
  1559. {
  1560. HeapBlock<juce_wchar> unicode (num + 1);
  1561. for (size_t i = 0; i < num; ++i)
  1562. unicode[i] = CharacterFunctions::getUnicodeCharFromWindows1252Codepage ((uint8) data[i]);
  1563. unicode[num] = 0;
  1564. return CharPointer_UTF32 (unicode);
  1565. }
  1566. String String::createStringFromData (const void* const unknownData, int size)
  1567. {
  1568. auto* data = static_cast<const uint8*> (unknownData);
  1569. if (size <= 0 || data == nullptr)
  1570. return {};
  1571. if (size == 1)
  1572. return charToString ((juce_wchar) data[0]);
  1573. if (CharPointer_UTF16::isByteOrderMarkBigEndian (data)
  1574. || CharPointer_UTF16::isByteOrderMarkLittleEndian (data))
  1575. {
  1576. const int numChars = size / 2 - 1;
  1577. StringCreationHelper builder ((size_t) numChars);
  1578. auto src = reinterpret_cast<const uint16*> (data + 2);
  1579. if (CharPointer_UTF16::isByteOrderMarkBigEndian (data))
  1580. {
  1581. for (int i = 0; i < numChars; ++i)
  1582. builder.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  1583. }
  1584. else
  1585. {
  1586. for (int i = 0; i < numChars; ++i)
  1587. builder.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  1588. }
  1589. builder.write (0);
  1590. return std::move (builder.result);
  1591. }
  1592. auto* start = (const char*) data;
  1593. if (size >= 3 && CharPointer_UTF8::isByteOrderMark (data))
  1594. {
  1595. start += 3;
  1596. size -= 3;
  1597. }
  1598. if (CharPointer_UTF8::isValidString (start, size))
  1599. return String (CharPointer_UTF8 (start),
  1600. CharPointer_UTF8 (start + size));
  1601. return getStringFromWindows1252Codepage (start, (size_t) size);
  1602. }
  1603. //==============================================================================
  1604. static const juce_wchar emptyChar = 0;
  1605. template <class CharPointerType_Src, class CharPointerType_Dest>
  1606. struct StringEncodingConverter
  1607. {
  1608. static CharPointerType_Dest convert (const String& s)
  1609. {
  1610. auto& source = const_cast<String&> (s);
  1611. using DestChar = typename CharPointerType_Dest::CharType;
  1612. if (source.isEmpty())
  1613. return CharPointerType_Dest (reinterpret_cast<const DestChar*> (&emptyChar));
  1614. CharPointerType_Src text (source.getCharPointer());
  1615. auto extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text) + sizeof (typename CharPointerType_Dest::CharType);
  1616. auto endOffset = (text.sizeInBytes() + 3) & ~3u; // the new string must be word-aligned or many Windows
  1617. // functions will fail to read it correctly!
  1618. source.preallocateBytes (endOffset + extraBytesNeeded);
  1619. text = source.getCharPointer();
  1620. void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset);
  1621. const CharPointerType_Dest extraSpace (static_cast<DestChar*> (newSpace));
  1622. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  1623. auto bytesToClear = (size_t) jmin ((int) extraBytesNeeded, 4);
  1624. zeromem (addBytesToPointer (newSpace, extraBytesNeeded - bytesToClear), bytesToClear);
  1625. #endif
  1626. CharPointerType_Dest (extraSpace).writeAll (text);
  1627. return extraSpace;
  1628. }
  1629. };
  1630. template <>
  1631. struct StringEncodingConverter<CharPointer_UTF8, CharPointer_UTF8>
  1632. {
  1633. static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 (reinterpret_cast<CharPointer_UTF8::CharType*> (source.getCharPointer().getAddress())); }
  1634. };
  1635. template <>
  1636. struct StringEncodingConverter<CharPointer_UTF16, CharPointer_UTF16>
  1637. {
  1638. static CharPointer_UTF16 convert (const String& source) noexcept { return CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (source.getCharPointer().getAddress())); }
  1639. };
  1640. template <>
  1641. struct StringEncodingConverter<CharPointer_UTF32, CharPointer_UTF32>
  1642. {
  1643. static CharPointer_UTF32 convert (const String& source) noexcept { return CharPointer_UTF32 (reinterpret_cast<CharPointer_UTF32::CharType*> (source.getCharPointer().getAddress())); }
  1644. };
  1645. CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF8 >::convert (*this); }
  1646. CharPointer_UTF16 String::toUTF16() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF16>::convert (*this); }
  1647. CharPointer_UTF32 String::toUTF32() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF32>::convert (*this); }
  1648. const char* String::toRawUTF8() const
  1649. {
  1650. return toUTF8().getAddress();
  1651. }
  1652. const wchar_t* String::toWideCharPointer() const
  1653. {
  1654. return StringEncodingConverter<CharPointerType, CharPointer_wchar_t>::convert (*this).getAddress();
  1655. }
  1656. std::string String::toStdString() const
  1657. {
  1658. return std::string (toRawUTF8());
  1659. }
  1660. //==============================================================================
  1661. template <class CharPointerType_Src, class CharPointerType_Dest>
  1662. struct StringCopier
  1663. {
  1664. static size_t copyToBuffer (const CharPointerType_Src source, typename CharPointerType_Dest::CharType* const buffer, const size_t maxBufferSizeBytes)
  1665. {
  1666. jassert (((ssize_t) maxBufferSizeBytes) >= 0); // keep this value positive!
  1667. if (buffer == nullptr)
  1668. return CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType);
  1669. return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes);
  1670. }
  1671. };
  1672. size_t String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1673. {
  1674. return StringCopier<CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1675. }
  1676. size_t String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1677. {
  1678. return StringCopier<CharPointerType, CharPointer_UTF16>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1679. }
  1680. size_t String::copyToUTF32 (CharPointer_UTF32::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1681. {
  1682. return StringCopier<CharPointerType, CharPointer_UTF32>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1683. }
  1684. //==============================================================================
  1685. size_t String::getNumBytesAsUTF8() const noexcept
  1686. {
  1687. return CharPointer_UTF8::getBytesRequiredFor (text);
  1688. }
  1689. String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  1690. {
  1691. if (buffer != nullptr)
  1692. {
  1693. if (bufferSizeBytes < 0)
  1694. return String (CharPointer_UTF8 (buffer));
  1695. if (bufferSizeBytes > 0)
  1696. {
  1697. jassert (CharPointer_UTF8::isValidString (buffer, bufferSizeBytes));
  1698. return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes));
  1699. }
  1700. }
  1701. return {};
  1702. }
  1703. JUCE_END_IGNORE_WARNINGS_MSVC
  1704. //==============================================================================
  1705. StringRef::StringRef() noexcept : text ((const String::CharPointerType::CharType*) "\0\0\0")
  1706. {
  1707. }
  1708. StringRef::StringRef (const char* stringLiteral) noexcept
  1709. #if JUCE_STRING_UTF_TYPE != 8
  1710. : text (nullptr), stringCopy (stringLiteral)
  1711. #else
  1712. : text (stringLiteral)
  1713. #endif
  1714. {
  1715. #if JUCE_STRING_UTF_TYPE != 8
  1716. text = stringCopy.getCharPointer();
  1717. #endif
  1718. jassert (stringLiteral != nullptr); // This must be a valid string literal, not a null pointer!!
  1719. #if JUCE_NATIVE_WCHAR_IS_UTF8
  1720. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  1721. that contains values greater than 127. These can NOT be correctly converted to unicode
  1722. because there's no way for the String class to know what encoding was used to
  1723. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  1724. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  1725. string to the StringRef class - so for example if your source data is actually UTF-8,
  1726. you'd call StringRef (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  1727. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  1728. you use UTF-8 with escape characters in your source code to represent extended characters,
  1729. because there's no other way to represent these strings in a way that isn't dependent on
  1730. the compiler, source code editor and platform.
  1731. */
  1732. jassert (CharPointer_ASCII::isValidString (stringLiteral, std::numeric_limits<int>::max()));
  1733. #endif
  1734. }
  1735. StringRef::StringRef (String::CharPointerType stringLiteral) noexcept : text (stringLiteral)
  1736. {
  1737. jassert (stringLiteral.getAddress() != nullptr); // This must be a valid string literal, not a null pointer!!
  1738. }
  1739. StringRef::StringRef (const String& string) noexcept : text (string.getCharPointer()) {}
  1740. StringRef::StringRef (const std::string& string) : StringRef (string.c_str()) {}
  1741. //==============================================================================
  1742. static String reduceLengthOfFloatString (const String& input)
  1743. {
  1744. const auto start = input.getCharPointer();
  1745. const auto end = start + (int) input.length();
  1746. auto trimStart = end;
  1747. auto trimEnd = trimStart;
  1748. auto exponentTrimStart = end;
  1749. auto exponentTrimEnd = exponentTrimStart;
  1750. decltype (*start) currentChar = '\0';
  1751. for (auto c = end - 1; c > start; --c)
  1752. {
  1753. currentChar = *c;
  1754. if (currentChar == '0' && c + 1 == trimStart)
  1755. {
  1756. --trimStart;
  1757. }
  1758. else if (currentChar == '.')
  1759. {
  1760. if (trimStart == c + 1 && trimStart != end && *trimStart == '0')
  1761. ++trimStart;
  1762. break;
  1763. }
  1764. else if (currentChar == 'e' || currentChar == 'E')
  1765. {
  1766. auto cNext = c + 1;
  1767. if (cNext != end)
  1768. {
  1769. if (*cNext == '-')
  1770. ++cNext;
  1771. exponentTrimStart = cNext;
  1772. if (cNext != end && *cNext == '+')
  1773. ++cNext;
  1774. exponentTrimEnd = cNext;
  1775. }
  1776. while (cNext != end && *cNext++ == '0')
  1777. exponentTrimEnd = cNext;
  1778. if (exponentTrimEnd == end)
  1779. exponentTrimStart = c;
  1780. trimStart = c;
  1781. trimEnd = trimStart;
  1782. }
  1783. }
  1784. if ((trimStart != trimEnd && currentChar == '.') || exponentTrimStart != exponentTrimEnd)
  1785. {
  1786. if (trimStart == trimEnd)
  1787. return String (start, exponentTrimStart) + String (exponentTrimEnd, end);
  1788. if (exponentTrimStart == exponentTrimEnd)
  1789. return String (start, trimStart) + String (trimEnd, end);
  1790. if (trimEnd == exponentTrimStart)
  1791. return String (start, trimStart) + String (exponentTrimEnd, end);
  1792. return String (start, trimStart) + String (trimEnd, exponentTrimStart) + String (exponentTrimEnd, end);
  1793. }
  1794. return input;
  1795. }
  1796. static String serialiseDouble (double input)
  1797. {
  1798. auto absInput = std::abs (input);
  1799. if (absInput >= 1.0e6 || absInput <= 1.0e-5)
  1800. return reduceLengthOfFloatString ({ input, 15, true });
  1801. int intInput = (int) input;
  1802. if ((double) intInput == input)
  1803. return { input, 1 };
  1804. auto numberOfDecimalPlaces = [absInput]
  1805. {
  1806. if (absInput < 1.0)
  1807. {
  1808. if (absInput >= 1.0e-3)
  1809. {
  1810. if (absInput >= 1.0e-1) return 16;
  1811. if (absInput >= 1.0e-2) return 17;
  1812. return 18;
  1813. }
  1814. if (absInput >= 1.0e-4) return 19;
  1815. return 20;
  1816. }
  1817. if (absInput < 1.0e3)
  1818. {
  1819. if (absInput < 1.0e1) return 15;
  1820. if (absInput < 1.0e2) return 14;
  1821. return 13;
  1822. }
  1823. if (absInput < 1.0e4) return 12;
  1824. if (absInput < 1.0e5) return 11;
  1825. return 10;
  1826. }();
  1827. return reduceLengthOfFloatString (String (input, numberOfDecimalPlaces));
  1828. }
  1829. //==============================================================================
  1830. //==============================================================================
  1831. #if JUCE_UNIT_TESTS
  1832. #define STRINGIFY2(X) #X
  1833. #define STRINGIFY(X) STRINGIFY2(X)
  1834. class StringTests : public UnitTest
  1835. {
  1836. public:
  1837. StringTests()
  1838. : UnitTest ("String class", UnitTestCategories::text)
  1839. {}
  1840. template <class CharPointerType>
  1841. struct TestUTFConversion
  1842. {
  1843. static void test (UnitTest& test, Random& r)
  1844. {
  1845. String s (createRandomWideCharString (r));
  1846. typename CharPointerType::CharType buffer [300];
  1847. memset (buffer, 0xff, sizeof (buffer));
  1848. CharPointerType (buffer).writeAll (s.toUTF32());
  1849. test.expectEquals (String (CharPointerType (buffer)), s);
  1850. memset (buffer, 0xff, sizeof (buffer));
  1851. CharPointerType (buffer).writeAll (s.toUTF16());
  1852. test.expectEquals (String (CharPointerType (buffer)), s);
  1853. memset (buffer, 0xff, sizeof (buffer));
  1854. CharPointerType (buffer).writeAll (s.toUTF8());
  1855. test.expectEquals (String (CharPointerType (buffer)), s);
  1856. test.expect (CharPointerType::isValidString (buffer, (int) strlen ((const char*) buffer)));
  1857. }
  1858. };
  1859. static String createRandomWideCharString (Random& r)
  1860. {
  1861. juce_wchar buffer[50] = { 0 };
  1862. for (int i = 0; i < numElementsInArray (buffer) - 1; ++i)
  1863. {
  1864. if (r.nextBool())
  1865. {
  1866. do
  1867. {
  1868. buffer[i] = (juce_wchar) (1 + r.nextInt (0x10ffff - 1));
  1869. }
  1870. while (! CharPointer_UTF16::canRepresent (buffer[i]));
  1871. }
  1872. else
  1873. buffer[i] = (juce_wchar) (1 + r.nextInt (0xff));
  1874. }
  1875. return CharPointer_UTF32 (buffer);
  1876. }
  1877. void runTest() override
  1878. {
  1879. Random r = getRandom();
  1880. {
  1881. beginTest ("Basics");
  1882. expect (String().length() == 0);
  1883. expect (String() == String());
  1884. String s1, s2 ("abcd");
  1885. expect (s1.isEmpty() && ! s1.isNotEmpty());
  1886. expect (s2.isNotEmpty() && ! s2.isEmpty());
  1887. expect (s2.length() == 4);
  1888. s1 = "abcd";
  1889. expect (s2 == s1 && s1 == s2);
  1890. expect (s1 == "abcd" && s1 == L"abcd");
  1891. expect (String ("abcd") == String (L"abcd"));
  1892. expect (String ("abcdefg", 4) == L"abcd");
  1893. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  1894. expect (String::charToString ('x') == "x");
  1895. expect (String::charToString (0) == String());
  1896. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  1897. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  1898. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  1899. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  1900. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  1901. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  1902. expectEquals (s1.indexOf (String()), 0);
  1903. expectEquals (s1.indexOfIgnoreCase (String()), 0);
  1904. expect (s1.startsWith (String()) && s1.endsWith (String()) && s1.contains (String()));
  1905. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  1906. expect (s1.containsChar ('a'));
  1907. expect (! s1.containsChar ('x'));
  1908. expect (! s1.containsChar (0));
  1909. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  1910. }
  1911. {
  1912. beginTest ("Operations");
  1913. String s ("012345678");
  1914. expect (s.hashCode() != 0);
  1915. expect (s.hashCode64() != 0);
  1916. expect (s.hashCode() != (s + s).hashCode());
  1917. expect (s.hashCode64() != (s + s).hashCode64());
  1918. expect (s.compare (String ("012345678")) == 0);
  1919. expect (s.compare (String ("012345679")) < 0);
  1920. expect (s.compare (String ("012345676")) > 0);
  1921. expect (String("a").compareNatural ("A") == 0);
  1922. expect (String("A").compareNatural ("B") < 0);
  1923. expect (String("a").compareNatural ("B") < 0);
  1924. expect (String("10").compareNatural ("2") > 0);
  1925. expect (String("Abc 10").compareNatural ("aBC 2") > 0);
  1926. expect (String("Abc 1").compareNatural ("aBC 2") < 0);
  1927. expect (s.substring (2, 3) == String::charToString (s[2]));
  1928. expect (s.substring (0, 1) == String::charToString (s[0]));
  1929. expect (s.getLastCharacter() == s [s.length() - 1]);
  1930. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  1931. expect (s.substring (0, 3) == L"012");
  1932. expect (s.substring (0, 100) == s);
  1933. expect (s.substring (-1, 100) == s);
  1934. expect (s.substring (3) == "345678");
  1935. expect (s.indexOf (String (L"45")) == 4);
  1936. expect (String ("444445").indexOf ("45") == 4);
  1937. expect (String ("444445").lastIndexOfChar ('4') == 4);
  1938. expect (String ("45454545x").lastIndexOf (String (L"45")) == 6);
  1939. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  1940. expect (String ("45454545x").lastIndexOfAnyOf (String (L"456x")) == 8);
  1941. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("aB") == 6);
  1942. expect (s.indexOfChar (L'4') == 4);
  1943. expect (s + s == "012345678012345678");
  1944. expect (s.startsWith (s));
  1945. expect (s.startsWith (s.substring (0, 4)));
  1946. expect (s.startsWith (s.dropLastCharacters (4)));
  1947. expect (s.endsWith (s.substring (5)));
  1948. expect (s.endsWith (s));
  1949. expect (s.contains (s.substring (3, 6)));
  1950. expect (s.contains (s.substring (3)));
  1951. expect (s.startsWithChar (s[0]));
  1952. expect (s.endsWithChar (s.getLastCharacter()));
  1953. expect (s [s.length()] == 0);
  1954. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  1955. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  1956. expect (String (StringRef ("abc")) == "abc");
  1957. expect (String (StringRef ("abc")) == StringRef ("abc"));
  1958. expect (String ("abc") + StringRef ("def") == "abcdef");
  1959. String s2 ("123");
  1960. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  1961. s2 += "xyz";
  1962. expect (s2 == "1234567890xyz");
  1963. s2 += (int) 123;
  1964. expect (s2 == "1234567890xyz123");
  1965. s2 += (int64) 123;
  1966. expect (s2 == "1234567890xyz123123");
  1967. s2 << StringRef ("def");
  1968. expect (s2 == "1234567890xyz123123def");
  1969. // int16
  1970. {
  1971. String numStr (std::numeric_limits<int16>::max());
  1972. expect (numStr == "32767");
  1973. }
  1974. {
  1975. String numStr (std::numeric_limits<int16>::min());
  1976. expect (numStr == "-32768");
  1977. }
  1978. {
  1979. String numStr;
  1980. numStr << std::numeric_limits<int16>::max();
  1981. expect (numStr == "32767");
  1982. }
  1983. {
  1984. String numStr;
  1985. numStr << std::numeric_limits<int16>::min();
  1986. expect (numStr == "-32768");
  1987. }
  1988. // int32
  1989. {
  1990. String numStr (std::numeric_limits<int32>::max());
  1991. expect (numStr == "2147483647");
  1992. }
  1993. {
  1994. String numStr (std::numeric_limits<int32>::min());
  1995. expect (numStr == "-2147483648");
  1996. }
  1997. {
  1998. String numStr;
  1999. numStr << std::numeric_limits<int32>::max();
  2000. expect (numStr == "2147483647");
  2001. }
  2002. {
  2003. String numStr;
  2004. numStr << std::numeric_limits<int32>::min();
  2005. expect (numStr == "-2147483648");
  2006. }
  2007. // uint32
  2008. {
  2009. String numStr (std::numeric_limits<uint32>::max());
  2010. expect (numStr == "4294967295");
  2011. }
  2012. {
  2013. String numStr (std::numeric_limits<uint32>::min());
  2014. expect (numStr == "0");
  2015. }
  2016. // int64
  2017. {
  2018. String numStr (std::numeric_limits<int64>::max());
  2019. expect (numStr == "9223372036854775807");
  2020. }
  2021. {
  2022. String numStr (std::numeric_limits<int64>::min());
  2023. expect (numStr == "-9223372036854775808");
  2024. }
  2025. {
  2026. String numStr;
  2027. numStr << std::numeric_limits<int64>::max();
  2028. expect (numStr == "9223372036854775807");
  2029. }
  2030. {
  2031. String numStr;
  2032. numStr << std::numeric_limits<int64>::min();
  2033. expect (numStr == "-9223372036854775808");
  2034. }
  2035. // uint64
  2036. {
  2037. String numStr (std::numeric_limits<uint64>::max());
  2038. expect (numStr == "18446744073709551615");
  2039. }
  2040. {
  2041. String numStr (std::numeric_limits<uint64>::min());
  2042. expect (numStr == "0");
  2043. }
  2044. {
  2045. String numStr;
  2046. numStr << std::numeric_limits<uint64>::max();
  2047. expect (numStr == "18446744073709551615");
  2048. }
  2049. {
  2050. String numStr;
  2051. numStr << std::numeric_limits<uint64>::min();
  2052. expect (numStr == "0");
  2053. }
  2054. // size_t
  2055. {
  2056. String numStr (std::numeric_limits<size_t>::min());
  2057. expect (numStr == "0");
  2058. }
  2059. beginTest ("Numeric conversions");
  2060. expect (String().getIntValue() == 0);
  2061. expect (String().getDoubleValue() == 0.0);
  2062. expect (String().getFloatValue() == 0.0f);
  2063. expect (s.getIntValue() == 12345678);
  2064. expect (s.getLargeIntValue() == (int64) 12345678);
  2065. expect (s.getDoubleValue() == 12345678.0);
  2066. expect (s.getFloatValue() == 12345678.0f);
  2067. expect (String (-1234).getIntValue() == -1234);
  2068. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  2069. expect (String (-1234.56).getDoubleValue() == -1234.56);
  2070. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  2071. expect (String (std::numeric_limits<int>::max()).getIntValue() == std::numeric_limits<int>::max());
  2072. expect (String (std::numeric_limits<int>::min()).getIntValue() == std::numeric_limits<int>::min());
  2073. expect (String (std::numeric_limits<int64>::max()).getLargeIntValue() == std::numeric_limits<int64>::max());
  2074. expect (String (std::numeric_limits<int64>::min()).getLargeIntValue() == std::numeric_limits<int64>::min());
  2075. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  2076. expect (s.getHexValue32() == 0x12345678);
  2077. expect (s.getHexValue64() == (int64) 0x12345678);
  2078. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  2079. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  2080. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  2081. expect (String::toHexString ((size_t) 0x12ab).equalsIgnoreCase ("12ab"));
  2082. expect (String::toHexString ((long) 0x12ab).equalsIgnoreCase ("12ab"));
  2083. expect (String::toHexString ((int8) -1).equalsIgnoreCase ("ff"));
  2084. expect (String::toHexString ((int16) -1).equalsIgnoreCase ("ffff"));
  2085. expect (String::toHexString ((int32) -1).equalsIgnoreCase ("ffffffff"));
  2086. expect (String::toHexString ((int64) -1).equalsIgnoreCase ("ffffffffffffffff"));
  2087. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  2088. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  2089. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  2090. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  2091. expectEquals (String (12345.67, 4), String ("12345.6700"));
  2092. expectEquals (String (12345.67, 6), String ("12345.670000"));
  2093. expectEquals (String (2589410.5894, 7), String ("2589410.5894000"));
  2094. expectEquals (String (12345.67, 8), String ("12345.67000000"));
  2095. expectEquals (String (1e19, 4), String ("10000000000000000000.0000"));
  2096. expectEquals (String (1e-34, 36), String ("0.000000000000000000000000000000000100"));
  2097. expectEquals (String (1.39, 1), String ("1.4"));
  2098. expectEquals (String (12345.67, 4, true), String ("1.2346e+04"));
  2099. expectEquals (String (12345.67, 6, true), String ("1.234567e+04"));
  2100. expectEquals (String (2589410.5894, 7, true), String ("2.5894106e+06"));
  2101. expectEquals (String (12345.67, 8, true), String ("1.23456700e+04"));
  2102. expectEquals (String (1e19, 4, true), String ("1.0000e+19"));
  2103. expectEquals (String (1e-34, 5, true), String ("1.00000e-34"));
  2104. expectEquals (String (1.39, 1, true), String ("1.4e+00"));
  2105. beginTest ("Subsections");
  2106. String s3;
  2107. s3 = "abcdeFGHIJ";
  2108. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  2109. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  2110. expect (s3.containsIgnoreCase (s3.substring (3)));
  2111. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  2112. expect (s3.indexOfAnyOf (String (L"xyzf"), 2, false) == -1);
  2113. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  2114. expect (s3.containsAnyOf (String (L"zzzFs")));
  2115. expect (s3.startsWith ("abcd"));
  2116. expect (s3.startsWithIgnoreCase (String (L"abCD")));
  2117. expect (s3.startsWith (String()));
  2118. expect (s3.startsWithChar ('a'));
  2119. expect (s3.endsWith (String ("HIJ")));
  2120. expect (s3.endsWithIgnoreCase (String (L"Hij")));
  2121. expect (s3.endsWith (String()));
  2122. expect (s3.endsWithChar (L'J'));
  2123. expect (s3.indexOf ("HIJ") == 7);
  2124. expect (s3.indexOf (String (L"HIJK")) == -1);
  2125. expect (s3.indexOfIgnoreCase ("hij") == 7);
  2126. expect (s3.indexOfIgnoreCase (String (L"hijk")) == -1);
  2127. expect (s3.toStdString() == s3.toRawUTF8());
  2128. String s4 (s3);
  2129. s4.append (String ("xyz123"), 3);
  2130. expect (s4 == s3 + "xyz");
  2131. expect (String (1234) < String (1235));
  2132. expect (String (1235) > String (1234));
  2133. expect (String (1234) >= String (1234));
  2134. expect (String (1234) <= String (1234));
  2135. expect (String (1235) >= String (1234));
  2136. expect (String (1234) <= String (1235));
  2137. String s5 ("word word2 word3");
  2138. expect (s5.containsWholeWord (String ("word2")));
  2139. expect (s5.indexOfWholeWord ("word2") == 5);
  2140. expect (s5.containsWholeWord (String (L"word")));
  2141. expect (s5.containsWholeWord ("word3"));
  2142. expect (s5.containsWholeWord (s5));
  2143. expect (s5.containsWholeWordIgnoreCase (String (L"Word2")));
  2144. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  2145. expect (s5.containsWholeWordIgnoreCase (String (L"Word")));
  2146. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  2147. expect (! s5.containsWholeWordIgnoreCase (String (L"Wordx")));
  2148. expect (! s5.containsWholeWordIgnoreCase ("xWord2"));
  2149. expect (s5.containsNonWhitespaceChars());
  2150. expect (s5.containsOnly ("ordw23 "));
  2151. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  2152. expect (s5.matchesWildcard (String (L"wor*"), false));
  2153. expect (s5.matchesWildcard ("wOr*", true));
  2154. expect (s5.matchesWildcard (String (L"*word3"), true));
  2155. expect (s5.matchesWildcard ("*word?", true));
  2156. expect (s5.matchesWildcard (String (L"Word*3"), true));
  2157. expect (! s5.matchesWildcard (String (L"*34"), true));
  2158. expect (String ("xx**y").matchesWildcard ("*y", true));
  2159. expect (String ("xx**y").matchesWildcard ("x*y", true));
  2160. expect (String ("xx**y").matchesWildcard ("xx*y", true));
  2161. expect (String ("xx**y").matchesWildcard ("xx*", true));
  2162. expect (String ("xx?y").matchesWildcard ("x??y", true));
  2163. expect (String ("xx?y").matchesWildcard ("xx?y", true));
  2164. expect (! String ("xx?y").matchesWildcard ("xx?y?", true));
  2165. expect (String ("xx?y").matchesWildcard ("xx??", true));
  2166. expectEquals (s5.fromFirstOccurrenceOf (String(), true, false), s5);
  2167. expectEquals (s5.fromFirstOccurrenceOf ("xword2", true, false), s5.substring (100));
  2168. expectEquals (s5.fromFirstOccurrenceOf (String (L"word2"), true, false), s5.substring (5));
  2169. expectEquals (s5.fromFirstOccurrenceOf ("Word2", true, true), s5.substring (5));
  2170. expectEquals (s5.fromFirstOccurrenceOf ("word2", false, false), s5.getLastCharacters (6));
  2171. expectEquals (s5.fromFirstOccurrenceOf ("Word2", false, true), s5.getLastCharacters (6));
  2172. expectEquals (s5.fromLastOccurrenceOf (String(), true, false), s5);
  2173. expectEquals (s5.fromLastOccurrenceOf ("wordx", true, false), s5);
  2174. expectEquals (s5.fromLastOccurrenceOf ("word", true, false), s5.getLastCharacters (5));
  2175. expectEquals (s5.fromLastOccurrenceOf ("worD", true, true), s5.getLastCharacters (5));
  2176. expectEquals (s5.fromLastOccurrenceOf ("word", false, false), s5.getLastCharacters (1));
  2177. expectEquals (s5.fromLastOccurrenceOf ("worD", false, true), s5.getLastCharacters (1));
  2178. expect (s5.upToFirstOccurrenceOf (String(), true, false).isEmpty());
  2179. expectEquals (s5.upToFirstOccurrenceOf ("word4", true, false), s5);
  2180. expectEquals (s5.upToFirstOccurrenceOf ("word2", true, false), s5.substring (0, 10));
  2181. expectEquals (s5.upToFirstOccurrenceOf ("Word2", true, true), s5.substring (0, 10));
  2182. expectEquals (s5.upToFirstOccurrenceOf ("word2", false, false), s5.substring (0, 5));
  2183. expectEquals (s5.upToFirstOccurrenceOf ("Word2", false, true), s5.substring (0, 5));
  2184. expectEquals (s5.upToLastOccurrenceOf (String(), true, false), s5);
  2185. expectEquals (s5.upToLastOccurrenceOf ("zword", true, false), s5);
  2186. expectEquals (s5.upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  2187. expectEquals (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false), s5.dropLastCharacters (1));
  2188. expectEquals (s5.upToLastOccurrenceOf ("Word", true, true), s5.dropLastCharacters (1));
  2189. expectEquals (s5.upToLastOccurrenceOf ("word", false, false), s5.dropLastCharacters (5));
  2190. expectEquals (s5.upToLastOccurrenceOf ("Word", false, true), s5.dropLastCharacters (5));
  2191. expectEquals (s5.replace ("word", "xyz", false), String ("xyz xyz2 xyz3"));
  2192. expect (s5.replace ("Word", "xyz", true) == "xyz xyz2 xyz3");
  2193. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  2194. expect (s5.replace ("Word", "", true) == " 2 3");
  2195. expectEquals (s5.replace ("Word2", "xyz", true), String ("word xyz word3"));
  2196. expect (s5.replaceCharacter (L'w', 'x') != s5);
  2197. expectEquals (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w'), s5);
  2198. expect (s5.replaceCharacters ("wo", "xy") != s5);
  2199. expectEquals (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", "wo"), s5);
  2200. expectEquals (s5.retainCharacters ("1wordxya"), String ("wordwordword"));
  2201. expect (s5.retainCharacters (String()).isEmpty());
  2202. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  2203. expectEquals (s5.removeCharacters (String()), s5);
  2204. expect (s5.initialSectionContainingOnly ("word") == L"word");
  2205. expect (String ("word").initialSectionContainingOnly ("word") == L"word");
  2206. expectEquals (s5.initialSectionNotContaining (String ("xyz ")), String ("word"));
  2207. expectEquals (s5.initialSectionNotContaining (String (";[:'/")), s5);
  2208. expect (! s5.isQuotedString());
  2209. expect (s5.quoted().isQuotedString());
  2210. expect (! s5.quoted().unquoted().isQuotedString());
  2211. expect (! String ("x'").isQuotedString());
  2212. expect (String ("'x").isQuotedString());
  2213. String s6 (" \t xyz \t\r\n");
  2214. expectEquals (s6.trim(), String ("xyz"));
  2215. expect (s6.trim().trim() == "xyz");
  2216. expectEquals (s5.trim(), s5);
  2217. expectEquals (s6.trimStart().trimEnd(), s6.trim());
  2218. expectEquals (s6.trimStart().trimEnd(), s6.trimEnd().trimStart());
  2219. expectEquals (s6.trimStart().trimStart().trimEnd().trimEnd(), s6.trimEnd().trimStart());
  2220. expect (s6.trimStart() != s6.trimEnd());
  2221. expectEquals (("\t\r\n " + s6 + "\t\n \r").trim(), s6.trim());
  2222. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  2223. }
  2224. {
  2225. beginTest ("UTF conversions");
  2226. TestUTFConversion <CharPointer_UTF32>::test (*this, r);
  2227. TestUTFConversion <CharPointer_UTF8>::test (*this, r);
  2228. TestUTFConversion <CharPointer_UTF16>::test (*this, r);
  2229. }
  2230. {
  2231. beginTest ("StringArray");
  2232. StringArray s;
  2233. s.addTokens ("4,3,2,1,0", ";,", "x");
  2234. expectEquals (s.size(), 5);
  2235. expectEquals (s.joinIntoString ("-"), String ("4-3-2-1-0"));
  2236. s.remove (2);
  2237. expectEquals (s.joinIntoString ("--"), String ("4--3--1--0"));
  2238. expectEquals (s.joinIntoString (StringRef()), String ("4310"));
  2239. s.clear();
  2240. expectEquals (s.joinIntoString ("x"), String());
  2241. StringArray toks;
  2242. toks.addTokens ("x,,", ";,", "");
  2243. expectEquals (toks.size(), 3);
  2244. expectEquals (toks.joinIntoString ("-"), String ("x--"));
  2245. toks.clear();
  2246. toks.addTokens (",x,", ";,", "");
  2247. expectEquals (toks.size(), 3);
  2248. expectEquals (toks.joinIntoString ("-"), String ("-x-"));
  2249. toks.clear();
  2250. toks.addTokens ("x,'y,z',", ";,", "'");
  2251. expectEquals (toks.size(), 3);
  2252. expectEquals (toks.joinIntoString ("-"), String ("x-'y,z'-"));
  2253. }
  2254. {
  2255. beginTest ("var");
  2256. var v1 = 0;
  2257. var v2 = 0.16;
  2258. var v3 = "0.16";
  2259. var v4 = (int64) 0;
  2260. var v5 = 0.0;
  2261. expect (! v2.equals (v1));
  2262. expect (! v1.equals (v2));
  2263. expect (v2.equals (v3));
  2264. expect (! v3.equals (v1));
  2265. expect (! v1.equals (v3));
  2266. expect (v1.equals (v4));
  2267. expect (v4.equals (v1));
  2268. expect (v5.equals (v4));
  2269. expect (v4.equals (v5));
  2270. expect (! v2.equals (v4));
  2271. expect (! v4.equals (v2));
  2272. }
  2273. {
  2274. beginTest ("Significant figures");
  2275. // Integers
  2276. expectEquals (String::toDecimalStringWithSignificantFigures (13, 1), String ("10"));
  2277. expectEquals (String::toDecimalStringWithSignificantFigures (13, 2), String ("13"));
  2278. expectEquals (String::toDecimalStringWithSignificantFigures (13, 3), String ("13.0"));
  2279. expectEquals (String::toDecimalStringWithSignificantFigures (13, 4), String ("13.00"));
  2280. expectEquals (String::toDecimalStringWithSignificantFigures (19368, 1), String ("20000"));
  2281. expectEquals (String::toDecimalStringWithSignificantFigures (19348, 3), String ("19300"));
  2282. expectEquals (String::toDecimalStringWithSignificantFigures (-5, 1), String ("-5"));
  2283. expectEquals (String::toDecimalStringWithSignificantFigures (-5, 3), String ("-5.00"));
  2284. // Zero
  2285. expectEquals (String::toDecimalStringWithSignificantFigures (0, 1), String ("0"));
  2286. expectEquals (String::toDecimalStringWithSignificantFigures (0, 2), String ("0.0"));
  2287. expectEquals (String::toDecimalStringWithSignificantFigures (0, 3), String ("0.00"));
  2288. // Floating point
  2289. expectEquals (String::toDecimalStringWithSignificantFigures (19.0, 1), String ("20"));
  2290. expectEquals (String::toDecimalStringWithSignificantFigures (19.0, 2), String ("19"));
  2291. expectEquals (String::toDecimalStringWithSignificantFigures (19.0, 3), String ("19.0"));
  2292. expectEquals (String::toDecimalStringWithSignificantFigures (19.0, 4), String ("19.00"));
  2293. expectEquals (String::toDecimalStringWithSignificantFigures (-5.45, 1), String ("-5"));
  2294. expectEquals (String::toDecimalStringWithSignificantFigures (-5.45, 3), String ("-5.45"));
  2295. expectEquals (String::toDecimalStringWithSignificantFigures (12345.6789, 9), String ("12345.6789"));
  2296. expectEquals (String::toDecimalStringWithSignificantFigures (12345.6789, 8), String ("12345.679"));
  2297. expectEquals (String::toDecimalStringWithSignificantFigures (12345.6789, 5), String ("12346"));
  2298. expectEquals (String::toDecimalStringWithSignificantFigures (0.00028647, 6), String ("0.000286470"));
  2299. expectEquals (String::toDecimalStringWithSignificantFigures (0.0028647, 6), String ("0.00286470"));
  2300. expectEquals (String::toDecimalStringWithSignificantFigures (2.8647, 6), String ("2.86470"));
  2301. expectEquals (String::toDecimalStringWithSignificantFigures (-0.0000000000019, 1), String ("-0.000000000002"));
  2302. }
  2303. {
  2304. beginTest ("Float trimming");
  2305. {
  2306. StringPairArray tests;
  2307. tests.set ("1", "1");
  2308. tests.set ("1.0", "1.0");
  2309. tests.set ("-1", "-1");
  2310. tests.set ("-100", "-100");
  2311. tests.set ("110", "110");
  2312. tests.set ("9090", "9090");
  2313. tests.set ("1000.0", "1000.0");
  2314. tests.set ("1.0", "1.0");
  2315. tests.set ("-1.00", "-1.0");
  2316. tests.set ("1.20", "1.2");
  2317. tests.set ("1.300", "1.3");
  2318. tests.set ("1.301", "1.301");
  2319. tests.set ("1e", "1");
  2320. tests.set ("-1e+", "-1");
  2321. tests.set ("1e-", "1");
  2322. tests.set ("1e0", "1");
  2323. tests.set ("1e+0", "1");
  2324. tests.set ("1e-0", "1");
  2325. tests.set ("1e000", "1");
  2326. tests.set ("1e+000", "1");
  2327. tests.set ("-1e-000", "-1");
  2328. tests.set ("1e100", "1e100");
  2329. tests.set ("100e100", "100e100");
  2330. tests.set ("100.0e0100", "100.0e100");
  2331. tests.set ("-1e1", "-1e1");
  2332. tests.set ("1e10", "1e10");
  2333. tests.set ("-1e+10", "-1e10");
  2334. tests.set ("1e-10", "1e-10");
  2335. tests.set ("1e0010", "1e10");
  2336. tests.set ("1e-0010", "1e-10");
  2337. tests.set ("1e-1", "1e-1");
  2338. tests.set ("-1.0e1", "-1.0e1");
  2339. tests.set ("1.0e-1", "1.0e-1");
  2340. tests.set ("1.00e-1", "1.0e-1");
  2341. tests.set ("1.001e1", "1.001e1");
  2342. tests.set ("1.010e+1", "1.01e1");
  2343. tests.set ("-1.1000e1", "-1.1e1");
  2344. for (auto& input : tests.getAllKeys())
  2345. expectEquals (reduceLengthOfFloatString (input), tests[input]);
  2346. }
  2347. {
  2348. std::map<double, String> tests;
  2349. tests[1] = "1.0";
  2350. tests[1.1] = "1.1";
  2351. tests[1.01] = "1.01";
  2352. tests[0.76378] = "7.6378e-1";
  2353. tests[-10] = "-1.0e1";
  2354. tests[10.01] = "1.001e1";
  2355. tests[10691.01] = "1.069101e4";
  2356. tests[0.0123] = "1.23e-2";
  2357. tests[-3.7e-27] = "-3.7e-27";
  2358. tests[1e+40] = "1.0e40";
  2359. for (auto& test : tests)
  2360. expectEquals (reduceLengthOfFloatString (String (test.first, 15, true)), test.second);
  2361. }
  2362. }
  2363. {
  2364. beginTest ("Serialisation");
  2365. std::map <double, String> tests;
  2366. tests[364] = "364.0";
  2367. tests[1e7] = "1.0e7";
  2368. tests[12345678901] = "1.2345678901e10";
  2369. tests[1234567890123456.7] = "1.234567890123457e15";
  2370. tests[12345678.901234567] = "1.234567890123457e7";
  2371. tests[1234567.8901234567] = "1.234567890123457e6";
  2372. tests[123456.78901234567] = "123456.7890123457";
  2373. tests[12345.678901234567] = "12345.67890123457";
  2374. tests[1234.5678901234567] = "1234.567890123457";
  2375. tests[123.45678901234567] = "123.4567890123457";
  2376. tests[12.345678901234567] = "12.34567890123457";
  2377. tests[1.2345678901234567] = "1.234567890123457";
  2378. tests[0.12345678901234567] = "0.1234567890123457";
  2379. tests[0.012345678901234567] = "0.01234567890123457";
  2380. tests[0.0012345678901234567] = "0.001234567890123457";
  2381. tests[0.00012345678901234567] = "0.0001234567890123457";
  2382. tests[0.000012345678901234567] = "0.00001234567890123457";
  2383. tests[0.0000012345678901234567] = "1.234567890123457e-6";
  2384. tests[0.00000012345678901234567] = "1.234567890123457e-7";
  2385. for (auto& test : tests)
  2386. {
  2387. expectEquals (serialiseDouble (test.first), test.second);
  2388. expectEquals (serialiseDouble (-test.first), "-" + test.second);
  2389. }
  2390. }
  2391. {
  2392. beginTest ("Loops");
  2393. String str (CharPointer_UTF8 ("\xc2\xaf\\_(\xe3\x83\x84)_/\xc2\xaf"));
  2394. std::vector<juce_wchar> parts { 175, 92, 95, 40, 12484, 41, 95, 47, 175 };
  2395. size_t index = 0;
  2396. for (auto c : str)
  2397. expectEquals (c, parts[index++]);
  2398. }
  2399. }
  2400. };
  2401. static StringTests stringUnitTests;
  2402. #endif
  2403. } // namespace juce