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.

2391 lines
85KB

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