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

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