juce_String.cpp 90 KB

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