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

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