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.

2711 lines
96KB

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