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.

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