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.

2932 lines
105KB

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