str.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include <stdarg.h>
  23. #include <stdio.h>
  24. #include "platform/platform.h"
  25. // Sigh... guess what compiler needs this...
  26. namespace DictHash { U32 hash( String::StringData* ); }
  27. namespace KeyCmp
  28. {
  29. template< typename Key > bool equals( const Key&, const Key& );
  30. template<> bool equals<>( String::StringData* const&, String::StringData* const& );
  31. }
  32. #include "core/util/str.h"
  33. #include "core/util/tDictionary.h"
  34. #include "core/strings/stringFunctions.h"
  35. #include "core/strings/unicode.h"
  36. #include "core/util/hashFunction.h"
  37. #include "core/util/autoPtr.h"
  38. #include "core/util/tVector.h"
  39. #include "core/dataChunker.h"
  40. #include "console/console.h"
  41. #include "math/mMathFn.h"
  42. #include "platform/platform.h"
  43. #include "platform/profiler.h"
  44. #include "platform/platformIntrinsics.h"
  45. #include "platform/threads/mutex.h"
  46. #ifndef TORQUE_DISABLE_MEMORY_MANAGER
  47. # undef new
  48. #else
  49. # define _new new
  50. #endif
  51. const String::SizeType String::NPos = U32(~0);
  52. const String String::EmptyString;
  53. /// A delete policy for the AutoPtr class
  54. struct DeleteString
  55. {
  56. template<class T>
  57. static void destroy(T *ptr) { dFree(ptr); }
  58. };
  59. //-----------------------------------------------------------------------------
  60. /// Search for a character.
  61. /// Search for the position of the needle in the haystack.
  62. /// Default mode is StrCase | StrLeft, mode also accepts StrNoCase and StrRight.
  63. /// If pos is non-zero, then in mode StrLeft the search starts at (hay + pos) and
  64. /// in mode StrRight the search starts at (hay + pos - 1)
  65. /// @return Returns a pointer to the location of the character in the haystack or 0
  66. static const char* StrFind(const char* hay, char needle, S32 pos, U32 mode)
  67. {
  68. if (mode & String::Right)
  69. {
  70. // Go to the end first, then search backwards
  71. const char *he = hay;
  72. if (pos)
  73. {
  74. he += pos - 1;
  75. }
  76. else
  77. {
  78. while (*he)
  79. he++;
  80. }
  81. if (mode & String::NoCase)
  82. {
  83. needle = dTolower(needle);
  84. for (; he >= hay; he--)
  85. {
  86. if (dTolower(*he) == needle)
  87. return he;
  88. }
  89. }
  90. else
  91. {
  92. for (; he >= hay; he--)
  93. {
  94. if (*he == needle)
  95. return he;
  96. }
  97. }
  98. return 0;
  99. }
  100. else
  101. {
  102. if (mode & String::NoCase)
  103. {
  104. needle = dTolower(needle);
  105. for (hay += pos; *hay && dTolower(*hay) != needle;)
  106. hay++;
  107. }
  108. else
  109. {
  110. for (hay += pos; *hay && *hay != needle;)
  111. hay++;
  112. }
  113. return *hay ? hay : 0;
  114. }
  115. }
  116. /// Search for a StringData.
  117. /// Search for the position of the needle in the haystack.
  118. /// Default mode is StrCase | StrLeft, mode also accepts StrNoCase and StrRight.
  119. /// If pos is non-zero, then in mode StrLeft the search starts at (hay + pos) and
  120. /// in mode StrRight the search starts at (hay + pos - 1)
  121. /// @return Returns a pointer to the StringData in the haystack or 0
  122. static const char* StrFind(const char* hay, const char* needle, S32 pos, U32 mode)
  123. {
  124. if (mode & String::Right)
  125. {
  126. const char *he = hay;
  127. if (pos)
  128. {
  129. he += pos - 1;
  130. }
  131. else
  132. {
  133. while (*he)
  134. he++;
  135. }
  136. if (mode & String::NoCase)
  137. {
  138. AutoPtr<char,DeleteString> ln(dStrlwr(dStrdup(needle)));
  139. for (; he >= hay; he--)
  140. {
  141. if (dTolower(*he) == *ln)
  142. {
  143. U32 i = 0;
  144. while (ln[i] && ln[i] == dTolower(he[i]))
  145. i++;
  146. if (!ln[i])
  147. return he;
  148. if (!hay[i])
  149. return 0;
  150. }
  151. }
  152. }
  153. else
  154. {
  155. for (; he >= hay; he--)
  156. {
  157. if (*he == *needle)
  158. {
  159. U32 i = 0;
  160. while (needle[i] && needle[i] == he[i])
  161. i++;
  162. if (!needle[i])
  163. return he;
  164. if (!hay[i])
  165. return 0;
  166. }
  167. }
  168. }
  169. return 0;
  170. }
  171. else
  172. {
  173. if (mode & String::NoCase)
  174. {
  175. AutoPtr<char,DeleteString> ln(dStrlwr(dStrdup(needle)));
  176. for (hay += pos; *hay; hay++)
  177. {
  178. if (dTolower(*hay) == *ln)
  179. {
  180. U32 i = 0;
  181. while (ln[i] && ln[i] == dTolower(hay[i]))
  182. i++;
  183. if (!ln[i])
  184. return hay;
  185. if (!hay[i])
  186. return 0;
  187. }
  188. }
  189. }
  190. else
  191. {
  192. for (hay += pos; *hay; hay++)
  193. {
  194. if (*hay == *needle)
  195. {
  196. U32 i = 0;
  197. while (needle[i] && needle[i] == hay[i])
  198. i++;
  199. if (!needle[i])
  200. return hay;
  201. if (!hay[i])
  202. return 0;
  203. }
  204. }
  205. }
  206. }
  207. return 0;
  208. }
  209. //-----------------------------------------------------------------------------
  210. /// Struct with String::StringData's field so we can initialize
  211. /// this without a constructor.
  212. struct StringDataImpl
  213. {
  214. #ifdef TORQUE_DEBUG
  215. StringChar* mString; ///< so we can inspect data in a debugger
  216. #endif
  217. U32 mRefCount; ///< String reference count; string is not refcounted if this is U32_MAX (necessary for thread-safety of interned strings and the empty string).
  218. U32 mLength; ///< String length in bytes excluding null.
  219. mutable U32 mNumChars; ///< Character count; varies from byte count for strings with multi-bytes characters.
  220. mutable U32 mHashCase; ///< case-sensitive hash
  221. mutable U32 mHashNoCase; ///< case-insensitive hash
  222. mutable UTF16* mUTF16;
  223. bool mIsInterned; ///< If true, this string is interned in the string table.
  224. StringChar mData[1]; ///< Start of string data
  225. };
  226. ///
  227. class String::StringData : protected StringDataImpl
  228. {
  229. public:
  230. ///
  231. StringData( const StringChar* data, bool interned = false )
  232. {
  233. mRefCount = 1;
  234. mNumChars = U32_MAX;
  235. mHashCase = U32_MAX;
  236. mHashNoCase = U32_MAX;
  237. mUTF16 = NULL;
  238. mIsInterned = interned;
  239. // mLength is initialized by operator new()
  240. if( data )
  241. {
  242. dMemcpy( mData, data, sizeof( StringChar ) * mLength );
  243. mData[ mLength ] = '\0';
  244. }
  245. #ifdef TORQUE_DEBUG
  246. mString = &mData[0];
  247. #endif
  248. if( mIsInterned )
  249. mRefCount = U32_MAX;
  250. }
  251. ~StringData()
  252. {
  253. if( mUTF16 )
  254. delete [] mUTF16;
  255. }
  256. void* operator new(size_t size, U32 len);
  257. void* operator new( size_t size, U32 len, DataChunker& chunker );
  258. void operator delete(void *);
  259. bool isShared() const
  260. {
  261. return ( mRefCount > 1 );
  262. }
  263. void addRef()
  264. {
  265. if( mRefCount != U32_MAX )
  266. mRefCount ++;
  267. }
  268. void release()
  269. {
  270. if( mRefCount != U32_MAX )
  271. {
  272. -- mRefCount;
  273. if( !mRefCount )
  274. delete this;
  275. }
  276. }
  277. U32 getLength() const
  278. {
  279. return mLength;
  280. }
  281. U32 getDataSize() const
  282. {
  283. return ( mLength + 1 );
  284. }
  285. U32 getDataSizeUTF16() const
  286. {
  287. return ( mLength * sizeof( UTF16 ) );
  288. }
  289. UTF8 operator []( U32 index ) const
  290. {
  291. AssertFatal( index < mLength, "String::StringData::operator []() - index out of range" );
  292. return mData[ index ];
  293. }
  294. UTF8* utf8()
  295. {
  296. return mData;
  297. }
  298. const UTF8* utf8() const
  299. {
  300. return mData;
  301. }
  302. UTF16* utf16() const
  303. {
  304. if( !mUTF16 )
  305. {
  306. // Do this atomically to protect interned strings.
  307. UTF16* utf16 = convertUTF8toUTF16( mData );
  308. if( !dCompareAndSwap( mUTF16,( UTF16* ) NULL, utf16 ) )
  309. delete [] utf16;
  310. }
  311. return mUTF16;
  312. }
  313. U32 getHashCase() const
  314. {
  315. return mHashCase;
  316. }
  317. U32 getOrCreateHashCase() const
  318. {
  319. if( mHashCase == U32_MAX )
  320. {
  321. PROFILE_SCOPE(StringData_getOrCreateHashCase);
  322. mHashCase = Torque::hash((const U8 *)(mData), mLength, 0);
  323. }
  324. return mHashCase;
  325. }
  326. U32 getHashNoCase() const
  327. {
  328. return mHashNoCase;
  329. }
  330. U32 getOrCreateHashNoCase() const
  331. {
  332. if( mHashNoCase == U32_MAX)
  333. {
  334. PROFILE_SCOPE(StringData_getOrCreateHashNoCase);
  335. UTF8 *lower = new UTF8[ mLength + 1 ];
  336. dStrncpy( lower, utf8(), mLength );
  337. lower[ mLength ] = 0;
  338. dStrlwr( lower );
  339. mHashNoCase = Torque::hash( (const U8*)lower, mLength, 0 );
  340. delete [] lower;
  341. }
  342. return mHashNoCase;
  343. }
  344. U32 getNumChars() const
  345. {
  346. if( mNumChars == U32_MAX )
  347. mNumChars = dStrlen( utf16() );
  348. return mNumChars;
  349. }
  350. bool isInterned() const
  351. {
  352. return mIsInterned;
  353. }
  354. static StringData* Empty()
  355. {
  356. static UTF16 emptyUTF16[ 1 ] = { 0 };
  357. static StringDataImpl empty =
  358. {
  359. #ifdef TORQUE_DEBUG
  360. "", // mString
  361. #endif
  362. U32_MAX, // mRefCount
  363. 0, // mLength
  364. 0, // mNumChars
  365. 0, // mHashCase
  366. 0, // mHashNoCase
  367. emptyUTF16, // mUTF16
  368. true, // mIsInterned
  369. { 0 } // mData
  370. };
  371. return ( StringData* ) &empty;
  372. }
  373. };
  374. //-----------------------------------------------------------------------------
  375. namespace DictHash
  376. {
  377. inline U32 hash( String::StringData* data )
  378. {
  379. return data->getOrCreateHashCase();
  380. }
  381. }
  382. namespace KeyCmp
  383. {
  384. template<>
  385. inline bool equals<>( String::StringData* const& d1, String::StringData* const& d2 )
  386. {
  387. return ( dStrcmp( d1->utf8(), d2->utf8() ) == 0 );
  388. }
  389. }
  390. /// Type for the intern string table. We don't want String instances directly
  391. /// on the table so that destructors don't run when the table is destroyed. This
  392. /// is because we really shouldn't depend on dtor ordering within this file and thus
  393. /// we can't tell whether the intern string memory is freed before or after the
  394. /// table is destroyed.
  395. struct StringInternTable : public HashTable< String::StringData*, String::StringData* >
  396. {
  397. Mutex mMutex;
  398. DataChunker mChunker;
  399. };
  400. static StringInternTable* sInternTable;
  401. struct KillInternTable
  402. {
  403. ~KillInternTable()
  404. {
  405. if( sInternTable )
  406. delete sInternTable;
  407. }
  408. };
  409. static KillInternTable sKillInternTable;
  410. //-----------------------------------------------------------------------------
  411. #ifdef TORQUE_DEBUG
  412. /// Tracks the number of bytes allocated for strings.
  413. /// @bug This currently does not include UTF16 allocations.
  414. static U32 sgStringMemBytes;
  415. /// Tracks the number of Strings which are currently instantiated.
  416. static U32 sgStringInstances;
  417. ConsoleFunction( dumpStringMemStats, void, 1, 1, "()"
  418. "@brief Dumps information about String memory usage\n\n"
  419. "@ingroup Debugging\n"
  420. "@ingroup Strings\n")
  421. {
  422. Con::printf( "String Data: %i instances, %i bytes", sgStringInstances, sgStringMemBytes );
  423. }
  424. #endif
  425. //-----------------------------------------------------------------------------
  426. void* String::StringData::operator new( size_t size, U32 len )
  427. {
  428. AssertFatal( len != 0, "String::StringData::operator new() - string must not be empty" );
  429. StringData *str = reinterpret_cast<StringData*>( dMalloc( size + len * sizeof(StringChar) ) );
  430. str->mLength = len;
  431. #ifdef TORQUE_DEBUG
  432. dFetchAndAdd( sgStringMemBytes, size + len * sizeof(StringChar) );
  433. dFetchAndAdd( sgStringInstances, 1 );
  434. #endif
  435. return str;
  436. }
  437. void String::StringData::operator delete(void *ptr)
  438. {
  439. StringData* sub = static_cast<StringData *>(ptr);
  440. TORQUE_UNUSED(sub);
  441. AssertFatal( sub->mRefCount == 0, "StringData::delete() - invalid refcount" );
  442. #ifdef TORQUE_DEBUG
  443. dFetchAndAdd( sgStringMemBytes, U32( -( S32( sizeof( StringData ) + sub->mLength * sizeof(StringChar) ) ) ) );
  444. dFetchAndAdd( sgStringInstances, U32( -1 ) );
  445. #endif
  446. dFree( ptr );
  447. }
  448. void* String::StringData::operator new( size_t size, U32 len, DataChunker& chunker )
  449. {
  450. AssertFatal( len != 0, "String::StringData::operator new() - string must not be empty" );
  451. StringData *str = reinterpret_cast<StringData*>( chunker.alloc( size + len * sizeof(StringChar) ) );
  452. str->mLength = len;
  453. #ifdef TORQUE_DEBUG
  454. dFetchAndAdd( sgStringMemBytes, size + len * sizeof(StringChar) );
  455. dFetchAndAdd( sgStringInstances, 1 );
  456. #endif
  457. return str;
  458. }
  459. //-----------------------------------------------------------------------------
  460. String::String()
  461. {
  462. PROFILE_SCOPE(String_default_constructor);
  463. _string = StringData::Empty();
  464. }
  465. String::String(const String &str)
  466. {
  467. PROFILE_SCOPE(String_String_constructor);
  468. _string = str._string;
  469. _string->addRef();
  470. }
  471. String::String(const StringChar *str)
  472. {
  473. PROFILE_SCOPE(String_char_constructor);
  474. if( str && *str )
  475. {
  476. U32 len = dStrlen(str);
  477. _string = new ( len ) StringData( str );
  478. }
  479. else
  480. _string = StringData::Empty();
  481. }
  482. String::String(const StringChar *str, SizeType len)
  483. {
  484. PROFILE_SCOPE(String_char_len_constructor);
  485. if (str && *str && len!=0)
  486. {
  487. AssertFatal(len<=dStrlen(str), "String::String: string too short");
  488. _string = new ( len ) StringData( str );
  489. }
  490. else
  491. _string = StringData::Empty();
  492. }
  493. String::String(const UTF16 *str)
  494. {
  495. PROFILE_SCOPE(String_UTF16_constructor);
  496. if( str && str[ 0 ] )
  497. {
  498. UTF8* utf8 = convertUTF16toUTF8( str );
  499. U32 len = dStrlen( utf8 );
  500. _string = new ( len ) StringData( utf8 );
  501. delete [] utf8;
  502. }
  503. else
  504. _string = StringData::Empty();
  505. }
  506. String::~String()
  507. {
  508. _string->release();
  509. }
  510. //-----------------------------------------------------------------------------
  511. String String::intern() const
  512. {
  513. if( isInterned() )
  514. return *this;
  515. // Create the intern table, if we haven't already.
  516. if( !sInternTable )
  517. sInternTable = new StringInternTable;
  518. // Lock the string table.
  519. MutexHandle mutex;
  520. mutex.lock( &sInternTable->mMutex );
  521. // Lookup.
  522. StringInternTable::Iterator iter = sInternTable->find( _string );
  523. if( iter != sInternTable->end() )
  524. return ( *iter ).value;
  525. // Create new.
  526. StringData* data = new ( length(), sInternTable->mChunker ) StringData( c_str(), true );
  527. iter = sInternTable->insertUnique( data, data );
  528. return ( *iter ).value;
  529. }
  530. //-----------------------------------------------------------------------------
  531. const StringChar* String::c_str() const
  532. {
  533. return _string->utf8();
  534. }
  535. const UTF16 *String::utf16() const
  536. {
  537. return _string->utf16();
  538. }
  539. String::SizeType String::length() const
  540. {
  541. return _string->getLength();
  542. }
  543. String::SizeType String::size() const
  544. {
  545. return _string->getDataSize();
  546. }
  547. String::SizeType String::numChars() const
  548. {
  549. return _string->getNumChars();
  550. }
  551. bool String::isEmpty() const
  552. {
  553. return ( _string == StringData::Empty() );
  554. }
  555. bool String::isShared() const
  556. {
  557. return _string->isShared();
  558. }
  559. bool String::isSame( const String& str ) const
  560. {
  561. return ( _string == str._string );
  562. }
  563. bool String::isInterned() const
  564. {
  565. return ( _string->isInterned() );
  566. }
  567. U32 String::getHashCaseSensitive() const
  568. {
  569. return _string->getOrCreateHashCase();
  570. }
  571. U32 String::getHashCaseInsensitive() const
  572. {
  573. return _string->getOrCreateHashNoCase();
  574. }
  575. //-----------------------------------------------------------------------------
  576. String::SizeType String::find(const String &str, SizeType pos, U32 mode) const
  577. {
  578. return find(str._string->utf8(), pos, mode);
  579. }
  580. String& String::insert(SizeType pos, const String &str)
  581. {
  582. return insert(pos, str._string->utf8());
  583. }
  584. String& String::replace(SizeType pos, SizeType len, const String &str)
  585. {
  586. return replace(pos, len, str._string->utf8());
  587. }
  588. //-----------------------------------------------------------------------------
  589. String& String::operator=(StringChar c)
  590. {
  591. _string->release();
  592. _string = new ( 2 ) StringData( 0 );
  593. _string->utf8()[ 0 ] = c;
  594. _string->utf8()[ 1 ] = '\0';
  595. return *this;
  596. }
  597. String& String::operator+=(StringChar c)
  598. {
  599. // Append the given string into a new string
  600. U32 len = _string->getLength();
  601. StringData* sub = new ( len + 1 ) StringData( NULL );
  602. copy( sub->utf8(), _string->utf8(), len );
  603. sub->utf8()[len] = c;
  604. sub->utf8()[len+1] = 0;
  605. _string->release();
  606. _string = sub;
  607. return *this;
  608. }
  609. //-----------------------------------------------------------------------------
  610. String& String::operator=(const StringChar *str)
  611. {
  612. // Protect against self assignment which is not only a
  613. // waste of time, but can also lead to the string being
  614. // freed before it can be reassigned.
  615. if ( _string->utf8() == str )
  616. return *this;
  617. _string->release();
  618. if (str && *str)
  619. {
  620. U32 len = dStrlen(str);
  621. _string = new ( len ) StringData( str );
  622. }
  623. else
  624. _string = StringData::Empty();
  625. return *this;
  626. }
  627. String& String::operator=(const String &src)
  628. {
  629. // Inc src first to avoid assignment to self problems.
  630. src._string->addRef();
  631. _string->release();
  632. _string = src._string;
  633. return *this;
  634. }
  635. String& String::operator+=(const StringChar *src)
  636. {
  637. if( src == NULL && !*src )
  638. return *this;
  639. // Append the given string into a new string
  640. U32 lena = _string->getLength();
  641. U32 lenb = dStrlen(src);
  642. U32 newlen = lena + lenb;
  643. StringData* sub;
  644. if( !newlen )
  645. sub = StringData::Empty();
  646. else
  647. {
  648. sub = new ( newlen ) StringData( NULL );
  649. copy(sub->utf8(),_string->utf8(),lena);
  650. copy(sub->utf8() + lena,src,lenb + 1);
  651. }
  652. _string->release();
  653. _string = sub;
  654. return *this;
  655. }
  656. String& String::operator+=(const String &src)
  657. {
  658. if( src.isEmpty() )
  659. return *this;
  660. // Append the given string into a new string
  661. U32 lena = _string->getLength();
  662. U32 lenb = src._string->getLength();
  663. U32 newlen = lena + lenb;
  664. StringData* sub;
  665. if( !newlen )
  666. sub = StringData::Empty();
  667. else
  668. {
  669. sub = new ( newlen ) StringData( NULL );
  670. copy(sub->utf8(),_string->utf8(),lena);
  671. copy(sub->utf8() + lena,src._string->utf8(),lenb + 1);
  672. }
  673. _string->release();
  674. _string = sub;
  675. return *this;
  676. }
  677. //-----------------------------------------------------------------------------
  678. String operator+(const String &a, const String &b)
  679. {
  680. PROFILE_SCOPE( String_String_plus_String );
  681. if( a.isEmpty() )
  682. return b;
  683. else if( b.isEmpty() )
  684. return a;
  685. U32 lena = a.length();
  686. U32 lenb = b.length();
  687. String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
  688. String::copy(sub->utf8(),a._string->utf8(),lena);
  689. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  690. return String(sub);
  691. }
  692. String operator+(const String &a, StringChar c)
  693. {
  694. //PROFILE_SCOPE( String_String_plus_Char );
  695. U32 lena = a.length();
  696. String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
  697. String::copy(sub->utf8(),a._string->utf8(),lena);
  698. sub->utf8()[lena] = c;
  699. sub->utf8()[lena+1] = 0;
  700. return String(sub);
  701. }
  702. String operator+(StringChar c, const String &a)
  703. {
  704. //PROFILE_SCOPE( String_Char_plus_String );
  705. U32 lena = a.length();
  706. String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
  707. String::copy(sub->utf8() + 1,a._string->utf8(),lena + 1);
  708. sub->utf8()[0] = c;
  709. return String(sub);
  710. }
  711. String operator+(const String &a, const StringChar *b)
  712. {
  713. //PROFILE_SCOPE( String_String_plus_CString );
  714. AssertFatal(b,"String:: Invalid null ptr argument");
  715. if( a.isEmpty() )
  716. return String( b );
  717. U32 lena = a.length();
  718. U32 lenb = dStrlen(b);
  719. if( !lenb )
  720. return a;
  721. String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
  722. String::copy(sub->utf8(),a._string->utf8(),lena);
  723. String::copy(sub->utf8() + lena,b,lenb + 1);
  724. return String(sub);
  725. }
  726. String operator+(const StringChar *a, const String &b)
  727. {
  728. //PROFILE_SCOPE( String_CString_plus_String );
  729. AssertFatal(a,"String:: Invalid null ptr argument");
  730. if( b.isEmpty() )
  731. return String( a );
  732. U32 lena = dStrlen(a);
  733. if( !lena )
  734. return b;
  735. U32 lenb = b.length();
  736. String::StringData* sub = new ( lena + lenb ) String::StringData( NULL );
  737. String::copy(sub->utf8(),a,lena);
  738. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  739. return String(sub);
  740. }
  741. bool String::operator==(const String &str) const
  742. {
  743. //PROFILE_SCOPE( String_op_equal );
  744. if( str._string == _string )
  745. return true;
  746. else if( str._string->isInterned() && _string->isInterned() )
  747. return false;
  748. else if( str.length() != length() )
  749. return false;
  750. else if( str._string->getHashCase() != U32_MAX
  751. && _string->getHashCase() != U32_MAX
  752. && str._string->getHashCase() != _string->getHashCase() )
  753. return false;
  754. else
  755. return ( dMemcmp( str._string->utf8(), _string->utf8(), _string->getLength() ) == 0 );
  756. }
  757. bool String::operator==( StringChar c ) const
  758. {
  759. if( !_string || _string->getLength() != 1 )
  760. return false;
  761. else
  762. return ( _string->utf8()[ 0 ] == c );
  763. }
  764. bool String::operator<(const String &str) const
  765. {
  766. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) < 0 );
  767. }
  768. bool String::operator>(const String &str) const
  769. {
  770. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) > 0 );
  771. }
  772. bool String::operator<=(const String &str) const
  773. {
  774. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) <= 0 );
  775. }
  776. bool String::operator>=(const String &str) const
  777. {
  778. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) >= 0 );
  779. }
  780. //-----------------------------------------------------------------------------
  781. // Base functions for string comparison
  782. S32 String::compare(const StringChar *str, SizeType len, U32 mode) const
  783. {
  784. PROFILE_SCOPE( String_compare );
  785. AssertFatal(str,"String:: Invalid null ptr argument");
  786. const StringChar *p1 = _string->utf8();
  787. const StringChar *p2 = str;
  788. if (p1 == p2)
  789. return 0;
  790. if( mode & String::Right )
  791. {
  792. U32 n = len;
  793. if( n > length() )
  794. n = length();
  795. p1 += length() - n;
  796. p2 += dStrlen( str ) - n;
  797. }
  798. if (mode & String::NoCase)
  799. {
  800. if (len)
  801. {
  802. for (;--len; p1++,p2++)
  803. {
  804. if (dTolower(*p1) != dTolower(*p2) || !*p1)
  805. break;
  806. }
  807. }
  808. else
  809. {
  810. while (dTolower(*p1) == dTolower(*p2) && *p1)
  811. {
  812. p1++;
  813. p2++;
  814. }
  815. }
  816. return dTolower(*p1) - dTolower(*p2);
  817. }
  818. if (len)
  819. return dMemcmp(p1,p2,len);
  820. while (*p1 == *p2 && *p1)
  821. {
  822. p1++;
  823. p2++;
  824. }
  825. return *p1 - *p2;
  826. }
  827. S32 String::compare(const String &str, SizeType len, U32 mode) const
  828. {
  829. if ( str._string == _string )
  830. return 0;
  831. return compare( str.c_str(), len, mode );
  832. }
  833. bool String::equal(const String &str, U32 mode) const
  834. {
  835. if( !mode )
  836. return ( *this == str );
  837. else
  838. {
  839. if( _string == str._string )
  840. return true;
  841. else if( _string->isInterned() && str._string->isInterned() )
  842. return false;
  843. else if( length() != str.length() )
  844. return false;
  845. else if( _string->getHashNoCase() != U32_MAX
  846. && str._string->getHashNoCase() != U32_MAX
  847. && _string->getHashNoCase() != str._string->getHashNoCase() )
  848. return false;
  849. else
  850. return ( compare( str.c_str(), length(), mode ) == 0 );
  851. }
  852. }
  853. //-----------------------------------------------------------------------------
  854. String::SizeType String::find(StringChar c, SizeType pos, U32 mode) const
  855. {
  856. const StringChar* ptr = StrFind(_string->utf8(),c,pos,mode);
  857. return ptr? SizeType(ptr - _string->utf8()): NPos;
  858. }
  859. String::SizeType String::find(const StringChar *str, SizeType pos, U32 mode) const
  860. {
  861. AssertFatal(str,"String:: Invalid null ptr argument");
  862. const StringChar* ptr = StrFind(_string->utf8(),str,pos,mode);
  863. return ptr? SizeType(ptr - _string->utf8()): NPos;
  864. }
  865. //-----------------------------------------------------------------------------
  866. String& String::insert(SizeType pos, const StringChar *str)
  867. {
  868. AssertFatal(str,"String:: Invalid null ptr argument");
  869. return insert(pos,str,dStrlen(str));
  870. }
  871. ///@todo review for error checking
  872. String& String::insert(SizeType pos, const StringChar *str, SizeType len)
  873. {
  874. if( !len )
  875. return *this;
  876. AssertFatal( str, "String:: Invalid null ptr argument" );
  877. SizeType lena = length();
  878. AssertFatal((pos <= lena),"Calling String::insert with position greater than length");
  879. U32 newlen = lena + len;
  880. StringData *sub;
  881. if( !newlen )
  882. sub = StringData::Empty();
  883. else
  884. {
  885. sub = new ( newlen ) StringData( NULL );
  886. String::copy(sub->utf8(),_string->utf8(),pos);
  887. String::copy(sub->utf8() + pos,str,len);
  888. String::copy(sub->utf8() + pos + len,_string->utf8() + pos,lena - pos + 1);
  889. }
  890. _string->release();
  891. _string = sub;
  892. return *this;
  893. }
  894. String& String::erase(SizeType pos, SizeType len)
  895. {
  896. AssertFatal( len != 0, "String::erase() - Calling String::erase with 0 length" );
  897. AssertFatal( ( pos + len ) <= length(), "String::erase() - Invalid string region" );
  898. if( !len )
  899. return *this;
  900. SizeType slen = length();
  901. U32 newlen = slen - len;
  902. StringData *sub;
  903. if( !newlen )
  904. sub = StringData::Empty();
  905. else
  906. {
  907. sub = new ( newlen ) StringData( NULL );
  908. if (pos > 0)
  909. String::copy(sub->utf8(),_string->utf8(),pos);
  910. String::copy(sub->utf8() + pos, _string->utf8() + pos + len, slen - (pos + len) + 1);
  911. }
  912. _string->release();
  913. _string = sub;
  914. return *this;
  915. }
  916. ///@todo review for error checking
  917. String& String::replace(SizeType pos, SizeType len, const StringChar *str)
  918. {
  919. AssertFatal( str, "String::replace() - Invalid null ptr argument" );
  920. AssertFatal( len != 0, "String::replace() - Zero length" );
  921. AssertFatal( ( pos + len ) <= length(), "String::replace() - Invalid string region" );
  922. SizeType slen = length();
  923. SizeType rlen = dStrlen(str);
  924. U32 newlen = slen - len + rlen;
  925. StringData *sub;
  926. if( !newlen )
  927. sub = StringData::Empty();
  928. else
  929. {
  930. sub = new ( newlen ) StringData( NULL );
  931. String::copy(sub->utf8(),_string->utf8(), pos);
  932. String::copy(sub->utf8() + pos,str,rlen);
  933. String::copy(sub->utf8() + pos + rlen,_string->utf8() + pos + len,slen - pos - len + 1);
  934. }
  935. _string->release();
  936. _string = sub;
  937. return *this;
  938. }
  939. String& String::replace( StringChar c1, StringChar c2 )
  940. {
  941. if( isEmpty() )
  942. return *this;
  943. // Create the new string lazily so that we don't needlessly
  944. // dup strings when there is nothing to replace.
  945. StringData* sub = NULL;
  946. bool foundReplacement = false;
  947. StringChar* c = _string->utf8();
  948. while( *c )
  949. {
  950. if( *c == c1 )
  951. {
  952. if( !foundReplacement )
  953. {
  954. sub = new ( length() ) StringData( _string->utf8() );
  955. c = &sub->utf8()[ c - _string->utf8() ];
  956. foundReplacement = true;
  957. }
  958. *c = c2;
  959. }
  960. c++;
  961. }
  962. if( foundReplacement )
  963. {
  964. _string->release();
  965. _string = sub;
  966. }
  967. return *this;
  968. }
  969. String &String::replace(const String &s1, const String &s2)
  970. {
  971. // Find number of occurrences of s1 and
  972. // Calculate length of the new string...
  973. const U32 &s1len = s1.length();
  974. const U32 &s2len = s2.length();
  975. U32 pos = 0;
  976. Vector<U32> indices;
  977. StringChar *walk = _string->utf8();
  978. while ( walk )
  979. {
  980. // Casting away the const... was there a better way?
  981. walk = (StringChar*)StrFind( _string->utf8(), s1.c_str(), pos, Case|Left );
  982. if ( walk )
  983. {
  984. pos = SizeType(walk - _string->utf8());
  985. indices.push_back( pos );
  986. pos += s1len;
  987. }
  988. }
  989. // Early-out, no StringDatas found.
  990. if ( indices.size() == 0 )
  991. return *this;
  992. U32 newSize = size() - ( indices.size() * s1len ) + ( indices.size() * s2len );
  993. StringData *sub;
  994. if( newSize == 1 )
  995. sub = StringData::Empty();
  996. else
  997. {
  998. sub = new (newSize - 1 ) StringData( NULL );
  999. // Now assemble the new string from the pieces of the old...
  1000. // Index into the old string
  1001. pos = 0;
  1002. // Index into the new string
  1003. U32 newPos = 0;
  1004. // Used to store a character count to be memcpy'd
  1005. U32 copyCharCount = 0;
  1006. for ( U32 i = 0; i < indices.size(); i++ )
  1007. {
  1008. const U32 &index = indices[i];
  1009. // Number of chars (if any) before the next indexed StringData
  1010. copyCharCount = index - pos;
  1011. // Copy chars before the StringData if we have any.
  1012. if ( copyCharCount > 0 )
  1013. {
  1014. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1015. newPos += copyCharCount;
  1016. }
  1017. // Copy over the replacement string.
  1018. if ( s2len > 0 )
  1019. dMemcpy( sub->utf8() + newPos, s2._string->utf8(), s2len * sizeof(StringChar) );
  1020. newPos += s2len;
  1021. pos = index + s1len;
  1022. }
  1023. // There could be characters left in the original string after the last
  1024. // StringData occurrence, which we need to copy now - outside the loop.
  1025. copyCharCount = length() - indices.last() - s1len;
  1026. if ( copyCharCount != 0 )
  1027. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1028. // Null terminate it!
  1029. sub->utf8()[newSize-1] = 0;
  1030. }
  1031. _string->release();
  1032. _string = sub;
  1033. return *this;
  1034. }
  1035. //-----------------------------------------------------------------------------
  1036. String String::substr(SizeType pos, SizeType len) const
  1037. {
  1038. //PROFILE_SCOPE( String_substr );
  1039. AssertFatal( pos <= length(), "String::substr - Invalid position!" );
  1040. if ( len == -1 )
  1041. len = length() - pos;
  1042. AssertFatal( len + pos <= length(), "String::substr - Invalid length!" );
  1043. StringData* sub;
  1044. if( !len )
  1045. sub = StringData::Empty();
  1046. else
  1047. sub = new ( len ) StringData( _string->utf8() + pos );
  1048. return sub;
  1049. }
  1050. //-----------------------------------------------------------------------------
  1051. String String::trim() const
  1052. {
  1053. if( isEmpty() )
  1054. return *this;
  1055. const StringChar* start = _string->utf8();
  1056. while( *start && dIsspace( *start ) )
  1057. start ++;
  1058. const StringChar* end = _string->utf8() + length() - 1;
  1059. while( end > start && dIsspace( *end ) )
  1060. end --;
  1061. end ++;
  1062. const U32 len = end - start;
  1063. if( len == length() )
  1064. return *this;
  1065. StringData* sub;
  1066. if( !len )
  1067. sub = StringData::Empty();
  1068. else
  1069. sub = new ( len ) StringData( start );
  1070. return sub;
  1071. }
  1072. //-----------------------------------------------------------------------------
  1073. String String::expandEscapes() const
  1074. {
  1075. char* tmp = ( char* ) dMalloc( length() * 2 + 1 ); // worst-case situation.
  1076. expandEscape( tmp, c_str() );
  1077. String str( tmp );
  1078. dFree( tmp );
  1079. return str;
  1080. }
  1081. //-----------------------------------------------------------------------------
  1082. String String::collapseEscapes() const
  1083. {
  1084. char* tmp = dStrdup( c_str() );
  1085. collapseEscape( tmp );
  1086. String str( tmp );
  1087. dFree( tmp );
  1088. return str;
  1089. }
  1090. //-----------------------------------------------------------------------------
  1091. void String::split( const char* delimiter, Vector< String >& outElements ) const
  1092. {
  1093. const char* ptr = _string->utf8();
  1094. const char* start = ptr;
  1095. while( *ptr )
  1096. {
  1097. // Search for start of delimiter.
  1098. if( *ptr != delimiter[ 0 ] )
  1099. ptr ++;
  1100. else
  1101. {
  1102. // Skip delimiter.
  1103. const char* end = ptr;
  1104. const char* del = delimiter;
  1105. while( *del && *del == *ptr )
  1106. {
  1107. ptr ++;
  1108. del ++;
  1109. }
  1110. // If we didn't match all of delimiter,
  1111. // continue with search.
  1112. if( *del != '\0' )
  1113. continue;
  1114. // Extract component.
  1115. outElements.push_back( String( start, end - start ) );
  1116. start = ptr;
  1117. }
  1118. }
  1119. // Add rest of string if there is any.
  1120. if( start != ptr )
  1121. outElements.push_back( start );
  1122. }
  1123. //-----------------------------------------------------------------------------
  1124. bool String::startsWith( const char* text ) const
  1125. {
  1126. return dStrStartsWith( _string->utf8(), text );
  1127. }
  1128. //-----------------------------------------------------------------------------
  1129. bool String::endsWith( const char* text ) const
  1130. {
  1131. return dStrEndsWith( _string->utf8(), text );
  1132. }
  1133. //-----------------------------------------------------------------------------
  1134. void String::copy(StringChar* dst, const StringChar *src, U32 len)
  1135. {
  1136. dMemcpy(dst, src, len * sizeof(StringChar));
  1137. }
  1138. //-----------------------------------------------------------------------------
  1139. #if defined(TORQUE_OS_WIN32) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)
  1140. // This standard function is not defined when compiling with VC7...
  1141. #define vsnprintf _vsnprintf
  1142. #endif
  1143. String::StrFormat::~StrFormat()
  1144. {
  1145. if( _dynamicBuffer )
  1146. dFree( _dynamicBuffer );
  1147. }
  1148. S32 String::StrFormat::format( const char *format, void *args )
  1149. {
  1150. _len=0;
  1151. return formatAppend(format,args);
  1152. }
  1153. S32 String::StrFormat::formatAppend( const char *format, void *args )
  1154. {
  1155. // Format into the fixed buffer first.
  1156. S32 startLen = _len;
  1157. if (_dynamicBuffer == NULL)
  1158. {
  1159. _len += vsnprintf(_fixedBuffer + _len, sizeof(_fixedBuffer) - _len, format, *(va_list*)args);
  1160. if (_len >= 0 && _len < sizeof(_fixedBuffer))
  1161. return _len;
  1162. // Start off the dynamic buffer at twice fixed buffer size
  1163. _len = startLen;
  1164. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1165. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1166. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1167. }
  1168. // Format into the dynamic buffer, if the buffer is not large enough, then
  1169. // keep doubling it's size until it is. The buffer is not reallocated
  1170. // using reallocate() to avoid unnecessary buffer copying.
  1171. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1172. while (_len < 0 || _len >= _dynamicSize)
  1173. {
  1174. _len = startLen;
  1175. _dynamicBuffer = (char*)dRealloc(_dynamicBuffer, _dynamicSize *= 2);
  1176. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1177. }
  1178. return _len;
  1179. }
  1180. S32 String::StrFormat::append(const char * str, S32 len)
  1181. {
  1182. if (_dynamicBuffer == NULL)
  1183. {
  1184. if (_len+len >= 0 && _len+len < sizeof(_fixedBuffer))
  1185. {
  1186. dMemcpy(_fixedBuffer + _len, str, len);
  1187. _len += len;
  1188. _fixedBuffer[_len] = '\0';
  1189. return _len;
  1190. }
  1191. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1192. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1193. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1194. }
  1195. S32 newSize = _dynamicSize;
  1196. while (newSize < _len+len)
  1197. newSize *= 2;
  1198. if (newSize != _dynamicSize)
  1199. _dynamicBuffer = (char*) dRealloc(_dynamicBuffer, newSize);
  1200. _dynamicSize = newSize;
  1201. dMemcpy(_dynamicBuffer + _len, str, len);
  1202. _len += len;
  1203. _dynamicBuffer[_len] = '\0';
  1204. return _len;
  1205. }
  1206. S32 String::StrFormat::append(const char * str)
  1207. {
  1208. return append(str, dStrlen(str));
  1209. }
  1210. char* String::StrFormat::copy( char *buffer ) const
  1211. {
  1212. dMemcpy(buffer, _dynamicBuffer? _dynamicBuffer: _fixedBuffer, _len+1);
  1213. return buffer;
  1214. }
  1215. //-----------------------------------------------------------------------------
  1216. String String::ToString( bool value )
  1217. {
  1218. static String sTrue = "true";
  1219. static String sFalse = "false";
  1220. if( value )
  1221. return sTrue;
  1222. return sFalse;
  1223. }
  1224. String String::ToString(const char *str, ...)
  1225. {
  1226. AssertFatal(str,"String:: Invalid null ptr argument");
  1227. // Use the format object
  1228. va_list args;
  1229. va_start(args, str);
  1230. String ret = VToString(str, args);
  1231. va_end(args);
  1232. return ret;
  1233. }
  1234. String String::VToString(const char* str, void* args)
  1235. {
  1236. StrFormat format(str,&args);
  1237. // Copy it into a string
  1238. U32 len = format.length();
  1239. StringData* sub;
  1240. if( !len )
  1241. sub = StringData::Empty();
  1242. else
  1243. {
  1244. sub = new ( len ) StringData( NULL );
  1245. format.copy( sub->utf8() );
  1246. sub->utf8()[ len ] = 0;
  1247. }
  1248. return sub;
  1249. }
  1250. String String::SpanToString(const char *start, const char *end)
  1251. {
  1252. if ( end == start )
  1253. return String();
  1254. AssertFatal( end > start, "Invalid arguments to String::SpanToString - end is before start" );
  1255. U32 len = U32(end - start);
  1256. StringData* sub = new ( len ) StringData( start );
  1257. return sub;
  1258. }
  1259. String String::ToLower(const String &string)
  1260. {
  1261. if ( string.isEmpty() )
  1262. return String();
  1263. StringData* sub = new ( string.length() ) StringData( string );
  1264. dStrlwr( sub->utf8() );
  1265. return sub;
  1266. }
  1267. String String::ToUpper(const String &string)
  1268. {
  1269. if ( string.isEmpty() )
  1270. return String();
  1271. StringData* sub = new ( string.length() ) StringData( string );
  1272. dStrupr( sub->utf8() );
  1273. return sub;
  1274. }
  1275. String String::GetTrailingNumber(const char* str, S32& number)
  1276. {
  1277. // Check for trivial strings
  1278. if (!str || !str[0])
  1279. return String::EmptyString;
  1280. // Find the number at the end of the string
  1281. String base(str);
  1282. const char* p = base.c_str() + base.length() - 1;
  1283. // Ignore trailing whitespace
  1284. while ((p != base.c_str()) && dIsspace(*p))
  1285. p--;
  1286. // Need at least one digit!
  1287. if (!isdigit(*p))
  1288. return base;
  1289. // Back up to the first non-digit character
  1290. while ((p != base.c_str()) && isdigit(*p))
  1291. p--;
  1292. // Convert number => allow negative numbers, treat '_' as '-' for Maya
  1293. if ((*p == '-') || (*p == '_'))
  1294. number = -dAtoi(p + 1);
  1295. else
  1296. number = ((p == base.c_str()) ? dAtoi(p) : dAtoi(++p));
  1297. // Remove space between the name and the number
  1298. while ((p > base.c_str()) && dIsspace(*(p-1)))
  1299. p--;
  1300. return base.substr(0, p - base.c_str());
  1301. }