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.

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