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.

2444 lines
87KB

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