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.

2547 lines
90KB

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