str.cpp 39 KB

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