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.

2947 lines
105KB

  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. #if JUCE_MSVC
  20. #pragma warning (push)
  21. #pragma warning (disable: 4514 4996)
  22. #endif
  23. NewLine newLine;
  24. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  25. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  26. #endif
  27. #if JUCE_NATIVE_WCHAR_IS_UTF8
  28. using CharPointer_wchar_t = CharPointer_UTF8;
  29. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  30. using CharPointer_wchar_t = CharPointer_UTF16;
  31. #else
  32. using CharPointer_wchar_t = CharPointer_UTF32;
  33. #endif
  34. static inline CharPointer_wchar_t castToCharPointer_wchar_t (const void* t) noexcept
  35. {
  36. return CharPointer_wchar_t (static_cast<const CharPointer_wchar_t::CharType*> (t));
  37. }
  38. //==============================================================================
  39. // (Mirrors the structure of StringHolder, but without the atomic member, so can be statically constructed)
  40. struct EmptyString
  41. {
  42. int refCount;
  43. size_t allocatedBytes;
  44. String::CharPointerType::CharType text;
  45. };
  46. static const EmptyString emptyString { 0x3fffffff, sizeof (String::CharPointerType::CharType), 0 };
  47. //==============================================================================
  48. class StringHolder
  49. {
  50. public:
  51. StringHolder() = delete;
  52. using CharPointerType = String::CharPointerType;
  53. using CharType = String::CharPointerType::CharType;
  54. //==============================================================================
  55. static CharPointerType createUninitialisedBytes (size_t numBytes)
  56. {
  57. numBytes = (numBytes + 3) & ~(size_t) 3;
  58. auto s = reinterpret_cast<StringHolder*> (new char [sizeof (StringHolder) - sizeof (CharType) + numBytes]);
  59. s->refCount.value = 0;
  60. s->allocatedNumBytes = numBytes;
  61. return CharPointerType (s->text);
  62. }
  63. template <class CharPointer>
  64. static CharPointerType createFromCharPointer (const CharPointer text)
  65. {
  66. if (text.getAddress() == nullptr || text.isEmpty())
  67. return CharPointerType (&(emptyString.text));
  68. auto bytesNeeded = sizeof (CharType) + CharPointerType::getBytesRequiredFor (text);
  69. auto dest = createUninitialisedBytes (bytesNeeded);
  70. CharPointerType (dest).writeAll (text);
  71. return dest;
  72. }
  73. template <class CharPointer>
  74. static CharPointerType createFromCharPointer (const CharPointer text, size_t maxChars)
  75. {
  76. if (text.getAddress() == nullptr || text.isEmpty() || maxChars == 0)
  77. return CharPointerType (&(emptyString.text));
  78. auto end = text;
  79. size_t numChars = 0;
  80. size_t bytesNeeded = sizeof (CharType);
  81. while (numChars < maxChars && ! end.isEmpty())
  82. {
  83. bytesNeeded += CharPointerType::getBytesRequiredFor (end.getAndAdvance());
  84. ++numChars;
  85. }
  86. auto dest = createUninitialisedBytes (bytesNeeded);
  87. CharPointerType (dest).writeWithCharLimit (text, (int) numChars + 1);
  88. return dest;
  89. }
  90. template <class CharPointer>
  91. static CharPointerType createFromCharPointer (const CharPointer start, const CharPointer end)
  92. {
  93. if (start.getAddress() == nullptr || start.isEmpty())
  94. return CharPointerType (&(emptyString.text));
  95. auto e = start;
  96. int numChars = 0;
  97. auto bytesNeeded = sizeof (CharType);
  98. while (e < end && ! e.isEmpty())
  99. {
  100. bytesNeeded += CharPointerType::getBytesRequiredFor (e.getAndAdvance());
  101. ++numChars;
  102. }
  103. auto dest = createUninitialisedBytes (bytesNeeded);
  104. CharPointerType (dest).writeWithCharLimit (start, numChars + 1);
  105. return dest;
  106. }
  107. static CharPointerType createFromCharPointer (const CharPointerType start, const CharPointerType end)
  108. {
  109. if (start.getAddress() == nullptr || start.isEmpty())
  110. return CharPointerType (&(emptyString.text));
  111. auto numBytes = (size_t) (reinterpret_cast<const char*> (end.getAddress())
  112. - reinterpret_cast<const char*> (start.getAddress()));
  113. auto dest = createUninitialisedBytes (numBytes + sizeof (CharType));
  114. memcpy (dest.getAddress(), start, numBytes);
  115. dest.getAddress()[numBytes / sizeof (CharType)] = 0;
  116. return dest;
  117. }
  118. static CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  119. {
  120. auto dest = createUninitialisedBytes (numChars * sizeof (CharType) + sizeof (CharType));
  121. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  122. return dest;
  123. }
  124. //==============================================================================
  125. static void retain (const CharPointerType text) noexcept
  126. {
  127. auto* b = bufferFromText (text);
  128. if (! isEmptyString (b))
  129. ++(b->refCount);
  130. }
  131. static inline void release (StringHolder* const b) noexcept
  132. {
  133. if (! isEmptyString (b))
  134. if (--(b->refCount) == -1)
  135. delete[] reinterpret_cast<char*> (b);
  136. }
  137. static void release (const CharPointerType text) noexcept
  138. {
  139. release (bufferFromText (text));
  140. }
  141. static inline int getReferenceCount (const CharPointerType text) noexcept
  142. {
  143. return bufferFromText (text)->refCount.get() + 1;
  144. }
  145. //==============================================================================
  146. static CharPointerType makeUniqueWithByteSize (const CharPointerType text, size_t numBytes)
  147. {
  148. auto* b = bufferFromText (text);
  149. if (isEmptyString (b))
  150. {
  151. auto newText = createUninitialisedBytes (numBytes);
  152. newText.writeNull();
  153. return newText;
  154. }
  155. if (b->allocatedNumBytes >= numBytes && b->refCount.get() <= 0)
  156. return text;
  157. auto newText = createUninitialisedBytes (jmax (b->allocatedNumBytes, numBytes));
  158. memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes);
  159. release (b);
  160. return newText;
  161. }
  162. static size_t getAllocatedNumBytes (const CharPointerType text) noexcept
  163. {
  164. return bufferFromText (text)->allocatedNumBytes;
  165. }
  166. //==============================================================================
  167. Atomic<int> refCount;
  168. size_t allocatedNumBytes;
  169. CharType text[1];
  170. private:
  171. static inline StringHolder* bufferFromText (const CharPointerType text) noexcept
  172. {
  173. // (Can't use offsetof() here because of warnings about this not being a POD)
  174. return reinterpret_cast<StringHolder*> (reinterpret_cast<char*> (text.getAddress())
  175. - (reinterpret_cast<size_t> (reinterpret_cast<StringHolder*> (128)->text) - 128));
  176. }
  177. static inline bool isEmptyString (StringHolder* other)
  178. {
  179. return (other->refCount.get() & 0x30000000) != 0;
  180. }
  181. void compileTimeChecks()
  182. {
  183. // Let me know if any of these assertions fail on your system!
  184. #if JUCE_NATIVE_WCHAR_IS_UTF8
  185. static_assert (sizeof (wchar_t) == 1, "JUCE_NATIVE_WCHAR_IS_* macro has incorrect value");
  186. #elif JUCE_NATIVE_WCHAR_IS_UTF16
  187. static_assert (sizeof (wchar_t) == 2, "JUCE_NATIVE_WCHAR_IS_* macro has incorrect value");
  188. #elif JUCE_NATIVE_WCHAR_IS_UTF32
  189. static_assert (sizeof (wchar_t) == 4, "JUCE_NATIVE_WCHAR_IS_* macro has incorrect value");
  190. #else
  191. #error "native wchar_t size is unknown"
  192. #endif
  193. static_assert (sizeof (EmptyString) == sizeof (StringHolder),
  194. "StringHolder is not large enough to hold an empty String");
  195. }
  196. };
  197. JUCE_DECLARE_DEPRECATED_STATIC (const String String::empty;)
  198. //==============================================================================
  199. String::String() noexcept : text (&(emptyString.text))
  200. {
  201. }
  202. String::~String() noexcept
  203. {
  204. StringHolder::release (text);
  205. }
  206. String::String (const String& other) noexcept : text (other.text)
  207. {
  208. StringHolder::retain (text);
  209. }
  210. void String::swapWith (String& other) noexcept
  211. {
  212. std::swap (text, other.text);
  213. }
  214. void String::clear() noexcept
  215. {
  216. StringHolder::release (text);
  217. text = &(emptyString.text);
  218. }
  219. String& String::operator= (const String& other) noexcept
  220. {
  221. StringHolder::retain (other.text);
  222. StringHolder::release (text.atomicSwap (other.text));
  223. return *this;
  224. }
  225. String::String (String&& other) noexcept : text (other.text)
  226. {
  227. other.text = &(emptyString.text);
  228. }
  229. String& String::operator= (String&& other) noexcept
  230. {
  231. std::swap (text, other.text);
  232. return *this;
  233. }
  234. inline String::PreallocationBytes::PreallocationBytes (const size_t num) noexcept : numBytes (num) {}
  235. String::String (const PreallocationBytes& preallocationSize)
  236. : text (StringHolder::createUninitialisedBytes (preallocationSize.numBytes + sizeof (CharPointerType::CharType)))
  237. {
  238. }
  239. void String::preallocateBytes (const size_t numBytesNeeded)
  240. {
  241. text = StringHolder::makeUniqueWithByteSize (text, numBytesNeeded + sizeof (CharPointerType::CharType));
  242. }
  243. int String::getReferenceCount() const noexcept
  244. {
  245. return StringHolder::getReferenceCount (text);
  246. }
  247. //==============================================================================
  248. String::String (const char* const t)
  249. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t)))
  250. {
  251. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  252. that contains values greater than 127. These can NOT be correctly converted to unicode
  253. because there's no way for the String class to know what encoding was used to
  254. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  255. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  256. string to the String class - so for example if your source data is actually UTF-8,
  257. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  258. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  259. you use UTF-8 with escape characters in your source code to represent extended characters,
  260. because there's no other way to represent these strings in a way that isn't dependent on
  261. the compiler, source code editor and platform.
  262. Note that the Projucer has a handy string literal generator utility that will convert
  263. any unicode string to a valid C++ string literal, creating ascii escape sequences that will
  264. work in any compiler.
  265. */
  266. jassert (t == nullptr || CharPointer_ASCII::isValidString (t, std::numeric_limits<int>::max()));
  267. }
  268. String::String (const char* const t, const size_t maxChars)
  269. : text (StringHolder::createFromCharPointer (CharPointer_ASCII (t), maxChars))
  270. {
  271. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  272. that contains values greater than 127. These can NOT be correctly converted to unicode
  273. because there's no way for the String class to know what encoding was used to
  274. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  275. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  276. string to the String class - so for example if your source data is actually UTF-8,
  277. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  278. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  279. you use UTF-8 with escape characters in your source code to represent extended characters,
  280. because there's no other way to represent these strings in a way that isn't dependent on
  281. the compiler, source code editor and platform.
  282. Note that the Projucer has a handy string literal generator utility that will convert
  283. any unicode string to a valid C++ string literal, creating ascii escape sequences that will
  284. work in any compiler.
  285. */
  286. jassert (t == nullptr || CharPointer_ASCII::isValidString (t, (int) maxChars));
  287. }
  288. String::String (const wchar_t* const t) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t))) {}
  289. String::String (const CharPointer_UTF8 t) : text (StringHolder::createFromCharPointer (t)) {}
  290. String::String (const CharPointer_UTF16 t) : text (StringHolder::createFromCharPointer (t)) {}
  291. String::String (const CharPointer_UTF32 t) : text (StringHolder::createFromCharPointer (t)) {}
  292. String::String (const CharPointer_ASCII t) : text (StringHolder::createFromCharPointer (t)) {}
  293. String::String (CharPointer_UTF8 t, size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  294. String::String (CharPointer_UTF16 t, size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  295. String::String (CharPointer_UTF32 t, size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  296. String::String (const wchar_t* t, size_t maxChars) : text (StringHolder::createFromCharPointer (castToCharPointer_wchar_t (t), maxChars)) {}
  297. String::String (CharPointer_UTF8 start, CharPointer_UTF8 end) : text (StringHolder::createFromCharPointer (start, end)) {}
  298. String::String (CharPointer_UTF16 start, CharPointer_UTF16 end) : text (StringHolder::createFromCharPointer (start, end)) {}
  299. String::String (CharPointer_UTF32 start, CharPointer_UTF32 end) : text (StringHolder::createFromCharPointer (start, end)) {}
  300. String::String (const std::string& s) : text (StringHolder::createFromFixedLength (s.data(), s.size())) {}
  301. String::String (StringRef s) : text (StringHolder::createFromCharPointer (s.text)) {}
  302. String String::charToString (juce_wchar character)
  303. {
  304. String result (PreallocationBytes (CharPointerType::getBytesRequiredFor (character)));
  305. CharPointerType t (result.text);
  306. t.write (character);
  307. t.writeNull();
  308. return result;
  309. }
  310. //==============================================================================
  311. namespace NumberToStringConverters
  312. {
  313. enum
  314. {
  315. charsNeededForInt = 32,
  316. charsNeededForDouble = 48
  317. };
  318. template <typename Type>
  319. static char* printDigits (char* t, Type v) noexcept
  320. {
  321. *--t = 0;
  322. do
  323. {
  324. *--t = static_cast<char> ('0' + (char) (v % 10));
  325. v /= 10;
  326. } while (v > 0);
  327. return t;
  328. }
  329. // pass in a pointer to the END of a buffer..
  330. static char* numberToString (char* t, int64 n) noexcept
  331. {
  332. if (n >= 0)
  333. return printDigits (t, static_cast<uint64> (n));
  334. // NB: this needs to be careful not to call -std::numeric_limits<int64>::min(),
  335. // which has undefined behaviour
  336. t = printDigits (t, static_cast<uint64> (-(n + 1)) + 1);
  337. *--t = '-';
  338. return t;
  339. }
  340. static char* numberToString (char* t, uint64 v) noexcept
  341. {
  342. return printDigits (t, v);
  343. }
  344. static char* numberToString (char* t, int n) noexcept
  345. {
  346. if (n >= 0)
  347. return printDigits (t, static_cast<unsigned int> (n));
  348. // NB: this needs to be careful not to call -std::numeric_limits<int>::min(),
  349. // which has undefined behaviour
  350. t = printDigits (t, static_cast<unsigned int> (-(n + 1)) + 1);
  351. *--t = '-';
  352. return t;
  353. }
  354. static char* numberToString (char* t, unsigned int v) noexcept
  355. {
  356. return printDigits (t, v);
  357. }
  358. static char* numberToString (char* t, long n) noexcept
  359. {
  360. if (n >= 0)
  361. return printDigits (t, static_cast<unsigned long> (n));
  362. t = printDigits (t, static_cast<unsigned long> (-(n + 1)) + 1);
  363. *--t = '-';
  364. return t;
  365. }
  366. static char* numberToString (char* t, unsigned long v) noexcept
  367. {
  368. return printDigits (t, v);
  369. }
  370. struct StackArrayStream : public std::basic_streambuf<char, std::char_traits<char>>
  371. {
  372. explicit StackArrayStream (char* d)
  373. {
  374. static const std::locale classicLocale (std::locale::classic());
  375. imbue (classicLocale);
  376. setp (d, d + charsNeededForDouble);
  377. }
  378. size_t writeDouble (double n, int numDecPlaces, bool useScientificNotation)
  379. {
  380. {
  381. std::ostream o (this);
  382. if (numDecPlaces > 0)
  383. {
  384. o.setf (useScientificNotation ? std::ios_base::scientific : std::ios_base::fixed);
  385. o.precision ((std::streamsize) numDecPlaces);
  386. }
  387. o << n;
  388. }
  389. return (size_t) (pptr() - pbase());
  390. }
  391. };
  392. static char* doubleToString (char* buffer, double n, int numDecPlaces, bool useScientificNotation, size_t& len) noexcept
  393. {
  394. StackArrayStream strm (buffer);
  395. len = strm.writeDouble (n, numDecPlaces, useScientificNotation);
  396. jassert (len <= charsNeededForDouble);
  397. return buffer;
  398. }
  399. template <typename IntegerType>
  400. static String::CharPointerType createFromInteger (IntegerType number)
  401. {
  402. char buffer [charsNeededForInt];
  403. auto* end = buffer + numElementsInArray (buffer);
  404. auto* start = numberToString (end, number);
  405. return StringHolder::createFromFixedLength (start, (size_t) (end - start - 1));
  406. }
  407. static String::CharPointerType createFromDouble (double number, int numberOfDecimalPlaces, bool useScientificNotation)
  408. {
  409. char buffer [charsNeededForDouble];
  410. size_t len;
  411. auto start = doubleToString (buffer, number, numberOfDecimalPlaces, useScientificNotation, len);
  412. return StringHolder::createFromFixedLength (start, len);
  413. }
  414. }
  415. //==============================================================================
  416. String::String (int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  417. String::String (unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  418. String::String (short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {}
  419. String::String (unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {}
  420. String::String (int64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  421. String::String (uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  422. String::String (long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  423. String::String (unsigned long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  424. String::String (float number) : text (NumberToStringConverters::createFromDouble ((double) number, 0, false)) {}
  425. String::String (double number) : text (NumberToStringConverters::createFromDouble ( number, 0, false)) {}
  426. String::String (float number, int numberOfDecimalPlaces, bool useScientificNotation) : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces, useScientificNotation)) {}
  427. String::String (double number, int numberOfDecimalPlaces, bool useScientificNotation) : text (NumberToStringConverters::createFromDouble ( number, numberOfDecimalPlaces, useScientificNotation)) {}
  428. //==============================================================================
  429. int String::length() const noexcept
  430. {
  431. return (int) text.length();
  432. }
  433. static size_t findByteOffsetOfEnd (String::CharPointerType text) noexcept
  434. {
  435. return (size_t) (((char*) text.findTerminatingNull().getAddress()) - (char*) text.getAddress());
  436. }
  437. size_t String::getByteOffsetOfEnd() const noexcept
  438. {
  439. return findByteOffsetOfEnd (text);
  440. }
  441. juce_wchar String::operator[] (int index) const noexcept
  442. {
  443. jassert (index == 0 || (index > 0 && index <= (int) text.lengthUpTo ((size_t) index + 1)));
  444. return text [index];
  445. }
  446. template <typename Type>
  447. struct HashGenerator
  448. {
  449. template <typename CharPointer>
  450. static Type calculate (CharPointer t) noexcept
  451. {
  452. Type result = {};
  453. while (! t.isEmpty())
  454. result = ((Type) multiplier) * result + (Type) t.getAndAdvance();
  455. return result;
  456. }
  457. enum { multiplier = sizeof (Type) > 4 ? 101 : 31 };
  458. };
  459. int String::hashCode() const noexcept { return (int) HashGenerator<uint32> ::calculate (text); }
  460. int64 String::hashCode64() const noexcept { return (int64) HashGenerator<uint64> ::calculate (text); }
  461. size_t String::hash() const noexcept { return HashGenerator<size_t> ::calculate (text); }
  462. //==============================================================================
  463. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; }
  464. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; }
  465. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const char* s2) noexcept { return s1.compare (s2) == 0; }
  466. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const char* s2) noexcept { return s1.compare (s2) != 0; }
  467. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const wchar_t* s2) noexcept { return s1.compare (s2) == 0; }
  468. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const wchar_t* s2) noexcept { return s1.compare (s2) != 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, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) <= 0; }
  473. JUCE_API bool JUCE_CALLTYPE operator> (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) > 0; }
  474. JUCE_API bool JUCE_CALLTYPE operator>= (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) >= 0; }
  475. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  476. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  477. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  478. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF16 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  479. JUCE_API bool JUCE_CALLTYPE operator== (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  480. JUCE_API bool JUCE_CALLTYPE operator!= (const String& s1, const CharPointer_UTF32 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  481. bool String::equalsIgnoreCase (const wchar_t* const t) const noexcept
  482. {
  483. return t != nullptr ? text.compareIgnoreCase (castToCharPointer_wchar_t (t)) == 0
  484. : isEmpty();
  485. }
  486. bool String::equalsIgnoreCase (const char* const t) const noexcept
  487. {
  488. return t != nullptr ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  489. : isEmpty();
  490. }
  491. bool String::equalsIgnoreCase (StringRef t) const noexcept
  492. {
  493. return text.compareIgnoreCase (t.text) == 0;
  494. }
  495. bool String::equalsIgnoreCase (const String& other) const noexcept
  496. {
  497. return text == other.text
  498. || text.compareIgnoreCase (other.text) == 0;
  499. }
  500. int String::compare (const String& other) const noexcept { return (text == other.text) ? 0 : text.compare (other.text); }
  501. int String::compare (const char* const other) const noexcept { return text.compare (CharPointer_UTF8 (other)); }
  502. int String::compare (const wchar_t* const other) const noexcept { return text.compare (castToCharPointer_wchar_t (other)); }
  503. int String::compareIgnoreCase (const String& other) const noexcept { return (text == other.text) ? 0 : text.compareIgnoreCase (other.text); }
  504. static int stringCompareRight (String::CharPointerType s1, String::CharPointerType s2) noexcept
  505. {
  506. for (int bias = 0;;)
  507. {
  508. auto c1 = s1.getAndAdvance();
  509. bool isDigit1 = CharacterFunctions::isDigit (c1);
  510. auto c2 = s2.getAndAdvance();
  511. bool isDigit2 = CharacterFunctions::isDigit (c2);
  512. if (! (isDigit1 || isDigit2)) return bias;
  513. if (! isDigit1) return -1;
  514. if (! isDigit2) return 1;
  515. if (c1 != c2 && bias == 0)
  516. bias = c1 < c2 ? -1 : 1;
  517. jassert (c1 != 0 && c2 != 0);
  518. }
  519. }
  520. static int stringCompareLeft (String::CharPointerType s1, String::CharPointerType s2) noexcept
  521. {
  522. for (;;)
  523. {
  524. auto c1 = s1.getAndAdvance();
  525. bool isDigit1 = CharacterFunctions::isDigit (c1);
  526. auto c2 = s2.getAndAdvance();
  527. bool isDigit2 = CharacterFunctions::isDigit (c2);
  528. if (! (isDigit1 || isDigit2)) return 0;
  529. if (! isDigit1) return -1;
  530. if (! isDigit2) return 1;
  531. if (c1 < c2) return -1;
  532. if (c1 > c2) return 1;
  533. }
  534. }
  535. static int naturalStringCompare (String::CharPointerType s1, String::CharPointerType s2, bool isCaseSensitive) noexcept
  536. {
  537. bool firstLoop = true;
  538. for (;;)
  539. {
  540. const bool hasSpace1 = s1.isWhitespace();
  541. const bool hasSpace2 = s2.isWhitespace();
  542. if ((! firstLoop) && (hasSpace1 ^ hasSpace2))
  543. {
  544. if (s1.isEmpty()) return -1;
  545. if (s2.isEmpty()) return 1;
  546. return hasSpace2 ? 1 : -1;
  547. }
  548. firstLoop = false;
  549. if (hasSpace1) s1 = s1.findEndOfWhitespace();
  550. if (hasSpace2) s2 = s2.findEndOfWhitespace();
  551. if (s1.isDigit() && s2.isDigit())
  552. {
  553. auto result = (*s1 == '0' || *s2 == '0') ? stringCompareLeft (s1, s2)
  554. : stringCompareRight (s1, s2);
  555. if (result != 0)
  556. return result;
  557. }
  558. auto c1 = s1.getAndAdvance();
  559. auto c2 = s2.getAndAdvance();
  560. if (c1 != c2 && ! isCaseSensitive)
  561. {
  562. c1 = CharacterFunctions::toUpperCase (c1);
  563. c2 = CharacterFunctions::toUpperCase (c2);
  564. }
  565. if (c1 == c2)
  566. {
  567. if (c1 == 0)
  568. return 0;
  569. }
  570. else
  571. {
  572. const bool isAlphaNum1 = CharacterFunctions::isLetterOrDigit (c1);
  573. const bool isAlphaNum2 = CharacterFunctions::isLetterOrDigit (c2);
  574. if (isAlphaNum2 && ! isAlphaNum1) return -1;
  575. if (isAlphaNum1 && ! isAlphaNum2) return 1;
  576. return c1 < c2 ? -1 : 1;
  577. }
  578. jassert (c1 != 0 && c2 != 0);
  579. }
  580. }
  581. int String::compareNatural (StringRef other, bool isCaseSensitive) const noexcept
  582. {
  583. return naturalStringCompare (getCharPointer(), other.text, isCaseSensitive);
  584. }
  585. //==============================================================================
  586. void String::append (const String& textToAppend, size_t maxCharsToTake)
  587. {
  588. appendCharPointer (this == &textToAppend ? String (textToAppend).text
  589. : textToAppend.text, maxCharsToTake);
  590. }
  591. void String::appendCharPointer (const CharPointerType textToAppend)
  592. {
  593. appendCharPointer (textToAppend, textToAppend.findTerminatingNull());
  594. }
  595. void String::appendCharPointer (const CharPointerType startOfTextToAppend,
  596. const CharPointerType endOfTextToAppend)
  597. {
  598. jassert (startOfTextToAppend.getAddress() != nullptr && endOfTextToAppend.getAddress() != nullptr);
  599. auto extraBytesNeeded = getAddressDifference (endOfTextToAppend.getAddress(),
  600. startOfTextToAppend.getAddress());
  601. jassert (extraBytesNeeded >= 0);
  602. if (extraBytesNeeded > 0)
  603. {
  604. auto byteOffsetOfNull = getByteOffsetOfEnd();
  605. preallocateBytes ((size_t) extraBytesNeeded + byteOffsetOfNull);
  606. auto* newStringStart = addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull);
  607. memcpy (newStringStart, startOfTextToAppend.getAddress(), (size_t) extraBytesNeeded);
  608. CharPointerType (addBytesToPointer (newStringStart, extraBytesNeeded)).writeNull();
  609. }
  610. }
  611. String& String::operator+= (const wchar_t* t)
  612. {
  613. appendCharPointer (castToCharPointer_wchar_t (t));
  614. return *this;
  615. }
  616. String& String::operator+= (const char* t)
  617. {
  618. appendCharPointer (CharPointer_UTF8 (t)); // (using UTF8 here triggers a faster code-path than ascii)
  619. return *this;
  620. }
  621. String& String::operator+= (const String& other)
  622. {
  623. if (isEmpty())
  624. return operator= (other);
  625. if (this == &other)
  626. return operator+= (String (*this));
  627. appendCharPointer (other.text);
  628. return *this;
  629. }
  630. String& String::operator+= (StringRef other)
  631. {
  632. return operator+= (String (other));
  633. }
  634. String& String::operator+= (char ch)
  635. {
  636. const char asString[] = { ch, 0 };
  637. return operator+= (asString);
  638. }
  639. String& String::operator+= (wchar_t ch)
  640. {
  641. const wchar_t asString[] = { ch, 0 };
  642. return operator+= (asString);
  643. }
  644. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  645. String& String::operator+= (juce_wchar ch)
  646. {
  647. const juce_wchar asString[] = { ch, 0 };
  648. appendCharPointer (CharPointer_UTF32 (asString));
  649. return *this;
  650. }
  651. #endif
  652. namespace StringHelpers
  653. {
  654. template <typename T>
  655. inline String& operationAddAssign (String& str, const T number)
  656. {
  657. char buffer [(sizeof(T) * 8) / 2];
  658. auto* end = buffer + numElementsInArray (buffer);
  659. auto* start = NumberToStringConverters::numberToString (end, number);
  660. #if JUCE_STRING_UTF_TYPE == 8
  661. str.appendCharPointer (String::CharPointerType (start), String::CharPointerType (end));
  662. #else
  663. str.appendCharPointer (CharPointer_ASCII (start), CharPointer_ASCII (end));
  664. #endif
  665. return str;
  666. }
  667. }
  668. String& String::operator+= (const int number) { return StringHelpers::operationAddAssign<int> (*this, number); }
  669. String& String::operator+= (const long number) { return StringHelpers::operationAddAssign<long> (*this, number); }
  670. String& String::operator+= (const int64 number) { return StringHelpers::operationAddAssign<int64> (*this, number); }
  671. String& String::operator+= (const uint64 number) { return StringHelpers::operationAddAssign<uint64> (*this, number); }
  672. //==============================================================================
  673. JUCE_API String JUCE_CALLTYPE operator+ (const char* s1, const String& s2) { String s (s1); return s += s2; }
  674. JUCE_API String JUCE_CALLTYPE operator+ (const wchar_t* s1, const String& s2) { String s (s1); return s += s2; }
  675. JUCE_API String JUCE_CALLTYPE operator+ (char s1, const String& s2) { return String::charToString ((juce_wchar) (uint8) s1) + s2; }
  676. JUCE_API String JUCE_CALLTYPE operator+ (wchar_t s1, const String& s2) { return String::charToString (s1) + s2; }
  677. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const String& s2) { return s1 += s2; }
  678. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const char* s2) { return s1 += s2; }
  679. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const wchar_t* s2) { return s1 += s2; }
  680. JUCE_API String JUCE_CALLTYPE operator+ (String s1, const std::string& s2) { return s1 += s2.c_str(); }
  681. JUCE_API String JUCE_CALLTYPE operator+ (String s1, char s2) { return s1 += s2; }
  682. JUCE_API String JUCE_CALLTYPE operator+ (String s1, wchar_t s2) { return s1 += s2; }
  683. #if ! JUCE_NATIVE_WCHAR_IS_UTF32
  684. JUCE_API String JUCE_CALLTYPE operator+ (juce_wchar s1, const String& s2) { return String::charToString (s1) + s2; }
  685. JUCE_API String JUCE_CALLTYPE operator+ (String s1, juce_wchar s2) { return s1 += s2; }
  686. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, juce_wchar s2) { return s1 += s2; }
  687. #endif
  688. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, char s2) { return s1 += s2; }
  689. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, wchar_t s2) { return s1 += s2; }
  690. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const char* s2) { return s1 += s2; }
  691. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const wchar_t* s2) { return s1 += s2; }
  692. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const String& s2) { return s1 += s2; }
  693. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, StringRef s2) { return s1 += s2; }
  694. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, const std::string& s2) { return s1 += s2.c_str(); }
  695. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, uint8 number) { return s1 += (int) number; }
  696. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, short number) { return s1 += (int) number; }
  697. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, int number) { return s1 += number; }
  698. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, long number) { return s1 += String (number); }
  699. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, unsigned long number) { return s1 += String (number); }
  700. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, int64 number) { return s1 += String (number); }
  701. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, uint64 number) { return s1 += String (number); }
  702. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, float number) { return s1 += String (number); }
  703. JUCE_API String& JUCE_CALLTYPE operator<< (String& s1, double number) { return s1 += String (number); }
  704. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  705. {
  706. return operator<< (stream, StringRef (text));
  707. }
  708. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, StringRef text)
  709. {
  710. auto numBytes = CharPointer_UTF8::getBytesRequiredFor (text.text);
  711. #if (JUCE_STRING_UTF_TYPE == 8)
  712. stream.write (text.text.getAddress(), numBytes);
  713. #else
  714. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  715. // if lots of large, persistent strings were to be written to streams).
  716. HeapBlock<char> temp (numBytes + 1);
  717. CharPointer_UTF8 (temp).writeAll (text.text);
  718. stream.write (temp, numBytes);
  719. #endif
  720. return stream;
  721. }
  722. //==============================================================================
  723. int String::indexOfChar (juce_wchar character) const noexcept
  724. {
  725. return text.indexOf (character);
  726. }
  727. int String::indexOfChar (int startIndex, juce_wchar character) const noexcept
  728. {
  729. auto t = text;
  730. for (int i = 0; ! t.isEmpty(); ++i)
  731. {
  732. if (i >= startIndex)
  733. {
  734. if (t.getAndAdvance() == character)
  735. return i;
  736. }
  737. else
  738. {
  739. ++t;
  740. }
  741. }
  742. return -1;
  743. }
  744. int String::lastIndexOfChar (juce_wchar character) const noexcept
  745. {
  746. auto t = text;
  747. int last = -1;
  748. for (int i = 0; ! t.isEmpty(); ++i)
  749. if (t.getAndAdvance() == character)
  750. last = i;
  751. return last;
  752. }
  753. int String::indexOfAnyOf (StringRef charactersToLookFor, int startIndex, bool ignoreCase) const noexcept
  754. {
  755. auto t = text;
  756. for (int i = 0; ! t.isEmpty(); ++i)
  757. {
  758. if (i >= startIndex)
  759. {
  760. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  761. return i;
  762. }
  763. else
  764. {
  765. ++t;
  766. }
  767. }
  768. return -1;
  769. }
  770. int String::indexOf (StringRef other) const noexcept
  771. {
  772. return other.isEmpty() ? 0 : text.indexOf (other.text);
  773. }
  774. int String::indexOfIgnoreCase (StringRef other) const noexcept
  775. {
  776. return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text);
  777. }
  778. int String::indexOf (int startIndex, StringRef other) const noexcept
  779. {
  780. if (other.isEmpty())
  781. return -1;
  782. auto t = text;
  783. for (int i = startIndex; --i >= 0;)
  784. {
  785. if (t.isEmpty())
  786. return -1;
  787. ++t;
  788. }
  789. auto found = t.indexOf (other.text);
  790. return found >= 0 ? found + startIndex : found;
  791. }
  792. int String::indexOfIgnoreCase (const int startIndex, StringRef other) const noexcept
  793. {
  794. if (other.isEmpty())
  795. return -1;
  796. auto t = text;
  797. for (int i = startIndex; --i >= 0;)
  798. {
  799. if (t.isEmpty())
  800. return -1;
  801. ++t;
  802. }
  803. auto found = CharacterFunctions::indexOfIgnoreCase (t, other.text);
  804. return found >= 0 ? found + startIndex : found;
  805. }
  806. int String::lastIndexOf (StringRef other) const noexcept
  807. {
  808. if (other.isNotEmpty())
  809. {
  810. auto len = other.length();
  811. int i = length() - len;
  812. if (i >= 0)
  813. {
  814. for (auto n = text + i; i >= 0; --i)
  815. {
  816. if (n.compareUpTo (other.text, len) == 0)
  817. return i;
  818. --n;
  819. }
  820. }
  821. }
  822. return -1;
  823. }
  824. int String::lastIndexOfIgnoreCase (StringRef other) const noexcept
  825. {
  826. if (other.isNotEmpty())
  827. {
  828. auto len = other.length();
  829. int i = length() - len;
  830. if (i >= 0)
  831. {
  832. for (auto n = text + i; i >= 0; --i)
  833. {
  834. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  835. return i;
  836. --n;
  837. }
  838. }
  839. }
  840. return -1;
  841. }
  842. int String::lastIndexOfAnyOf (StringRef charactersToLookFor, const bool ignoreCase) const noexcept
  843. {
  844. auto t = text;
  845. int last = -1;
  846. for (int i = 0; ! t.isEmpty(); ++i)
  847. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  848. last = i;
  849. return last;
  850. }
  851. bool String::contains (StringRef other) const noexcept
  852. {
  853. return indexOf (other) >= 0;
  854. }
  855. bool String::containsChar (const juce_wchar character) const noexcept
  856. {
  857. return text.indexOf (character) >= 0;
  858. }
  859. bool String::containsIgnoreCase (StringRef t) const noexcept
  860. {
  861. return indexOfIgnoreCase (t) >= 0;
  862. }
  863. int String::indexOfWholeWord (StringRef word) const noexcept
  864. {
  865. if (word.isNotEmpty())
  866. {
  867. auto t = text;
  868. auto wordLen = word.length();
  869. auto end = (int) t.length() - wordLen;
  870. for (int i = 0; i <= end; ++i)
  871. {
  872. if (t.compareUpTo (word.text, wordLen) == 0
  873. && (i == 0 || ! (t - 1).isLetterOrDigit())
  874. && ! (t + wordLen).isLetterOrDigit())
  875. return i;
  876. ++t;
  877. }
  878. }
  879. return -1;
  880. }
  881. int String::indexOfWholeWordIgnoreCase (StringRef word) const noexcept
  882. {
  883. if (word.isNotEmpty())
  884. {
  885. auto t = text;
  886. auto wordLen = word.length();
  887. auto end = (int) t.length() - wordLen;
  888. for (int i = 0; i <= end; ++i)
  889. {
  890. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  891. && (i == 0 || ! (t - 1).isLetterOrDigit())
  892. && ! (t + wordLen).isLetterOrDigit())
  893. return i;
  894. ++t;
  895. }
  896. }
  897. return -1;
  898. }
  899. bool String::containsWholeWord (StringRef wordToLookFor) const noexcept
  900. {
  901. return indexOfWholeWord (wordToLookFor) >= 0;
  902. }
  903. bool String::containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept
  904. {
  905. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  906. }
  907. //==============================================================================
  908. template <typename CharPointer>
  909. struct WildCardMatcher
  910. {
  911. static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  912. {
  913. for (;;)
  914. {
  915. auto wc = wildcard.getAndAdvance();
  916. if (wc == '*')
  917. return wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase);
  918. if (! characterMatches (wc, test.getAndAdvance(), ignoreCase))
  919. return false;
  920. if (wc == 0)
  921. return true;
  922. }
  923. }
  924. static bool characterMatches (const juce_wchar wc, const juce_wchar tc, const bool ignoreCase) noexcept
  925. {
  926. return (wc == tc) || (wc == '?' && tc != 0)
  927. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc));
  928. }
  929. static bool matchesAnywhere (const CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  930. {
  931. for (; ! test.isEmpty(); ++test)
  932. if (matches (wildcard, test, ignoreCase))
  933. return true;
  934. return false;
  935. }
  936. };
  937. bool String::matchesWildcard (StringRef wildcard, const bool ignoreCase) const noexcept
  938. {
  939. return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase);
  940. }
  941. //==============================================================================
  942. String String::repeatedString (StringRef stringToRepeat, int numberOfTimesToRepeat)
  943. {
  944. if (numberOfTimesToRepeat <= 0)
  945. return {};
  946. String result (PreallocationBytes (findByteOffsetOfEnd (stringToRepeat) * (size_t) numberOfTimesToRepeat));
  947. auto n = result.text;
  948. while (--numberOfTimesToRepeat >= 0)
  949. n.writeAll (stringToRepeat.text);
  950. return result;
  951. }
  952. String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  953. {
  954. jassert (padCharacter != 0);
  955. auto extraChars = minimumLength;
  956. auto end = text;
  957. while (! end.isEmpty())
  958. {
  959. --extraChars;
  960. ++end;
  961. }
  962. if (extraChars <= 0 || padCharacter == 0)
  963. return *this;
  964. auto currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  965. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  966. auto n = result.text;
  967. while (--extraChars >= 0)
  968. n.write (padCharacter);
  969. n.writeAll (text);
  970. return result;
  971. }
  972. String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  973. {
  974. jassert (padCharacter != 0);
  975. auto extraChars = minimumLength;
  976. CharPointerType end (text);
  977. while (! end.isEmpty())
  978. {
  979. --extraChars;
  980. ++end;
  981. }
  982. if (extraChars <= 0 || padCharacter == 0)
  983. return *this;
  984. auto currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  985. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  986. auto n = result.text;
  987. n.writeAll (text);
  988. while (--extraChars >= 0)
  989. n.write (padCharacter);
  990. n.writeNull();
  991. return result;
  992. }
  993. //==============================================================================
  994. String String::replaceSection (int index, int numCharsToReplace, StringRef stringToInsert) const
  995. {
  996. if (index < 0)
  997. {
  998. // a negative index to replace from?
  999. jassertfalse;
  1000. index = 0;
  1001. }
  1002. if (numCharsToReplace < 0)
  1003. {
  1004. // replacing a negative number of characters?
  1005. numCharsToReplace = 0;
  1006. jassertfalse;
  1007. }
  1008. auto insertPoint = text;
  1009. for (int i = 0; i < index; ++i)
  1010. {
  1011. if (insertPoint.isEmpty())
  1012. {
  1013. // replacing beyond the end of the string?
  1014. jassertfalse;
  1015. return *this + stringToInsert;
  1016. }
  1017. ++insertPoint;
  1018. }
  1019. auto startOfRemainder = insertPoint;
  1020. for (int i = 0; i < numCharsToReplace && ! startOfRemainder.isEmpty(); ++i)
  1021. ++startOfRemainder;
  1022. if (insertPoint == text && startOfRemainder.isEmpty())
  1023. return stringToInsert.text;
  1024. auto initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress());
  1025. auto newStringBytes = findByteOffsetOfEnd (stringToInsert);
  1026. auto remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress());
  1027. auto newTotalBytes = initialBytes + newStringBytes + remainderBytes;
  1028. if (newTotalBytes <= 0)
  1029. return {};
  1030. String result (PreallocationBytes ((size_t) newTotalBytes));
  1031. auto* dest = (char*) result.text.getAddress();
  1032. memcpy (dest, text.getAddress(), initialBytes);
  1033. dest += initialBytes;
  1034. memcpy (dest, stringToInsert.text.getAddress(), newStringBytes);
  1035. dest += newStringBytes;
  1036. memcpy (dest, startOfRemainder.getAddress(), remainderBytes);
  1037. dest += remainderBytes;
  1038. CharPointerType ((CharPointerType::CharType*) dest).writeNull();
  1039. return result;
  1040. }
  1041. String String::replace (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  1042. {
  1043. auto stringToReplaceLen = stringToReplace.length();
  1044. auto stringToInsertLen = stringToInsert.length();
  1045. int i = 0;
  1046. String result (*this);
  1047. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  1048. : result.indexOf (i, stringToReplace))) >= 0)
  1049. {
  1050. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  1051. i += stringToInsertLen;
  1052. }
  1053. return result;
  1054. }
  1055. String String::replaceFirstOccurrenceOf (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  1056. {
  1057. auto stringToReplaceLen = stringToReplace.length();
  1058. auto index = ignoreCase ? indexOfIgnoreCase (stringToReplace)
  1059. : indexOf (stringToReplace);
  1060. if (index >= 0)
  1061. return replaceSection (index, stringToReplaceLen, stringToInsert);
  1062. return *this;
  1063. }
  1064. struct StringCreationHelper
  1065. {
  1066. StringCreationHelper (size_t initialBytes) : allocatedBytes (initialBytes)
  1067. {
  1068. result.preallocateBytes (allocatedBytes);
  1069. dest = result.getCharPointer();
  1070. }
  1071. StringCreationHelper (const String::CharPointerType s)
  1072. : source (s), allocatedBytes (StringHolder::getAllocatedNumBytes (s))
  1073. {
  1074. result.preallocateBytes (allocatedBytes);
  1075. dest = result.getCharPointer();
  1076. }
  1077. void write (juce_wchar c)
  1078. {
  1079. bytesWritten += String::CharPointerType::getBytesRequiredFor (c);
  1080. if (bytesWritten > allocatedBytes)
  1081. {
  1082. allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16);
  1083. auto destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress());
  1084. result.preallocateBytes (allocatedBytes);
  1085. dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset);
  1086. }
  1087. dest.write (c);
  1088. }
  1089. String result;
  1090. String::CharPointerType source { nullptr }, dest { nullptr };
  1091. size_t allocatedBytes, bytesWritten = 0;
  1092. };
  1093. String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  1094. {
  1095. if (! containsChar (charToReplace))
  1096. return *this;
  1097. StringCreationHelper builder (text);
  1098. for (;;)
  1099. {
  1100. auto c = builder.source.getAndAdvance();
  1101. if (c == charToReplace)
  1102. c = charToInsert;
  1103. builder.write (c);
  1104. if (c == 0)
  1105. break;
  1106. }
  1107. return std::move (builder.result);
  1108. }
  1109. String String::replaceCharacters (StringRef charactersToReplace, StringRef charactersToInsertInstead) const
  1110. {
  1111. // Each character in the first string must have a matching one in the
  1112. // second, so the two strings must be the same length.
  1113. jassert (charactersToReplace.length() == charactersToInsertInstead.length());
  1114. StringCreationHelper builder (text);
  1115. for (;;)
  1116. {
  1117. auto c = builder.source.getAndAdvance();
  1118. auto index = charactersToReplace.text.indexOf (c);
  1119. if (index >= 0)
  1120. c = charactersToInsertInstead [index];
  1121. builder.write (c);
  1122. if (c == 0)
  1123. break;
  1124. }
  1125. return std::move (builder.result);
  1126. }
  1127. //==============================================================================
  1128. bool String::startsWith (StringRef other) const noexcept
  1129. {
  1130. return text.compareUpTo (other.text, other.length()) == 0;
  1131. }
  1132. bool String::startsWithIgnoreCase (StringRef other) const noexcept
  1133. {
  1134. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  1135. }
  1136. bool String::startsWithChar (const juce_wchar character) const noexcept
  1137. {
  1138. jassert (character != 0); // strings can't contain a null character!
  1139. return *text == character;
  1140. }
  1141. bool String::endsWithChar (const juce_wchar character) const noexcept
  1142. {
  1143. jassert (character != 0); // strings can't contain a null character!
  1144. if (text.isEmpty())
  1145. return false;
  1146. auto t = text.findTerminatingNull();
  1147. return *--t == character;
  1148. }
  1149. bool String::endsWith (StringRef other) const noexcept
  1150. {
  1151. auto end = text.findTerminatingNull();
  1152. auto otherEnd = other.text.findTerminatingNull();
  1153. while (end > text && otherEnd > other.text)
  1154. {
  1155. --end;
  1156. --otherEnd;
  1157. if (*end != *otherEnd)
  1158. return false;
  1159. }
  1160. return otherEnd == other.text;
  1161. }
  1162. bool String::endsWithIgnoreCase (StringRef other) const noexcept
  1163. {
  1164. auto end = text.findTerminatingNull();
  1165. auto otherEnd = other.text.findTerminatingNull();
  1166. while (end > text && otherEnd > other.text)
  1167. {
  1168. --end;
  1169. --otherEnd;
  1170. if (end.toLowerCase() != otherEnd.toLowerCase())
  1171. return false;
  1172. }
  1173. return otherEnd == other.text;
  1174. }
  1175. //==============================================================================
  1176. String String::toUpperCase() const
  1177. {
  1178. StringCreationHelper builder (text);
  1179. for (;;)
  1180. {
  1181. auto c = builder.source.toUpperCase();
  1182. builder.write (c);
  1183. if (c == 0)
  1184. break;
  1185. ++(builder.source);
  1186. }
  1187. return std::move (builder.result);
  1188. }
  1189. String String::toLowerCase() const
  1190. {
  1191. StringCreationHelper builder (text);
  1192. for (;;)
  1193. {
  1194. auto c = builder.source.toLowerCase();
  1195. builder.write (c);
  1196. if (c == 0)
  1197. break;
  1198. ++(builder.source);
  1199. }
  1200. return std::move (builder.result);
  1201. }
  1202. //==============================================================================
  1203. juce_wchar String::getLastCharacter() const noexcept
  1204. {
  1205. return isEmpty() ? juce_wchar() : text [length() - 1];
  1206. }
  1207. String String::substring (int start, const int end) const
  1208. {
  1209. if (start < 0)
  1210. start = 0;
  1211. if (end <= start)
  1212. return {};
  1213. int i = 0;
  1214. auto t1 = text;
  1215. while (i < start)
  1216. {
  1217. if (t1.isEmpty())
  1218. return {};
  1219. ++i;
  1220. ++t1;
  1221. }
  1222. auto t2 = t1;
  1223. while (i < end)
  1224. {
  1225. if (t2.isEmpty())
  1226. {
  1227. if (start == 0)
  1228. return *this;
  1229. break;
  1230. }
  1231. ++i;
  1232. ++t2;
  1233. }
  1234. return String (t1, t2);
  1235. }
  1236. String String::substring (int start) const
  1237. {
  1238. if (start <= 0)
  1239. return *this;
  1240. auto t = text;
  1241. while (--start >= 0)
  1242. {
  1243. if (t.isEmpty())
  1244. return {};
  1245. ++t;
  1246. }
  1247. return String (t);
  1248. }
  1249. String String::dropLastCharacters (const int numberToDrop) const
  1250. {
  1251. return String (text, (size_t) jmax (0, length() - numberToDrop));
  1252. }
  1253. String String::getLastCharacters (const int numCharacters) const
  1254. {
  1255. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  1256. }
  1257. String String::fromFirstOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1258. {
  1259. auto i = ignoreCase ? indexOfIgnoreCase (sub)
  1260. : indexOf (sub);
  1261. if (i < 0)
  1262. return {};
  1263. return substring (includeSubString ? i : i + sub.length());
  1264. }
  1265. String String::fromLastOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1266. {
  1267. auto i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1268. : lastIndexOf (sub);
  1269. if (i < 0)
  1270. return *this;
  1271. return substring (includeSubString ? i : i + sub.length());
  1272. }
  1273. String String::upToFirstOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1274. {
  1275. auto i = ignoreCase ? indexOfIgnoreCase (sub)
  1276. : indexOf (sub);
  1277. if (i < 0)
  1278. return *this;
  1279. return substring (0, includeSubString ? i + sub.length() : i);
  1280. }
  1281. String String::upToLastOccurrenceOf (StringRef sub, bool includeSubString, bool ignoreCase) const
  1282. {
  1283. auto i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1284. : lastIndexOf (sub);
  1285. if (i < 0)
  1286. return *this;
  1287. return substring (0, includeSubString ? i + sub.length() : i);
  1288. }
  1289. static bool isQuoteCharacter (juce_wchar c) noexcept
  1290. {
  1291. return c == '"' || c == '\'';
  1292. }
  1293. bool String::isQuotedString() const
  1294. {
  1295. return isQuoteCharacter (*text.findEndOfWhitespace());
  1296. }
  1297. String String::unquoted() const
  1298. {
  1299. if (! isQuoteCharacter (*text))
  1300. return *this;
  1301. auto len = length();
  1302. return substring (1, len - (isQuoteCharacter (text[len - 1]) ? 1 : 0));
  1303. }
  1304. String String::quoted (juce_wchar quoteCharacter) const
  1305. {
  1306. if (isEmpty())
  1307. return charToString (quoteCharacter) + quoteCharacter;
  1308. String t (*this);
  1309. if (! t.startsWithChar (quoteCharacter))
  1310. t = charToString (quoteCharacter) + t;
  1311. if (! t.endsWithChar (quoteCharacter))
  1312. t += quoteCharacter;
  1313. return t;
  1314. }
  1315. //==============================================================================
  1316. static String::CharPointerType findTrimmedEnd (const String::CharPointerType start,
  1317. String::CharPointerType end)
  1318. {
  1319. while (end > start)
  1320. {
  1321. if (! (--end).isWhitespace())
  1322. {
  1323. ++end;
  1324. break;
  1325. }
  1326. }
  1327. return end;
  1328. }
  1329. String String::trim() const
  1330. {
  1331. if (isNotEmpty())
  1332. {
  1333. auto start = text.findEndOfWhitespace();
  1334. auto end = start.findTerminatingNull();
  1335. auto trimmedEnd = findTrimmedEnd (start, end);
  1336. if (trimmedEnd <= start)
  1337. return {};
  1338. if (text < start || trimmedEnd < end)
  1339. return String (start, trimmedEnd);
  1340. }
  1341. return *this;
  1342. }
  1343. String String::trimStart() const
  1344. {
  1345. if (isNotEmpty())
  1346. {
  1347. auto t = text.findEndOfWhitespace();
  1348. if (t != text)
  1349. return String (t);
  1350. }
  1351. return *this;
  1352. }
  1353. String String::trimEnd() const
  1354. {
  1355. if (isNotEmpty())
  1356. {
  1357. auto end = text.findTerminatingNull();
  1358. auto trimmedEnd = findTrimmedEnd (text, end);
  1359. if (trimmedEnd < end)
  1360. return String (text, trimmedEnd);
  1361. }
  1362. return *this;
  1363. }
  1364. String String::trimCharactersAtStart (StringRef charactersToTrim) const
  1365. {
  1366. auto t = text;
  1367. while (charactersToTrim.text.indexOf (*t) >= 0)
  1368. ++t;
  1369. return t == text ? *this : String (t);
  1370. }
  1371. String String::trimCharactersAtEnd (StringRef charactersToTrim) const
  1372. {
  1373. if (isNotEmpty())
  1374. {
  1375. auto end = text.findTerminatingNull();
  1376. auto trimmedEnd = end;
  1377. while (trimmedEnd > text)
  1378. {
  1379. if (charactersToTrim.text.indexOf (*--trimmedEnd) < 0)
  1380. {
  1381. ++trimmedEnd;
  1382. break;
  1383. }
  1384. }
  1385. if (trimmedEnd < end)
  1386. return String (text, trimmedEnd);
  1387. }
  1388. return *this;
  1389. }
  1390. //==============================================================================
  1391. String String::retainCharacters (StringRef charactersToRetain) const
  1392. {
  1393. if (isEmpty())
  1394. return {};
  1395. StringCreationHelper builder (text);
  1396. for (;;)
  1397. {
  1398. auto c = builder.source.getAndAdvance();
  1399. if (charactersToRetain.text.indexOf (c) >= 0)
  1400. builder.write (c);
  1401. if (c == 0)
  1402. break;
  1403. }
  1404. builder.write (0);
  1405. return std::move (builder.result);
  1406. }
  1407. String String::removeCharacters (StringRef charactersToRemove) const
  1408. {
  1409. if (isEmpty())
  1410. return {};
  1411. StringCreationHelper builder (text);
  1412. for (;;)
  1413. {
  1414. auto c = builder.source.getAndAdvance();
  1415. if (charactersToRemove.text.indexOf (c) < 0)
  1416. builder.write (c);
  1417. if (c == 0)
  1418. break;
  1419. }
  1420. return std::move (builder.result);
  1421. }
  1422. String String::initialSectionContainingOnly (StringRef permittedCharacters) const
  1423. {
  1424. for (auto t = text; ! t.isEmpty(); ++t)
  1425. if (permittedCharacters.text.indexOf (*t) < 0)
  1426. return String (text, t);
  1427. return *this;
  1428. }
  1429. String String::initialSectionNotContaining (StringRef charactersToStopAt) const
  1430. {
  1431. for (auto t = text; ! t.isEmpty(); ++t)
  1432. if (charactersToStopAt.text.indexOf (*t) >= 0)
  1433. return String (text, t);
  1434. return *this;
  1435. }
  1436. bool String::containsOnly (StringRef chars) const noexcept
  1437. {
  1438. for (auto t = text; ! t.isEmpty();)
  1439. if (chars.text.indexOf (t.getAndAdvance()) < 0)
  1440. return false;
  1441. return true;
  1442. }
  1443. bool String::containsAnyOf (StringRef chars) const noexcept
  1444. {
  1445. for (auto t = text; ! t.isEmpty();)
  1446. if (chars.text.indexOf (t.getAndAdvance()) >= 0)
  1447. return true;
  1448. return false;
  1449. }
  1450. bool String::containsNonWhitespaceChars() const noexcept
  1451. {
  1452. for (auto t = text; ! t.isEmpty(); ++t)
  1453. if (! t.isWhitespace())
  1454. return true;
  1455. return false;
  1456. }
  1457. String String::formattedRaw (const char* pf, ...)
  1458. {
  1459. size_t bufferSize = 256;
  1460. for (;;)
  1461. {
  1462. va_list args;
  1463. va_start (args, pf);
  1464. #if JUCE_ANDROID
  1465. HeapBlock<char> temp (bufferSize);
  1466. int num = (int) vsnprintf (temp.get(), bufferSize - 1, pf, args);
  1467. if (num >= static_cast<int> (bufferSize))
  1468. num = -1;
  1469. #else
  1470. String wideCharVersion (pf);
  1471. HeapBlock<wchar_t> temp (bufferSize);
  1472. const int num = (int)
  1473. #if JUCE_WINDOWS
  1474. _vsnwprintf
  1475. #else
  1476. vswprintf
  1477. #endif
  1478. (temp.get(), bufferSize - 1, wideCharVersion.toWideCharPointer(), args);
  1479. #endif
  1480. va_end (args);
  1481. if (num > 0)
  1482. return String (temp.get());
  1483. bufferSize += 256;
  1484. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  1485. break; // returns -1 because of an error rather than because it needs more space.
  1486. }
  1487. return {};
  1488. }
  1489. //==============================================================================
  1490. int String::getIntValue() const noexcept { return text.getIntValue32(); }
  1491. int64 String::getLargeIntValue() const noexcept { return text.getIntValue64(); }
  1492. float String::getFloatValue() const noexcept { return (float) getDoubleValue(); }
  1493. double String::getDoubleValue() const noexcept { return text.getDoubleValue(); }
  1494. int String::getTrailingIntValue() const noexcept
  1495. {
  1496. int n = 0;
  1497. int mult = 1;
  1498. auto t = text.findTerminatingNull();
  1499. while (--t >= text)
  1500. {
  1501. if (! t.isDigit())
  1502. {
  1503. if (*t == '-')
  1504. n = -n;
  1505. break;
  1506. }
  1507. n += static_cast<juce_wchar> (mult) * (*t - '0');
  1508. mult *= 10;
  1509. }
  1510. return n;
  1511. }
  1512. static const char hexDigits[] = "0123456789abcdef";
  1513. template <typename Type>
  1514. static String hexToString (Type v)
  1515. {
  1516. String::CharPointerType::CharType buffer[32];
  1517. auto* end = buffer + numElementsInArray (buffer) - 1;
  1518. auto* t = end;
  1519. *t = 0;
  1520. do
  1521. {
  1522. *--t = hexDigits [(int) (v & 15)];
  1523. v = static_cast<Type> (v >> 4);
  1524. } while (v != 0);
  1525. return String (String::CharPointerType (t),
  1526. String::CharPointerType (end));
  1527. }
  1528. String String::createHex (uint8 n) { return hexToString (n); }
  1529. String String::createHex (uint16 n) { return hexToString (n); }
  1530. String String::createHex (uint32 n) { return hexToString (n); }
  1531. String String::createHex (uint64 n) { return hexToString (n); }
  1532. String String::toHexString (const void* const d, const int size, const int groupSize)
  1533. {
  1534. if (size <= 0)
  1535. return {};
  1536. int numChars = (size * 2) + 2;
  1537. if (groupSize > 0)
  1538. numChars += size / groupSize;
  1539. String s (PreallocationBytes ((size_t) numChars * sizeof (CharPointerType::CharType)));
  1540. auto* data = static_cast<const unsigned char*> (d);
  1541. auto dest = s.text;
  1542. for (int i = 0; i < size; ++i)
  1543. {
  1544. const unsigned char nextByte = *data++;
  1545. dest.write ((juce_wchar) hexDigits [nextByte >> 4]);
  1546. dest.write ((juce_wchar) hexDigits [nextByte & 0xf]);
  1547. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  1548. dest.write ((juce_wchar) ' ');
  1549. }
  1550. dest.writeNull();
  1551. return s;
  1552. }
  1553. int String::getHexValue32() const noexcept { return CharacterFunctions::HexParser<int> ::parse (text); }
  1554. int64 String::getHexValue64() const noexcept { return CharacterFunctions::HexParser<int64>::parse (text); }
  1555. //==============================================================================
  1556. static String getStringFromWindows1252Codepage (const char* data, size_t num)
  1557. {
  1558. HeapBlock<juce_wchar> unicode (num + 1);
  1559. for (size_t i = 0; i < num; ++i)
  1560. unicode[i] = CharacterFunctions::getUnicodeCharFromWindows1252Codepage ((uint8) data[i]);
  1561. unicode[num] = 0;
  1562. return CharPointer_UTF32 (unicode);
  1563. }
  1564. String String::createStringFromData (const void* const unknownData, int size)
  1565. {
  1566. auto* data = static_cast<const uint8*> (unknownData);
  1567. if (size <= 0 || data == nullptr)
  1568. return {};
  1569. if (size == 1)
  1570. return charToString ((juce_wchar) data[0]);
  1571. if (CharPointer_UTF16::isByteOrderMarkBigEndian (data)
  1572. || CharPointer_UTF16::isByteOrderMarkLittleEndian (data))
  1573. {
  1574. const int numChars = size / 2 - 1;
  1575. StringCreationHelper builder ((size_t) numChars);
  1576. auto src = reinterpret_cast<const uint16*> (data + 2);
  1577. if (CharPointer_UTF16::isByteOrderMarkBigEndian (data))
  1578. {
  1579. for (int i = 0; i < numChars; ++i)
  1580. builder.write ((juce_wchar) ByteOrder::swapIfLittleEndian (src[i]));
  1581. }
  1582. else
  1583. {
  1584. for (int i = 0; i < numChars; ++i)
  1585. builder.write ((juce_wchar) ByteOrder::swapIfBigEndian (src[i]));
  1586. }
  1587. builder.write (0);
  1588. return std::move (builder.result);
  1589. }
  1590. auto* start = (const char*) data;
  1591. if (size >= 3 && CharPointer_UTF8::isByteOrderMark (data))
  1592. {
  1593. start += 3;
  1594. size -= 3;
  1595. }
  1596. if (CharPointer_UTF8::isValidString (start, size))
  1597. return String (CharPointer_UTF8 (start),
  1598. CharPointer_UTF8 (start + size));
  1599. return getStringFromWindows1252Codepage (start, (size_t) size);
  1600. }
  1601. //==============================================================================
  1602. static const juce_wchar emptyChar = 0;
  1603. template <class CharPointerType_Src, class CharPointerType_Dest>
  1604. struct StringEncodingConverter
  1605. {
  1606. static CharPointerType_Dest convert (const String& s)
  1607. {
  1608. auto& source = const_cast<String&> (s);
  1609. using DestChar = typename CharPointerType_Dest::CharType;
  1610. if (source.isEmpty())
  1611. return CharPointerType_Dest (reinterpret_cast<const DestChar*> (&emptyChar));
  1612. CharPointerType_Src text (source.getCharPointer());
  1613. auto extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text) + sizeof (typename CharPointerType_Dest::CharType);
  1614. auto endOffset = (text.sizeInBytes() + 3) & ~3u; // the new string must be word-aligned or many Windows
  1615. // functions will fail to read it correctly!
  1616. source.preallocateBytes (endOffset + extraBytesNeeded);
  1617. text = source.getCharPointer();
  1618. void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset);
  1619. const CharPointerType_Dest extraSpace (static_cast<DestChar*> (newSpace));
  1620. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  1621. auto bytesToClear = (size_t) jmin ((int) extraBytesNeeded, 4);
  1622. zeromem (addBytesToPointer (newSpace, extraBytesNeeded - bytesToClear), bytesToClear);
  1623. #endif
  1624. CharPointerType_Dest (extraSpace).writeAll (text);
  1625. return extraSpace;
  1626. }
  1627. };
  1628. template <>
  1629. struct StringEncodingConverter<CharPointer_UTF8, CharPointer_UTF8>
  1630. {
  1631. static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 (reinterpret_cast<CharPointer_UTF8::CharType*> (source.getCharPointer().getAddress())); }
  1632. };
  1633. template <>
  1634. struct StringEncodingConverter<CharPointer_UTF16, CharPointer_UTF16>
  1635. {
  1636. static CharPointer_UTF16 convert (const String& source) noexcept { return CharPointer_UTF16 (reinterpret_cast<CharPointer_UTF16::CharType*> (source.getCharPointer().getAddress())); }
  1637. };
  1638. template <>
  1639. struct StringEncodingConverter<CharPointer_UTF32, CharPointer_UTF32>
  1640. {
  1641. static CharPointer_UTF32 convert (const String& source) noexcept { return CharPointer_UTF32 (reinterpret_cast<CharPointer_UTF32::CharType*> (source.getCharPointer().getAddress())); }
  1642. };
  1643. CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF8 >::convert (*this); }
  1644. CharPointer_UTF16 String::toUTF16() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF16>::convert (*this); }
  1645. CharPointer_UTF32 String::toUTF32() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF32>::convert (*this); }
  1646. const char* String::toRawUTF8() const
  1647. {
  1648. return toUTF8().getAddress();
  1649. }
  1650. const wchar_t* String::toWideCharPointer() const
  1651. {
  1652. return StringEncodingConverter<CharPointerType, CharPointer_wchar_t>::convert (*this).getAddress();
  1653. }
  1654. std::string String::toStdString() const
  1655. {
  1656. return std::string (toRawUTF8());
  1657. }
  1658. //==============================================================================
  1659. template <class CharPointerType_Src, class CharPointerType_Dest>
  1660. struct StringCopier
  1661. {
  1662. static size_t copyToBuffer (const CharPointerType_Src source, typename CharPointerType_Dest::CharType* const buffer, const size_t maxBufferSizeBytes)
  1663. {
  1664. jassert (((ssize_t) maxBufferSizeBytes) >= 0); // keep this value positive!
  1665. if (buffer == nullptr)
  1666. return CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType);
  1667. return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes);
  1668. }
  1669. };
  1670. size_t String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1671. {
  1672. return StringCopier<CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1673. }
  1674. size_t String::copyToUTF16 (CharPointer_UTF16::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1675. {
  1676. return StringCopier<CharPointerType, CharPointer_UTF16>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1677. }
  1678. size_t String::copyToUTF32 (CharPointer_UTF32::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1679. {
  1680. return StringCopier<CharPointerType, CharPointer_UTF32>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1681. }
  1682. //==============================================================================
  1683. size_t String::getNumBytesAsUTF8() const noexcept
  1684. {
  1685. return CharPointer_UTF8::getBytesRequiredFor (text);
  1686. }
  1687. String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  1688. {
  1689. if (buffer != nullptr)
  1690. {
  1691. if (bufferSizeBytes < 0)
  1692. return String (CharPointer_UTF8 (buffer));
  1693. if (bufferSizeBytes > 0)
  1694. {
  1695. jassert (CharPointer_UTF8::isValidString (buffer, bufferSizeBytes));
  1696. return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes));
  1697. }
  1698. }
  1699. return {};
  1700. }
  1701. #if JUCE_MSVC
  1702. #pragma warning (pop)
  1703. #endif
  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. };
  2393. static StringTests stringUnitTests;
  2394. #endif
  2395. } // namespace juce