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.

2436 lines
86KB

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