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.

2454 lines
87KB

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