Audio plugin host https://kx.studio/carla
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.

String.cpp 66KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066
  1. /*
  2. ==============================================================================
  3. This file is part of the Water library.
  4. Copyright (c) 2016 ROLI Ltd.
  5. Copyright (C) 2017-2019 Filipe Coelho <falktx@falktx.com>
  6. Permission is granted to use this software under the terms of the ISC license
  7. http://www.isc.org/downloads/software-support-policy/isc-license/
  8. Permission to use, copy, modify, and/or distribute this software for any
  9. purpose with or without fee is hereby granted, provided that the above
  10. copyright notice and this permission notice appear in all copies.
  11. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  12. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  13. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  14. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  15. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  16. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  17. OF THIS SOFTWARE.
  18. ==============================================================================
  19. */
  20. #include "String.h"
  21. #include "NewLine.h"
  22. #include "../maths/MathsFunctions.h"
  23. #include "../memory/HeapBlock.h"
  24. #include "../streams/OutputStream.h"
  25. #include "CarlaJuceUtils.hpp"
  26. #include <locale>
  27. #include <iostream>
  28. #ifdef CARLA_OS_MAC
  29. // FIXME
  30. // # import <CoreData/CoreData.h>
  31. #endif
  32. // #import <Carbon/UnicodeConverter.h>
  33. namespace water {
  34. //==============================================================================
  35. // (Mirrors the structure of StringHolder, but without the atomic member, so can be statically constructed)
  36. struct EmptyString
  37. {
  38. int refCount;
  39. size_t allocatedBytes;
  40. String::CharPointerType::CharType text;
  41. };
  42. static const EmptyString emptyString = { 0x3fffffff, sizeof (String::CharPointerType::CharType), '\0' };
  43. //==============================================================================
  44. class StringHolder
  45. {
  46. public:
  47. StringHolder() WATER_DELETED_FUNCTION;
  48. typedef String::CharPointerType CharPointerType;
  49. typedef String::CharPointerType::CharType CharType;
  50. //==============================================================================
  51. static CharPointerType createUninitialisedBytes (size_t numBytes)
  52. {
  53. numBytes = (numBytes + 3) & ~(size_t) 3;
  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 CharPointerType (&(emptyString.text));
  64. const size_t bytesNeeded = sizeof (CharType) + CharPointerType::getBytesRequiredFor (text);
  65. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  66. CharPointerType (dest).writeAll (text);
  67. return dest;
  68. }
  69. template <class CharPointer>
  70. static CharPointerType createFromCharPointer (const CharPointer text, size_t maxChars)
  71. {
  72. if (text.getAddress() == nullptr || text.isEmpty() || maxChars == 0)
  73. return CharPointerType (&(emptyString.text));
  74. CharPointer end (text);
  75. size_t numChars = 0;
  76. size_t bytesNeeded = sizeof (CharType);
  77. while (numChars < maxChars && ! end.isEmpty())
  78. {
  79. bytesNeeded += CharPointerType::getBytesRequiredFor (end.getAndAdvance());
  80. ++numChars;
  81. }
  82. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  83. CharPointerType (dest).writeWithCharLimit (text, (int) numChars + 1);
  84. return dest;
  85. }
  86. template <class CharPointer>
  87. static CharPointerType createFromCharPointer (const CharPointer start, const CharPointer end)
  88. {
  89. if (start.getAddress() == nullptr || start.isEmpty())
  90. return CharPointerType (&(emptyString.text));
  91. CharPointer e (start);
  92. int numChars = 0;
  93. size_t bytesNeeded = sizeof (CharType);
  94. while (e < end && ! e.isEmpty())
  95. {
  96. bytesNeeded += CharPointerType::getBytesRequiredFor (e.getAndAdvance());
  97. ++numChars;
  98. }
  99. const CharPointerType dest (createUninitialisedBytes (bytesNeeded));
  100. CharPointerType (dest).writeWithCharLimit (start, numChars + 1);
  101. return dest;
  102. }
  103. static CharPointerType createFromCharPointer (const CharPointerType start, const CharPointerType end)
  104. {
  105. if (start.getAddress() == nullptr || start.isEmpty())
  106. return CharPointerType (&(emptyString.text));
  107. const size_t numBytes = (size_t) (reinterpret_cast<const char*> (end.getAddress())
  108. - reinterpret_cast<const char*> (start.getAddress()));
  109. const CharPointerType dest (createUninitialisedBytes (numBytes + sizeof (CharType)));
  110. memcpy (dest.getAddress(), start, numBytes);
  111. dest.getAddress()[numBytes / sizeof (CharType)] = 0;
  112. return dest;
  113. }
  114. static CharPointerType createFromFixedLength (const char* const src, const size_t numChars)
  115. {
  116. const CharPointerType dest (createUninitialisedBytes (numChars * sizeof (CharType) + sizeof (CharType)));
  117. CharPointerType (dest).writeWithCharLimit (CharPointer_UTF8 (src), (int) (numChars + 1));
  118. return dest;
  119. }
  120. //==============================================================================
  121. static void retain (const CharPointerType text) noexcept
  122. {
  123. StringHolder* const b = bufferFromText (text);
  124. if (b != (StringHolder*) &emptyString)
  125. ++(b->refCount);
  126. }
  127. static inline void release (StringHolder* const b) noexcept
  128. {
  129. if (b != (StringHolder*) &emptyString)
  130. if (--(b->refCount) == -1)
  131. delete[] reinterpret_cast<char*> (b);
  132. }
  133. static void release (const CharPointerType text) noexcept
  134. {
  135. release (bufferFromText (text));
  136. }
  137. static inline int getReferenceCount (const CharPointerType text) noexcept
  138. {
  139. return bufferFromText (text)->refCount.get() + 1;
  140. }
  141. //==============================================================================
  142. static CharPointerType makeUniqueWithByteSize (const CharPointerType text, size_t numBytes)
  143. {
  144. StringHolder* const b = bufferFromText (text);
  145. if (b == (StringHolder*) &emptyString)
  146. {
  147. CharPointerType newText (createUninitialisedBytes (numBytes));
  148. newText.writeNull();
  149. return newText;
  150. }
  151. if (b->allocatedNumBytes >= numBytes && b->refCount.get() <= 0)
  152. return text;
  153. CharPointerType newText (createUninitialisedBytes (jmax (b->allocatedNumBytes, numBytes)));
  154. memcpy (newText.getAddress(), text.getAddress(), b->allocatedNumBytes);
  155. release (b);
  156. return newText;
  157. }
  158. static size_t getAllocatedNumBytes (const CharPointerType text) noexcept
  159. {
  160. return bufferFromText (text)->allocatedNumBytes;
  161. }
  162. //==============================================================================
  163. Atomic<int> refCount;
  164. size_t allocatedNumBytes;
  165. CharType text[1];
  166. private:
  167. static inline StringHolder* bufferFromText (const CharPointerType text) noexcept
  168. {
  169. // (Can't use offsetof() here because of warnings about this not being a POD)
  170. return reinterpret_cast<StringHolder*> (reinterpret_cast<char*> (text.getAddress())
  171. - (reinterpret_cast<size_t> (reinterpret_cast<StringHolder*> (1)->text) - 1));
  172. }
  173. };
  174. //==============================================================================
  175. String::String() noexcept : text (&(emptyString.text))
  176. {
  177. }
  178. String::~String() noexcept
  179. {
  180. StringHolder::release (text);
  181. }
  182. String::String (const String& other) noexcept : text (other.text)
  183. {
  184. StringHolder::retain (text);
  185. }
  186. void String::swapWith (String& other) noexcept
  187. {
  188. std::swap (text, other.text);
  189. }
  190. void String::clear() noexcept
  191. {
  192. StringHolder::release (text);
  193. text = &(emptyString.text);
  194. }
  195. String& String::operator= (const String& other) noexcept
  196. {
  197. StringHolder::retain (other.text);
  198. StringHolder::release (text.atomicSwap (other.text));
  199. return *this;
  200. }
  201. inline String::PreallocationBytes::PreallocationBytes (const size_t num) noexcept : numBytes (num) {}
  202. String::String (const PreallocationBytes& preallocationSize)
  203. : text (StringHolder::createUninitialisedBytes (preallocationSize.numBytes + sizeof (CharPointerType::CharType)))
  204. {
  205. }
  206. void String::preallocateBytes (const size_t numBytesNeeded)
  207. {
  208. text = StringHolder::makeUniqueWithByteSize (text, numBytesNeeded + sizeof (CharPointerType::CharType));
  209. }
  210. int String::getReferenceCount() const noexcept
  211. {
  212. return StringHolder::getReferenceCount (text);
  213. }
  214. //==============================================================================
  215. String::String (const char* const t)
  216. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t)))
  217. {
  218. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  219. that contains values greater than 127. These can NOT be correctly converted to unicode
  220. because there's no way for the String class to know what encoding was used to
  221. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  222. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  223. string to the String class - so for example if your source data is actually UTF-8,
  224. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  225. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  226. you use UTF-8 with escape characters in your source code to represent extended characters,
  227. because there's no other way to represent these strings in a way that isn't dependent on
  228. the compiler, source code editor and platform.
  229. */
  230. CARLA_SAFE_ASSERT (t == nullptr || CharPointer_UTF8::isValidString (t, std::numeric_limits<int>::max()));
  231. }
  232. String::String (const char* const t, const size_t maxChars)
  233. : text (StringHolder::createFromCharPointer (CharPointer_UTF8 (t), maxChars))
  234. {
  235. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  236. that contains values greater than 127. These can NOT be correctly converted to unicode
  237. because there's no way for the String class to know what encoding was used to
  238. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  239. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  240. string to the String class - so for example if your source data is actually UTF-8,
  241. you'd call String (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  242. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  243. you use UTF-8 with escape characters in your source code to represent extended characters,
  244. because there's no other way to represent these strings in a way that isn't dependent on
  245. the compiler, source code editor and platform.
  246. */
  247. CARLA_SAFE_ASSERT (t == nullptr || CharPointer_UTF8::isValidString (t, (int) maxChars));
  248. }
  249. String::String (const CharPointer_UTF8 t) : text (StringHolder::createFromCharPointer (t)) {}
  250. String::String (const CharPointer_UTF8 t, const size_t maxChars) : text (StringHolder::createFromCharPointer (t, maxChars)) {}
  251. String::String (const CharPointer_UTF8 start, const CharPointer_UTF8 end) : text (StringHolder::createFromCharPointer (start, end)) {}
  252. String::String (const std::string& s) : text (StringHolder::createFromFixedLength (s.data(), s.size())) {}
  253. String::String (StringRef s) : text (StringHolder::createFromCharPointer (s.text)) {}
  254. String String::charToString (const water_uchar character)
  255. {
  256. String result (PreallocationBytes (CharPointerType::getBytesRequiredFor (character)));
  257. CharPointerType t (result.text);
  258. t.write (character);
  259. t.writeNull();
  260. return result;
  261. }
  262. //==============================================================================
  263. namespace NumberToStringConverters
  264. {
  265. static char* numberToString (char* t, uint64 v) noexcept
  266. {
  267. return printDigits (t, v);
  268. }
  269. static char* numberToString (char* t, const int n) noexcept
  270. {
  271. if (n >= 0)
  272. return printDigits (t, static_cast<unsigned int> (n));
  273. // NB: this needs to be careful not to call -std::numeric_limits<int>::min(),
  274. // which has undefined behaviour
  275. t = printDigits (t, static_cast<unsigned int> (-(n + 1)) + 1);
  276. *--t = '-';
  277. return t;
  278. }
  279. static char* numberToString (char* t, const unsigned int v) noexcept
  280. {
  281. return printDigits (t, v);
  282. }
  283. static char* numberToString (char* t, const long n) noexcept
  284. {
  285. if (n >= 0)
  286. return printDigits (t, static_cast<unsigned long> (n));
  287. t = printDigits (t, static_cast<unsigned long> (-(n + 1)) + 1);
  288. *--t = '-';
  289. return t;
  290. }
  291. static char* numberToString (char* t, const unsigned long v) noexcept
  292. {
  293. return printDigits (t, v);
  294. }
  295. struct StackArrayStream : public std::basic_streambuf<char, std::char_traits<char> >
  296. {
  297. explicit StackArrayStream (char* d)
  298. {
  299. static const std::locale classicLocale (std::locale::classic());
  300. imbue (classicLocale);
  301. setp (d, d + charsNeededForDouble);
  302. }
  303. size_t writeDouble (double n, int numDecPlaces)
  304. {
  305. {
  306. std::ostream o (this);
  307. if (numDecPlaces > 0)
  308. o.precision ((std::streamsize) numDecPlaces);
  309. o << n;
  310. }
  311. return (size_t) (pptr() - pbase());
  312. }
  313. };
  314. static char* doubleToString (char* buffer, const int numChars, double n, int numDecPlaces, size_t& len) noexcept
  315. {
  316. if (numDecPlaces > 0 && numDecPlaces < 7 && n > -1.0e20 && n < 1.0e20)
  317. {
  318. char* const end = buffer + numChars;
  319. char* t = end;
  320. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  321. *--t = (char) 0;
  322. while (numDecPlaces >= 0 || v > 0)
  323. {
  324. if (numDecPlaces == 0)
  325. *--t = '.';
  326. *--t = (char) ('0' + (v % 10));
  327. v /= 10;
  328. --numDecPlaces;
  329. }
  330. if (n < 0)
  331. *--t = '-';
  332. len = (size_t) (end - t - 1);
  333. return t;
  334. }
  335. StackArrayStream strm (buffer);
  336. len = strm.writeDouble (n, numDecPlaces);
  337. wassert (len <= charsNeededForDouble);
  338. return buffer;
  339. }
  340. template <typename IntegerType>
  341. static String::CharPointerType createFromInteger (const IntegerType number)
  342. {
  343. char buffer [charsNeededForInt];
  344. char* const end = buffer + numElementsInArray (buffer);
  345. char* const start = numberToString (end, number);
  346. return StringHolder::createFromFixedLength (start, (size_t) (end - start - 1));
  347. }
  348. static String::CharPointerType createFromDouble (const double number, const int numberOfDecimalPlaces)
  349. {
  350. char buffer [charsNeededForDouble];
  351. size_t len;
  352. char* const start = doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  353. return StringHolder::createFromFixedLength (start, len);
  354. }
  355. }
  356. //==============================================================================
  357. String::String (const int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  358. String::String (const unsigned int number) : text (NumberToStringConverters::createFromInteger (number)) {}
  359. String::String (const short number) : text (NumberToStringConverters::createFromInteger ((int) number)) {}
  360. String::String (const unsigned short number) : text (NumberToStringConverters::createFromInteger ((unsigned int) number)) {}
  361. String::String (const int64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  362. String::String (const uint64 number) : text (NumberToStringConverters::createFromInteger (number)) {}
  363. String::String (const long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  364. String::String (const unsigned long number) : text (NumberToStringConverters::createFromInteger (number)) {}
  365. String::String (const float number) : text (NumberToStringConverters::createFromDouble ((double) number, 0)) {}
  366. String::String (const double number) : text (NumberToStringConverters::createFromDouble (number, 0)) {}
  367. String::String (const float number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble ((double) number, numberOfDecimalPlaces)) {}
  368. String::String (const double number, const int numberOfDecimalPlaces) : text (NumberToStringConverters::createFromDouble (number, numberOfDecimalPlaces)) {}
  369. //==============================================================================
  370. int String::length() const noexcept
  371. {
  372. return (int) text.length();
  373. }
  374. static size_t findByteOffsetOfEnd (String::CharPointerType text) noexcept
  375. {
  376. return (size_t) (((char*) text.findTerminatingNull().getAddress()) - (char*) text.getAddress());
  377. }
  378. size_t String::getByteOffsetOfEnd() const noexcept
  379. {
  380. return findByteOffsetOfEnd (text);
  381. }
  382. water_uchar String::operator[] (int index) const noexcept
  383. {
  384. wassert (index == 0 || (index > 0 && index <= (int) text.lengthUpTo ((size_t) index + 1)));
  385. return text [index];
  386. }
  387. template <typename Type>
  388. struct HashGenerator
  389. {
  390. template <typename CharPointer>
  391. static Type calculate (CharPointer t) noexcept
  392. {
  393. Type result = Type();
  394. while (! t.isEmpty())
  395. result = ((Type) multiplier) * result + (Type) t.getAndAdvance();
  396. return result;
  397. }
  398. enum { multiplier = sizeof (Type) > 4 ? 101 : 31 };
  399. };
  400. int String::hashCode() const noexcept { return HashGenerator<int> ::calculate (text); }
  401. int64 String::hashCode64() const noexcept { return HashGenerator<int64> ::calculate (text); }
  402. size_t String::hash() const noexcept { return HashGenerator<size_t> ::calculate (text); }
  403. //==============================================================================
  404. bool operator== (const String& s1, const String& s2) noexcept { return s1.compare (s2) == 0; }
  405. bool operator!= (const String& s1, const String& s2) noexcept { return s1.compare (s2) != 0; }
  406. bool operator== (const String& s1, const char* s2) noexcept { return s1.compare (s2) == 0; }
  407. bool operator!= (const String& s1, const char* s2) noexcept { return s1.compare (s2) != 0; }
  408. bool operator== (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) == 0; }
  409. bool operator!= (const String& s1, StringRef s2) noexcept { return s1.getCharPointer().compare (s2.text) != 0; }
  410. bool operator== (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) == 0; }
  411. bool operator!= (const String& s1, const CharPointer_UTF8 s2) noexcept { return s1.getCharPointer().compare (s2) != 0; }
  412. bool operator> (const String& s1, const String& s2) noexcept { return s1.compare (s2) > 0; }
  413. bool operator< (const String& s1, const String& s2) noexcept { return s1.compare (s2) < 0; }
  414. bool operator>= (const String& s1, const String& s2) noexcept { return s1.compare (s2) >= 0; }
  415. bool operator<= (const String& s1, const String& s2) noexcept { return s1.compare (s2) <= 0; }
  416. bool String::equalsIgnoreCase (const char* const t) const noexcept
  417. {
  418. return t != nullptr ? text.compareIgnoreCase (CharPointer_UTF8 (t)) == 0
  419. : isEmpty();
  420. }
  421. bool String::equalsIgnoreCase (StringRef t) const noexcept
  422. {
  423. return text.compareIgnoreCase (t.text) == 0;
  424. }
  425. bool String::equalsIgnoreCase (const String& other) const noexcept
  426. {
  427. return text == other.text
  428. || text.compareIgnoreCase (other.text) == 0;
  429. }
  430. int String::compare (const String& other) const noexcept { return (text == other.text) ? 0 : text.compare (other.text); }
  431. int String::compare (const char* const other) const noexcept { return text.compare (CharPointer_UTF8 (other)); }
  432. int String::compareIgnoreCase (const String& other) const noexcept { return (text == other.text) ? 0 : text.compareIgnoreCase (other.text); }
  433. static int stringCompareRight (String::CharPointerType s1, String::CharPointerType s2) noexcept
  434. {
  435. for (int bias = 0;;)
  436. {
  437. const water_uchar c1 = s1.getAndAdvance();
  438. const bool isDigit1 = CharacterFunctions::isDigit (c1);
  439. const water_uchar c2 = s2.getAndAdvance();
  440. const bool isDigit2 = CharacterFunctions::isDigit (c2);
  441. if (! (isDigit1 || isDigit2)) return bias;
  442. if (! isDigit1) return -1;
  443. if (! isDigit2) return 1;
  444. if (c1 != c2 && bias == 0)
  445. bias = c1 < c2 ? -1 : 1;
  446. wassert (c1 != 0 && c2 != 0);
  447. }
  448. }
  449. static int stringCompareLeft (String::CharPointerType s1, String::CharPointerType s2) noexcept
  450. {
  451. for (;;)
  452. {
  453. const water_uchar c1 = s1.getAndAdvance();
  454. const bool isDigit1 = CharacterFunctions::isDigit (c1);
  455. const water_uchar c2 = s2.getAndAdvance();
  456. const bool isDigit2 = CharacterFunctions::isDigit (c2);
  457. if (! (isDigit1 || isDigit2)) return 0;
  458. if (! isDigit1) return -1;
  459. if (! isDigit2) return 1;
  460. if (c1 < c2) return -1;
  461. if (c1 > c2) return 1;
  462. }
  463. }
  464. static int naturalStringCompare (String::CharPointerType s1, String::CharPointerType s2, bool isCaseSensitive) noexcept
  465. {
  466. bool firstLoop = true;
  467. for (;;)
  468. {
  469. const bool hasSpace1 = s1.isWhitespace();
  470. const bool hasSpace2 = s2.isWhitespace();
  471. if ((! firstLoop) && (hasSpace1 ^ hasSpace2))
  472. return hasSpace2 ? 1 : -1;
  473. firstLoop = false;
  474. if (hasSpace1) s1 = s1.findEndOfWhitespace();
  475. if (hasSpace2) s2 = s2.findEndOfWhitespace();
  476. if (s1.isDigit() && s2.isDigit())
  477. {
  478. const int result = (*s1 == '0' || *s2 == '0') ? stringCompareLeft (s1, s2)
  479. : stringCompareRight (s1, s2);
  480. if (result != 0)
  481. return result;
  482. }
  483. water_uchar c1 = s1.getAndAdvance();
  484. water_uchar c2 = s2.getAndAdvance();
  485. if (c1 != c2 && ! isCaseSensitive)
  486. {
  487. c1 = CharacterFunctions::toUpperCase (c1);
  488. c2 = CharacterFunctions::toUpperCase (c2);
  489. }
  490. if (c1 == c2)
  491. {
  492. if (c1 == 0)
  493. return 0;
  494. }
  495. else
  496. {
  497. const bool isAlphaNum1 = CharacterFunctions::isLetterOrDigit (c1);
  498. const bool isAlphaNum2 = CharacterFunctions::isLetterOrDigit (c2);
  499. if (isAlphaNum2 && ! isAlphaNum1) return -1;
  500. if (isAlphaNum1 && ! isAlphaNum2) return 1;
  501. return c1 < c2 ? -1 : 1;
  502. }
  503. wassert (c1 != 0 && c2 != 0);
  504. }
  505. }
  506. int String::compareNatural (StringRef other, bool isCaseSensitive) const noexcept
  507. {
  508. return naturalStringCompare (getCharPointer(), other.text, isCaseSensitive);
  509. }
  510. //==============================================================================
  511. void String::append (const String& textToAppend, size_t maxCharsToTake)
  512. {
  513. appendCharPointer (this == &textToAppend ? String (textToAppend).text
  514. : textToAppend.text, maxCharsToTake);
  515. }
  516. void String::appendCharPointer (const CharPointerType textToAppend)
  517. {
  518. appendCharPointer (textToAppend, textToAppend.findTerminatingNull());
  519. }
  520. void String::appendCharPointer (const CharPointerType startOfTextToAppend,
  521. const CharPointerType endOfTextToAppend)
  522. {
  523. wassert (startOfTextToAppend.getAddress() != nullptr && endOfTextToAppend.getAddress() != nullptr);
  524. const int extraBytesNeeded = getAddressDifference (endOfTextToAppend.getAddress(),
  525. startOfTextToAppend.getAddress());
  526. wassert (extraBytesNeeded >= 0);
  527. if (extraBytesNeeded > 0)
  528. {
  529. const size_t byteOffsetOfNull = getByteOffsetOfEnd();
  530. preallocateBytes (byteOffsetOfNull + (size_t) extraBytesNeeded);
  531. CharPointerType::CharType* const newStringStart = addBytesToPointer (text.getAddress(), (int) byteOffsetOfNull);
  532. memcpy (newStringStart, startOfTextToAppend.getAddress(), (size_t) extraBytesNeeded);
  533. CharPointerType (addBytesToPointer (newStringStart, extraBytesNeeded)).writeNull();
  534. }
  535. }
  536. String& String::operator+= (const char* const t)
  537. {
  538. appendCharPointer (CharPointer_UTF8 (t)); // (using UTF8 here triggers a faster code-path than ascii)
  539. return *this;
  540. }
  541. String& String::operator+= (const String& other)
  542. {
  543. if (isEmpty())
  544. return operator= (other);
  545. if (this == &other)
  546. return operator+= (String (*this));
  547. appendCharPointer (other.text);
  548. return *this;
  549. }
  550. String& String::operator+= (StringRef other)
  551. {
  552. return operator+= (String (other));
  553. }
  554. String& String::operator+= (const char ch)
  555. {
  556. const char asString[] = { ch, 0 };
  557. return operator+= (asString);
  558. }
  559. String& String::operator+= (const water_uchar ch)
  560. {
  561. return operator+= (charToString(ch));
  562. }
  563. namespace StringHelpers
  564. {
  565. template <typename T>
  566. inline String& operationAddAssign (String& str, const T number)
  567. {
  568. char buffer [(sizeof(T) * 8) / 2];
  569. char* end = buffer + numElementsInArray (buffer);
  570. char* start = NumberToStringConverters::numberToString (end, number);
  571. str.appendCharPointer (String::CharPointerType (start), String::CharPointerType (end));
  572. return str;
  573. }
  574. }
  575. String& String::operator+= (const int number) { return StringHelpers::operationAddAssign<int> (*this, number); }
  576. String& String::operator+= (const int64 number) { return StringHelpers::operationAddAssign<int64> (*this, number); }
  577. String& String::operator+= (const uint64 number) { return StringHelpers::operationAddAssign<uint64> (*this, number); }
  578. //==============================================================================
  579. String operator+ (const char* const s1, const String& s2) { String s (s1); return s += s2; }
  580. String operator+ (const char s1, const String& s2) { return String::charToString ((water_uchar) (uint8) s1) + s2; }
  581. String operator+ (String s1, const String& s2) { return s1 += s2; }
  582. String operator+ (String s1, const char* const s2) { return s1 += s2; }
  583. String operator+ (String s1, const char s2) { return s1 += s2; }
  584. String operator+ (const water_uchar s1, const String& s2) { return String::charToString (s1) + s2; }
  585. String operator+ (String s1, const water_uchar s2) { return s1 += s2; }
  586. String& operator<< (String& s1, const water_uchar s2) { return s1 += s2; }
  587. String& operator<< (String& s1, const char s2) { return s1 += s2; }
  588. String& operator<< (String& s1, const char* const s2) { return s1 += s2; }
  589. String& operator<< (String& s1, const String& s2) { return s1 += s2; }
  590. String& operator<< (String& s1, StringRef s2) { return s1 += s2; }
  591. String& operator<< (String& s1, const int number) { return s1 += number; }
  592. String& operator<< (String& s1, const short number) { return s1 += (int) number; }
  593. String& operator<< (String& s1, const unsigned short number) { return s1 += (uint64) number; }
  594. String& operator<< (String& s1, const long number) { return s1 += String (number); }
  595. String& operator<< (String& s1, const unsigned long number) { return s1 += String (number); }
  596. String& operator<< (String& s1, const int64 number) { return s1 += String (number); }
  597. String& operator<< (String& s1, const uint64 number) { return s1 += String (number); }
  598. String& operator<< (String& s1, const float number) { return s1 += String (number); }
  599. String& operator<< (String& s1, const double number) { return s1 += String (number); }
  600. OutputStream& operator<< (OutputStream& stream, const String& text)
  601. {
  602. return operator<< (stream, StringRef (text));
  603. }
  604. OutputStream& operator<< (OutputStream& stream, StringRef text)
  605. {
  606. const size_t numBytes = CharPointer_UTF8::getBytesRequiredFor (text.text);
  607. stream.write (text.text.getAddress(), numBytes);
  608. return stream;
  609. }
  610. //==============================================================================
  611. int String::indexOfChar (const water_uchar character) const noexcept
  612. {
  613. return text.indexOf (character);
  614. }
  615. int String::indexOfChar (const int startIndex, const water_uchar character) const noexcept
  616. {
  617. CharPointerType t (text);
  618. for (int i = 0; ! t.isEmpty(); ++i)
  619. {
  620. if (i >= startIndex)
  621. {
  622. if (t.getAndAdvance() == character)
  623. return i;
  624. }
  625. else
  626. {
  627. ++t;
  628. }
  629. }
  630. return -1;
  631. }
  632. int String::lastIndexOfChar (const water_uchar character) const noexcept
  633. {
  634. CharPointerType t (text);
  635. int last = -1;
  636. for (int i = 0; ! t.isEmpty(); ++i)
  637. if (t.getAndAdvance() == character)
  638. last = i;
  639. return last;
  640. }
  641. int String::indexOfAnyOf (StringRef charactersToLookFor, const int startIndex, const bool ignoreCase) const noexcept
  642. {
  643. CharPointerType t (text);
  644. for (int i = 0; ! t.isEmpty(); ++i)
  645. {
  646. if (i >= startIndex)
  647. {
  648. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  649. return i;
  650. }
  651. else
  652. {
  653. ++t;
  654. }
  655. }
  656. return -1;
  657. }
  658. int String::indexOf (StringRef other) const noexcept
  659. {
  660. return other.isEmpty() ? 0 : text.indexOf (other.text);
  661. }
  662. int String::indexOfIgnoreCase (StringRef other) const noexcept
  663. {
  664. return other.isEmpty() ? 0 : CharacterFunctions::indexOfIgnoreCase (text, other.text);
  665. }
  666. int String::indexOf (const int startIndex, StringRef other) const noexcept
  667. {
  668. if (other.isEmpty())
  669. return -1;
  670. CharPointerType t (text);
  671. for (int i = startIndex; --i >= 0;)
  672. {
  673. if (t.isEmpty())
  674. return -1;
  675. ++t;
  676. }
  677. int found = t.indexOf (other.text);
  678. if (found >= 0)
  679. found += startIndex;
  680. return found;
  681. }
  682. int String::indexOfIgnoreCase (const int startIndex, StringRef other) const noexcept
  683. {
  684. if (other.isEmpty())
  685. return -1;
  686. CharPointerType t (text);
  687. for (int i = startIndex; --i >= 0;)
  688. {
  689. if (t.isEmpty())
  690. return -1;
  691. ++t;
  692. }
  693. int found = CharacterFunctions::indexOfIgnoreCase (t, other.text);
  694. if (found >= 0)
  695. found += startIndex;
  696. return found;
  697. }
  698. int String::lastIndexOf (StringRef other) const noexcept
  699. {
  700. if (other.isNotEmpty())
  701. {
  702. const int len = other.length();
  703. int i = length() - len;
  704. if (i >= 0)
  705. {
  706. for (CharPointerType n (text + i); i >= 0; --i)
  707. {
  708. if (n.compareUpTo (other.text, len) == 0)
  709. return i;
  710. --n;
  711. }
  712. }
  713. }
  714. return -1;
  715. }
  716. int String::lastIndexOfIgnoreCase (StringRef other) const noexcept
  717. {
  718. if (other.isNotEmpty())
  719. {
  720. const int len = other.length();
  721. int i = length() - len;
  722. if (i >= 0)
  723. {
  724. for (CharPointerType n (text + i); i >= 0; --i)
  725. {
  726. if (n.compareIgnoreCaseUpTo (other.text, len) == 0)
  727. return i;
  728. --n;
  729. }
  730. }
  731. }
  732. return -1;
  733. }
  734. int String::lastIndexOfAnyOf (StringRef charactersToLookFor, const bool ignoreCase) const noexcept
  735. {
  736. CharPointerType t (text);
  737. int last = -1;
  738. for (int i = 0; ! t.isEmpty(); ++i)
  739. if (charactersToLookFor.text.indexOf (t.getAndAdvance(), ignoreCase) >= 0)
  740. last = i;
  741. return last;
  742. }
  743. bool String::contains (StringRef other) const noexcept
  744. {
  745. return indexOf (other) >= 0;
  746. }
  747. bool String::containsChar (const water_uchar character) const noexcept
  748. {
  749. return text.indexOf (character) >= 0;
  750. }
  751. bool String::containsIgnoreCase (StringRef t) const noexcept
  752. {
  753. return indexOfIgnoreCase (t) >= 0;
  754. }
  755. int String::indexOfWholeWord (StringRef word) const noexcept
  756. {
  757. if (word.isNotEmpty())
  758. {
  759. CharPointerType t (text);
  760. const int wordLen = word.length();
  761. const int end = (int) t.length() - wordLen;
  762. for (int i = 0; i <= end; ++i)
  763. {
  764. if (t.compareUpTo (word.text, wordLen) == 0
  765. && (i == 0 || ! (t - 1).isLetterOrDigit())
  766. && ! (t + wordLen).isLetterOrDigit())
  767. return i;
  768. ++t;
  769. }
  770. }
  771. return -1;
  772. }
  773. int String::indexOfWholeWordIgnoreCase (StringRef word) const noexcept
  774. {
  775. if (word.isNotEmpty())
  776. {
  777. CharPointerType t (text);
  778. const int wordLen = word.length();
  779. const int end = (int) t.length() - wordLen;
  780. for (int i = 0; i <= end; ++i)
  781. {
  782. if (t.compareIgnoreCaseUpTo (word.text, wordLen) == 0
  783. && (i == 0 || ! (t - 1).isLetterOrDigit())
  784. && ! (t + wordLen).isLetterOrDigit())
  785. return i;
  786. ++t;
  787. }
  788. }
  789. return -1;
  790. }
  791. bool String::containsWholeWord (StringRef wordToLookFor) const noexcept
  792. {
  793. return indexOfWholeWord (wordToLookFor) >= 0;
  794. }
  795. bool String::containsWholeWordIgnoreCase (StringRef wordToLookFor) const noexcept
  796. {
  797. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  798. }
  799. //==============================================================================
  800. template <typename CharPointer>
  801. struct WildCardMatcher
  802. {
  803. static bool matches (CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  804. {
  805. for (;;)
  806. {
  807. const water_uchar wc = wildcard.getAndAdvance();
  808. if (wc == '*')
  809. return wildcard.isEmpty() || matchesAnywhere (wildcard, test, ignoreCase);
  810. if (! characterMatches (wc, test.getAndAdvance(), ignoreCase))
  811. return false;
  812. if (wc == 0)
  813. return true;
  814. }
  815. }
  816. static bool characterMatches (const water_uchar wc, const water_uchar tc, const bool ignoreCase) noexcept
  817. {
  818. return (wc == tc) || (wc == '?' && tc != 0)
  819. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (tc));
  820. }
  821. static bool matchesAnywhere (const CharPointer wildcard, CharPointer test, const bool ignoreCase) noexcept
  822. {
  823. for (; ! test.isEmpty(); ++test)
  824. if (matches (wildcard, test, ignoreCase))
  825. return true;
  826. return false;
  827. }
  828. };
  829. bool String::matchesWildcard (StringRef wildcard, const bool ignoreCase) const noexcept
  830. {
  831. return WildCardMatcher<CharPointerType>::matches (wildcard.text, text, ignoreCase);
  832. }
  833. //==============================================================================
  834. String String::repeatedString (StringRef stringToRepeat, int numberOfTimesToRepeat)
  835. {
  836. if (numberOfTimesToRepeat <= 0)
  837. return String();
  838. String result (PreallocationBytes (findByteOffsetOfEnd (stringToRepeat) * (size_t) numberOfTimesToRepeat));
  839. CharPointerType n (result.text);
  840. while (--numberOfTimesToRepeat >= 0)
  841. n.writeAll (stringToRepeat.text);
  842. return result;
  843. }
  844. String String::paddedLeft (const water_uchar padCharacter, int minimumLength) const
  845. {
  846. wassert (padCharacter != 0);
  847. int extraChars = minimumLength;
  848. CharPointerType end (text);
  849. while (! end.isEmpty())
  850. {
  851. --extraChars;
  852. ++end;
  853. }
  854. if (extraChars <= 0 || padCharacter == 0)
  855. return *this;
  856. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  857. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  858. CharPointerType n (result.text);
  859. while (--extraChars >= 0)
  860. n.write (padCharacter);
  861. n.writeAll (text);
  862. return result;
  863. }
  864. String String::paddedRight (const water_uchar padCharacter, int minimumLength) const
  865. {
  866. CARLA_SAFE_ASSERT_RETURN (padCharacter != 0, *this);
  867. int extraChars = minimumLength;
  868. CharPointerType end (text);
  869. while (! end.isEmpty())
  870. {
  871. --extraChars;
  872. ++end;
  873. }
  874. if (extraChars <= 0 || padCharacter == 0)
  875. return *this;
  876. const size_t currentByteSize = (size_t) (((char*) end.getAddress()) - (char*) text.getAddress());
  877. String result (PreallocationBytes (currentByteSize + (size_t) extraChars * CharPointerType::getBytesRequiredFor (padCharacter)));
  878. CharPointerType n (result.text);
  879. n.writeAll (text);
  880. while (--extraChars >= 0)
  881. n.write (padCharacter);
  882. n.writeNull();
  883. return result;
  884. }
  885. //==============================================================================
  886. String String::replaceSection (int index, int numCharsToReplace, StringRef stringToInsert) const
  887. {
  888. if (index < 0)
  889. {
  890. // a negative index to replace from?
  891. wassertfalse;
  892. index = 0;
  893. }
  894. if (numCharsToReplace < 0)
  895. {
  896. // replacing a negative number of characters?
  897. numCharsToReplace = 0;
  898. wassertfalse;
  899. }
  900. CharPointerType insertPoint (text);
  901. for (int i = 0; i < index; ++i)
  902. {
  903. if (insertPoint.isEmpty())
  904. {
  905. // replacing beyond the end of the string?
  906. wassertfalse;
  907. return *this + stringToInsert;
  908. }
  909. ++insertPoint;
  910. }
  911. CharPointerType startOfRemainder (insertPoint);
  912. for (int i = 0; i < numCharsToReplace && ! startOfRemainder.isEmpty(); ++i)
  913. ++startOfRemainder;
  914. if (insertPoint == text && startOfRemainder.isEmpty())
  915. return stringToInsert.text;
  916. const size_t initialBytes = (size_t) (((char*) insertPoint.getAddress()) - (char*) text.getAddress());
  917. const size_t newStringBytes = findByteOffsetOfEnd (stringToInsert);
  918. const size_t remainderBytes = (size_t) (((char*) startOfRemainder.findTerminatingNull().getAddress()) - (char*) startOfRemainder.getAddress());
  919. const size_t newTotalBytes = initialBytes + newStringBytes + remainderBytes;
  920. if (newTotalBytes <= 0)
  921. return String();
  922. String result (PreallocationBytes ((size_t) newTotalBytes));
  923. char* dest = (char*) result.text.getAddress();
  924. memcpy (dest, text.getAddress(), initialBytes);
  925. dest += initialBytes;
  926. memcpy (dest, stringToInsert.text.getAddress(), newStringBytes);
  927. dest += newStringBytes;
  928. memcpy (dest, startOfRemainder.getAddress(), remainderBytes);
  929. dest += remainderBytes;
  930. CharPointerType ((CharPointerType::CharType*) dest).writeNull();
  931. return result;
  932. }
  933. String String::replace (StringRef stringToReplace, StringRef stringToInsert, const bool ignoreCase) const
  934. {
  935. const int stringToReplaceLen = stringToReplace.length();
  936. const int stringToInsertLen = stringToInsert.length();
  937. int i = 0;
  938. String result (*this);
  939. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  940. : result.indexOf (i, stringToReplace))) >= 0)
  941. {
  942. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  943. i += stringToInsertLen;
  944. }
  945. return result;
  946. }
  947. class StringCreationHelper
  948. {
  949. public:
  950. StringCreationHelper (const size_t initialBytes)
  951. : source (nullptr), dest (nullptr), allocatedBytes (initialBytes), bytesWritten (0)
  952. {
  953. result.preallocateBytes (allocatedBytes);
  954. dest = result.getCharPointer();
  955. }
  956. StringCreationHelper (const String::CharPointerType s)
  957. : source (s), dest (nullptr), allocatedBytes (StringHolder::getAllocatedNumBytes (s)), bytesWritten (0)
  958. {
  959. result.preallocateBytes (allocatedBytes);
  960. dest = result.getCharPointer();
  961. }
  962. void write (water_uchar c)
  963. {
  964. bytesWritten += String::CharPointerType::getBytesRequiredFor (c);
  965. if (bytesWritten > allocatedBytes)
  966. {
  967. allocatedBytes += jmax ((size_t) 8, allocatedBytes / 16);
  968. const size_t destOffset = (size_t) (((char*) dest.getAddress()) - (char*) result.getCharPointer().getAddress());
  969. result.preallocateBytes (allocatedBytes);
  970. dest = addBytesToPointer (result.getCharPointer().getAddress(), (int) destOffset);
  971. }
  972. dest.write (c);
  973. }
  974. String result;
  975. String::CharPointerType source;
  976. private:
  977. String::CharPointerType dest;
  978. size_t allocatedBytes, bytesWritten;
  979. };
  980. String String::replaceCharacter (const water_uchar charToReplace, const water_uchar charToInsert) const
  981. {
  982. if (! containsChar (charToReplace))
  983. return *this;
  984. StringCreationHelper builder (text);
  985. for (;;)
  986. {
  987. water_uchar c = builder.source.getAndAdvance();
  988. if (c == charToReplace)
  989. c = charToInsert;
  990. builder.write (c);
  991. if (c == 0)
  992. break;
  993. }
  994. return builder.result;
  995. }
  996. String String::replaceCharacters (StringRef charactersToReplace, StringRef charactersToInsertInstead) const
  997. {
  998. // Each character in the first string must have a matching one in the
  999. // second, so the two strings must be the same length.
  1000. wassert (charactersToReplace.length() == charactersToInsertInstead.length());
  1001. StringCreationHelper builder (text);
  1002. for (;;)
  1003. {
  1004. water_uchar c = builder.source.getAndAdvance();
  1005. const int index = charactersToReplace.text.indexOf (c);
  1006. if (index >= 0)
  1007. c = charactersToInsertInstead [index];
  1008. builder.write (c);
  1009. if (c == 0)
  1010. break;
  1011. }
  1012. return builder.result;
  1013. }
  1014. //==============================================================================
  1015. bool String::startsWith (StringRef other) const noexcept
  1016. {
  1017. return text.compareUpTo (other.text, other.length()) == 0;
  1018. }
  1019. bool String::startsWithIgnoreCase (StringRef other) const noexcept
  1020. {
  1021. return text.compareIgnoreCaseUpTo (other.text, other.length()) == 0;
  1022. }
  1023. bool String::startsWithChar (const water_uchar character) const noexcept
  1024. {
  1025. // strings can't contain a null character!
  1026. CARLA_SAFE_ASSERT_RETURN (character != 0, false);
  1027. return *text == character;
  1028. }
  1029. bool String::endsWithChar (const water_uchar character) const noexcept
  1030. {
  1031. // strings can't contain a null character!
  1032. CARLA_SAFE_ASSERT_RETURN (character != 0, false);
  1033. if (text.isEmpty())
  1034. return false;
  1035. CharPointerType t (text.findTerminatingNull());
  1036. return *--t == character;
  1037. }
  1038. bool String::endsWith (StringRef other) const noexcept
  1039. {
  1040. CharPointerType end (text.findTerminatingNull());
  1041. CharPointerType otherEnd (other.text.findTerminatingNull());
  1042. while (end > text && otherEnd > other.text)
  1043. {
  1044. --end;
  1045. --otherEnd;
  1046. if (*end != *otherEnd)
  1047. return false;
  1048. }
  1049. return otherEnd == other.text;
  1050. }
  1051. bool String::endsWithIgnoreCase (StringRef other) const noexcept
  1052. {
  1053. CharPointerType end (text.findTerminatingNull());
  1054. CharPointerType otherEnd (other.text.findTerminatingNull());
  1055. while (end > text && otherEnd > other.text)
  1056. {
  1057. --end;
  1058. --otherEnd;
  1059. if (end.toLowerCase() != otherEnd.toLowerCase())
  1060. return false;
  1061. }
  1062. return otherEnd == other.text;
  1063. }
  1064. //==============================================================================
  1065. String String::toUpperCase() const
  1066. {
  1067. StringCreationHelper builder (text);
  1068. for (;;)
  1069. {
  1070. const water_uchar c = builder.source.toUpperCase();
  1071. builder.write (c);
  1072. if (c == 0)
  1073. break;
  1074. ++(builder.source);
  1075. }
  1076. return builder.result;
  1077. }
  1078. String String::toLowerCase() const
  1079. {
  1080. StringCreationHelper builder (text);
  1081. for (;;)
  1082. {
  1083. const water_uchar c = builder.source.toLowerCase();
  1084. builder.write (c);
  1085. if (c == 0)
  1086. break;
  1087. ++(builder.source);
  1088. }
  1089. return builder.result;
  1090. }
  1091. //==============================================================================
  1092. water_uchar String::getLastCharacter() const noexcept
  1093. {
  1094. return isEmpty() ? water_uchar() : text [length() - 1];
  1095. }
  1096. String String::substring (int start, const int end) const
  1097. {
  1098. if (start < 0)
  1099. start = 0;
  1100. if (end <= start)
  1101. return String();
  1102. int i = 0;
  1103. CharPointerType t1 (text);
  1104. while (i < start)
  1105. {
  1106. if (t1.isEmpty())
  1107. return String();
  1108. ++i;
  1109. ++t1;
  1110. }
  1111. CharPointerType t2 (t1);
  1112. while (i < end)
  1113. {
  1114. if (t2.isEmpty())
  1115. {
  1116. if (start == 0)
  1117. return *this;
  1118. break;
  1119. }
  1120. ++i;
  1121. ++t2;
  1122. }
  1123. return String (t1, t2);
  1124. }
  1125. String String::substring (int start) const
  1126. {
  1127. if (start <= 0)
  1128. return *this;
  1129. CharPointerType t (text);
  1130. while (--start >= 0)
  1131. {
  1132. if (t.isEmpty())
  1133. return String();
  1134. ++t;
  1135. }
  1136. return String (t);
  1137. }
  1138. String String::dropLastCharacters (const int numberToDrop) const
  1139. {
  1140. return String (text, (size_t) jmax (0, length() - numberToDrop));
  1141. }
  1142. String String::getLastCharacters (const int numCharacters) const
  1143. {
  1144. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  1145. }
  1146. String String::fromFirstOccurrenceOf (StringRef sub,
  1147. const bool includeSubString,
  1148. const bool ignoreCase) const
  1149. {
  1150. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1151. : indexOf (sub);
  1152. if (i < 0)
  1153. return String();
  1154. return substring (includeSubString ? i : i + sub.length());
  1155. }
  1156. String String::fromLastOccurrenceOf (StringRef sub,
  1157. const bool includeSubString,
  1158. const bool ignoreCase) const
  1159. {
  1160. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1161. : lastIndexOf (sub);
  1162. if (i < 0)
  1163. return *this;
  1164. return substring (includeSubString ? i : i + sub.length());
  1165. }
  1166. String String::upToFirstOccurrenceOf (StringRef sub,
  1167. const bool includeSubString,
  1168. const bool ignoreCase) const
  1169. {
  1170. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  1171. : indexOf (sub);
  1172. if (i < 0)
  1173. return *this;
  1174. return substring (0, includeSubString ? i + sub.length() : i);
  1175. }
  1176. String String::upToLastOccurrenceOf (StringRef sub,
  1177. const bool includeSubString,
  1178. const bool ignoreCase) const
  1179. {
  1180. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  1181. : lastIndexOf (sub);
  1182. if (i < 0)
  1183. return *this;
  1184. return substring (0, includeSubString ? i + sub.length() : i);
  1185. }
  1186. bool String::isQuotedString() const
  1187. {
  1188. const water_uchar trimmedStart = trimStart()[0];
  1189. return trimmedStart == '"'
  1190. || trimmedStart == '\'';
  1191. }
  1192. String String::unquoted() const
  1193. {
  1194. const int len = length();
  1195. if (len == 0)
  1196. return String();
  1197. const water_uchar lastChar = text [len - 1];
  1198. const int dropAtStart = (*text == '"' || *text == '\'') ? 1 : 0;
  1199. const int dropAtEnd = (lastChar == '"' || lastChar == '\'') ? 1 : 0;
  1200. return substring (dropAtStart, len - dropAtEnd);
  1201. }
  1202. String String::quoted (water_uchar quoteCharacter) const
  1203. {
  1204. if (isEmpty())
  1205. return charToString (quoteCharacter) + quoteCharacter;
  1206. String t (*this);
  1207. if (! t.startsWithChar (quoteCharacter))
  1208. t = charToString (quoteCharacter) + t;
  1209. if (! t.endsWithChar (quoteCharacter))
  1210. t += quoteCharacter;
  1211. return t;
  1212. }
  1213. //==============================================================================
  1214. static String::CharPointerType findTrimmedEnd (const String::CharPointerType start,
  1215. String::CharPointerType end)
  1216. {
  1217. while (end > start)
  1218. {
  1219. if (! (--end).isWhitespace())
  1220. {
  1221. ++end;
  1222. break;
  1223. }
  1224. }
  1225. return end;
  1226. }
  1227. String String::trim() const
  1228. {
  1229. if (isNotEmpty())
  1230. {
  1231. CharPointerType start (text.findEndOfWhitespace());
  1232. const CharPointerType end (start.findTerminatingNull());
  1233. CharPointerType trimmedEnd (findTrimmedEnd (start, end));
  1234. if (trimmedEnd <= start)
  1235. return String();
  1236. if (text < start || trimmedEnd < end)
  1237. return String (start, trimmedEnd);
  1238. }
  1239. return *this;
  1240. }
  1241. String String::trimStart() const
  1242. {
  1243. if (isNotEmpty())
  1244. {
  1245. const CharPointerType t (text.findEndOfWhitespace());
  1246. if (t != text)
  1247. return String (t);
  1248. }
  1249. return *this;
  1250. }
  1251. String String::trimEnd() const
  1252. {
  1253. if (isNotEmpty())
  1254. {
  1255. const CharPointerType end (text.findTerminatingNull());
  1256. CharPointerType trimmedEnd (findTrimmedEnd (text, end));
  1257. if (trimmedEnd < end)
  1258. return String (text, trimmedEnd);
  1259. }
  1260. return *this;
  1261. }
  1262. String String::trimCharactersAtStart (StringRef charactersToTrim) const
  1263. {
  1264. CharPointerType t (text);
  1265. while (charactersToTrim.text.indexOf (*t) >= 0)
  1266. ++t;
  1267. return t == text ? *this : String (t);
  1268. }
  1269. String String::trimCharactersAtEnd (StringRef charactersToTrim) const
  1270. {
  1271. if (isNotEmpty())
  1272. {
  1273. const CharPointerType end (text.findTerminatingNull());
  1274. CharPointerType trimmedEnd (end);
  1275. while (trimmedEnd > text)
  1276. {
  1277. if (charactersToTrim.text.indexOf (*--trimmedEnd) < 0)
  1278. {
  1279. ++trimmedEnd;
  1280. break;
  1281. }
  1282. }
  1283. if (trimmedEnd < end)
  1284. return String (text, trimmedEnd);
  1285. }
  1286. return *this;
  1287. }
  1288. //==============================================================================
  1289. String String::retainCharacters (StringRef charactersToRetain) const
  1290. {
  1291. if (isEmpty())
  1292. return String();
  1293. StringCreationHelper builder (text);
  1294. for (;;)
  1295. {
  1296. water_uchar c = builder.source.getAndAdvance();
  1297. if (charactersToRetain.text.indexOf (c) >= 0)
  1298. builder.write (c);
  1299. if (c == 0)
  1300. break;
  1301. }
  1302. builder.write (0);
  1303. return builder.result;
  1304. }
  1305. String String::removeCharacters (StringRef charactersToRemove) const
  1306. {
  1307. if (isEmpty())
  1308. return String();
  1309. StringCreationHelper builder (text);
  1310. for (;;)
  1311. {
  1312. water_uchar c = builder.source.getAndAdvance();
  1313. if (charactersToRemove.text.indexOf (c) < 0)
  1314. builder.write (c);
  1315. if (c == 0)
  1316. break;
  1317. }
  1318. return builder.result;
  1319. }
  1320. String String::initialSectionContainingOnly (StringRef permittedCharacters) const
  1321. {
  1322. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1323. if (permittedCharacters.text.indexOf (*t) < 0)
  1324. return String (text, t);
  1325. return *this;
  1326. }
  1327. String String::initialSectionNotContaining (StringRef charactersToStopAt) const
  1328. {
  1329. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1330. if (charactersToStopAt.text.indexOf (*t) >= 0)
  1331. return String (text, t);
  1332. return *this;
  1333. }
  1334. bool String::containsOnly (StringRef chars) const noexcept
  1335. {
  1336. for (CharPointerType t (text); ! t.isEmpty();)
  1337. if (chars.text.indexOf (t.getAndAdvance()) < 0)
  1338. return false;
  1339. return true;
  1340. }
  1341. bool String::containsAnyOf (StringRef chars) const noexcept
  1342. {
  1343. for (CharPointerType t (text); ! t.isEmpty();)
  1344. if (chars.text.indexOf (t.getAndAdvance()) >= 0)
  1345. return true;
  1346. return false;
  1347. }
  1348. bool String::containsNonWhitespaceChars() const noexcept
  1349. {
  1350. for (CharPointerType t (text); ! t.isEmpty(); ++t)
  1351. if (! t.isWhitespace())
  1352. return true;
  1353. return false;
  1354. }
  1355. //=====================================================================================================================
  1356. static String getStringFromWindows1252Codepage (const char* data, size_t num)
  1357. {
  1358. HeapBlock<char> unicode;
  1359. CARLA_SAFE_ASSERT_RETURN(unicode.malloc(num + 1), String());
  1360. for (size_t i = 0; i < num; ++i)
  1361. unicode[i] = CharacterFunctions::getUnicodeCharFromWindows1252Codepage ((uint8) data[i]);
  1362. unicode[num] = 0;
  1363. return CharPointer_UTF8 (unicode);
  1364. }
  1365. String String::createStringFromData (const void* const unknownData, int size)
  1366. {
  1367. const uint8* const data = static_cast<const uint8*> (unknownData);
  1368. if (size <= 0 || data == nullptr)
  1369. return String();
  1370. if (size == 1)
  1371. return charToString ((water_uchar) data[0]);
  1372. const char* start = (const char*) data;
  1373. if (size >= 3 && CharPointer_UTF8::isByteOrderMark (data))
  1374. {
  1375. start += 3;
  1376. size -= 3;
  1377. }
  1378. if (CharPointer_UTF8::isValidString (start, size))
  1379. return String (CharPointer_UTF8 (start),
  1380. CharPointer_UTF8 (start + size));
  1381. return getStringFromWindows1252Codepage (start, (size_t) size);
  1382. }
  1383. // Note! The format parameter here MUST NOT be a reference, otherwise MS's va_start macro fails to work (but still compiles).
  1384. String String::formatted (const String pf, ... )
  1385. {
  1386. size_t bufferSize = 256;
  1387. HeapBlock<char> temp;
  1388. CARLA_SAFE_ASSERT_RETURN(temp.malloc(bufferSize), String());
  1389. for (;;)
  1390. {
  1391. va_list args;
  1392. va_start (args, pf);
  1393. // FIXME - needed?
  1394. temp.clear (bufferSize);
  1395. const int num = vsnprintf (temp.getData(), bufferSize - 1, pf.toRawUTF8(), args);
  1396. va_end (args);
  1397. if (num > 0)
  1398. return String (temp);
  1399. bufferSize += 256;
  1400. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vsnprintf repeatedly
  1401. break; // returns -1 because of an error rather than because it needs more space.
  1402. temp.realloc (bufferSize);
  1403. }
  1404. return String();
  1405. }
  1406. //==============================================================================
  1407. int String::getIntValue() const noexcept { return text.getIntValue32(); }
  1408. int64 String::getLargeIntValue() const noexcept { return text.getIntValue64(); }
  1409. float String::getFloatValue() const noexcept { return (float) getDoubleValue(); }
  1410. double String::getDoubleValue() const noexcept { return text.getDoubleValue(); }
  1411. int String::getTrailingIntValue() const noexcept
  1412. {
  1413. int n = 0;
  1414. int mult = 1;
  1415. CharPointerType t (text.findTerminatingNull());
  1416. while (--t >= text)
  1417. {
  1418. if (! t.isDigit())
  1419. {
  1420. if (*t == '-')
  1421. n = -n;
  1422. break;
  1423. }
  1424. n += mult * (*t - '0');
  1425. mult *= 10;
  1426. }
  1427. return n;
  1428. }
  1429. static const char hexDigits[] = "0123456789abcdef";
  1430. template <typename Type>
  1431. static String hexToString (Type v)
  1432. {
  1433. String::CharPointerType::CharType buffer[32];
  1434. String::CharPointerType::CharType* const end = buffer + numElementsInArray (buffer) - 1;
  1435. String::CharPointerType::CharType* t = end;
  1436. *t = 0;
  1437. do
  1438. {
  1439. *--t = hexDigits [(int) (v & 15)];
  1440. v >>= 4;
  1441. } while (v != 0);
  1442. return String (String::CharPointerType (t),
  1443. String::CharPointerType (end));
  1444. }
  1445. String String::toHexString (int number) { return hexToString ((unsigned int) number); }
  1446. String String::toHexString (int64 number) { return hexToString ((uint64) number); }
  1447. String String::toHexString (short number) { return toHexString ((int) (unsigned short) number); }
  1448. String String::toHexString (const void* const d, const int size, const int groupSize)
  1449. {
  1450. if (size <= 0)
  1451. return String();
  1452. int numChars = (size * 2) + 2;
  1453. if (groupSize > 0)
  1454. numChars += size / groupSize;
  1455. String s (PreallocationBytes (sizeof (CharPointerType::CharType) * (size_t) numChars));
  1456. const unsigned char* data = static_cast<const unsigned char*> (d);
  1457. CharPointerType dest (s.text);
  1458. for (int i = 0; i < size; ++i)
  1459. {
  1460. const unsigned char nextByte = *data++;
  1461. dest.write ((water_uchar) hexDigits [nextByte >> 4]);
  1462. dest.write ((water_uchar) hexDigits [nextByte & 0xf]);
  1463. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  1464. dest.write ((water_uchar) ' ');
  1465. }
  1466. dest.writeNull();
  1467. return s;
  1468. }
  1469. int String::getHexValue32() const noexcept { return CharacterFunctions::HexParser<int> ::parse (text); }
  1470. int64 String::getHexValue64() const noexcept { return CharacterFunctions::HexParser<int64>::parse (text); }
  1471. //==============================================================================
  1472. static const water_uchar emptyChar = 0;
  1473. template <class CharPointerType_Src, class CharPointerType_Dest>
  1474. struct StringEncodingConverter
  1475. {
  1476. static CharPointerType_Dest convert (const String& s)
  1477. {
  1478. String& source = const_cast<String&> (s);
  1479. typedef typename CharPointerType_Dest::CharType DestChar;
  1480. if (source.isEmpty())
  1481. return CharPointerType_Dest (reinterpret_cast<const DestChar*> (&emptyChar));
  1482. CharPointerType_Src text (source.getCharPointer());
  1483. const size_t extraBytesNeeded = CharPointerType_Dest::getBytesRequiredFor (text) + sizeof (typename CharPointerType_Dest::CharType);
  1484. const size_t endOffset = (text.sizeInBytes() + 3) & ~3u; // the new string must be word-aligned or many Windows
  1485. // functions will fail to read it correctly!
  1486. source.preallocateBytes (endOffset + extraBytesNeeded);
  1487. text = source.getCharPointer();
  1488. void* const newSpace = addBytesToPointer (text.getAddress(), (int) endOffset);
  1489. const CharPointerType_Dest extraSpace (static_cast<DestChar*> (newSpace));
  1490. #ifdef DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  1491. const size_t bytesToClear = (size_t) jmin ((int) extraBytesNeeded, 4);
  1492. zeromem (addBytesToPointer (newSpace, extraBytesNeeded - bytesToClear), bytesToClear);
  1493. #endif
  1494. CharPointerType_Dest (extraSpace).writeAll (text);
  1495. return extraSpace;
  1496. }
  1497. };
  1498. template <>
  1499. struct StringEncodingConverter<CharPointer_UTF8, CharPointer_UTF8>
  1500. {
  1501. static CharPointer_UTF8 convert (const String& source) noexcept { return CharPointer_UTF8 ((CharPointer_UTF8::CharType*) source.getCharPointer().getAddress()); }
  1502. };
  1503. CharPointer_UTF8 String::toUTF8() const { return StringEncodingConverter<CharPointerType, CharPointer_UTF8 >::convert (*this); }
  1504. #ifdef CARLA_OS_WIN
  1505. std::wstring String::toUTF16() const
  1506. {
  1507. if (isEmpty())
  1508. return L"";
  1509. const int len = MultiByteToWideChar (CP_UTF8, 0, toUTF8(), length() + 1, nullptr, 0);
  1510. CARLA_SAFE_ASSERT_RETURN(len > 0, L"");
  1511. std::wstring ret;
  1512. ret.resize(len);
  1513. MultiByteToWideChar (CP_UTF8, 0, toUTF8(), length(), &ret[0], len);
  1514. return ret;
  1515. }
  1516. #endif
  1517. const char* String::toRawUTF8() const
  1518. {
  1519. return toUTF8().getAddress();
  1520. }
  1521. std::string String::toStdString() const
  1522. {
  1523. return std::string (toRawUTF8());
  1524. }
  1525. //==============================================================================
  1526. template <class CharPointerType_Src, class CharPointerType_Dest>
  1527. struct StringCopier
  1528. {
  1529. static size_t copyToBuffer (const CharPointerType_Src source, typename CharPointerType_Dest::CharType* const buffer, const size_t maxBufferSizeBytes)
  1530. {
  1531. wassert (((ssize_t) maxBufferSizeBytes) >= 0); // keep this value positive!
  1532. if (buffer == nullptr)
  1533. return CharPointerType_Dest::getBytesRequiredFor (source) + sizeof (typename CharPointerType_Dest::CharType);
  1534. return CharPointerType_Dest (buffer).writeWithDestByteLimit (source, maxBufferSizeBytes);
  1535. }
  1536. };
  1537. size_t String::copyToUTF8 (CharPointer_UTF8::CharType* const buffer, size_t maxBufferSizeBytes) const noexcept
  1538. {
  1539. return StringCopier<CharPointerType, CharPointer_UTF8>::copyToBuffer (text, buffer, maxBufferSizeBytes);
  1540. }
  1541. //==============================================================================
  1542. size_t String::getNumBytesAsUTF8() const noexcept
  1543. {
  1544. return CharPointer_UTF8::getBytesRequiredFor (text);
  1545. }
  1546. String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  1547. {
  1548. if (buffer != nullptr)
  1549. {
  1550. if (bufferSizeBytes < 0)
  1551. return String (CharPointer_UTF8 (buffer));
  1552. if (bufferSizeBytes > 0)
  1553. {
  1554. wassert (CharPointer_UTF8::isValidString (buffer, bufferSizeBytes));
  1555. return String (CharPointer_UTF8 (buffer), CharPointer_UTF8 (buffer + bufferSizeBytes));
  1556. }
  1557. }
  1558. return String();
  1559. }
  1560. #ifdef CARLA_OS_MAC
  1561. String String::convertToPrecomposedUnicode() const
  1562. {
  1563. #if 0
  1564. UnicodeMapping map;
  1565. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  1566. kUnicodeNoSubset,
  1567. kTextEncodingDefaultFormat);
  1568. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  1569. kUnicodeCanonicalCompVariant,
  1570. kTextEncodingDefaultFormat);
  1571. map.mappingVersion = kUnicodeUseLatestMapping;
  1572. UnicodeToTextInfo conversionInfo = 0;
  1573. String result;
  1574. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  1575. {
  1576. const size_t bytesNeeded = CharPointer_UTF16::getBytesRequiredFor (getCharPointer());
  1577. HeapBlock<char> tempOut;
  1578. tempOut.calloc (bytesNeeded + 4);
  1579. ByteCount bytesRead = 0;
  1580. ByteCount outputBufferSize = 0;
  1581. if (ConvertFromUnicodeToText (conversionInfo,
  1582. bytesNeeded, (ConstUniCharArrayPtr) toUTF16().getAddress(),
  1583. kUnicodeDefaultDirectionMask,
  1584. 0, 0, 0, 0,
  1585. bytesNeeded, &bytesRead,
  1586. &outputBufferSize, tempOut) == noErr)
  1587. {
  1588. result = String (CharPointer_UTF16 ((CharPointer_UTF16::CharType*) tempOut.getData()));
  1589. }
  1590. DisposeUnicodeToTextInfo (&conversionInfo);
  1591. }
  1592. return result;
  1593. #else
  1594. return *this;
  1595. #endif
  1596. }
  1597. #endif
  1598. //==============================================================================
  1599. StringRef::StringRef() noexcept : text ((const String::CharPointerType::CharType*) "\0\0\0")
  1600. {
  1601. }
  1602. StringRef::StringRef (const char* stringLiteral) noexcept
  1603. : text (stringLiteral)
  1604. {
  1605. wassert (stringLiteral != nullptr); // This must be a valid string literal, not a null pointer!!
  1606. /* If you get an assertion here, then you're trying to create a string from 8-bit data
  1607. that contains values greater than 127. These can NOT be correctly converted to unicode
  1608. because there's no way for the String class to know what encoding was used to
  1609. create them. The source data could be UTF-8, ASCII or one of many local code-pages.
  1610. To get around this problem, you must be more explicit when you pass an ambiguous 8-bit
  1611. string to the StringRef class - so for example if your source data is actually UTF-8,
  1612. you'd call StringRef (CharPointer_UTF8 ("my utf8 string..")), and it would be able to
  1613. correctly convert the multi-byte characters to unicode. It's *highly* recommended that
  1614. you use UTF-8 with escape characters in your source code to represent extended characters,
  1615. because there's no other way to represent these strings in a way that isn't dependent on
  1616. the compiler, source code editor and platform.
  1617. */
  1618. wassert (CharPointer_UTF8::isValidString (stringLiteral, std::numeric_limits<int>::max()));
  1619. }
  1620. StringRef::StringRef (String::CharPointerType stringLiteral) noexcept : text (stringLiteral)
  1621. {
  1622. wassert (stringLiteral.getAddress() != nullptr); // This must be a valid string literal, not a null pointer!!
  1623. }
  1624. StringRef::StringRef (const String& string) noexcept : text (string.getCharPointer()) {}
  1625. }
  1626. //==============================================================================