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.

2713 lines
97KB

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