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.

2698 lines
96KB

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