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.

2702 lines
96KB

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