str.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723
  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, U32 length, bool interned = false )
  233. {
  234. mRefCount = 1;
  235. mNumChars = U32_MAX;
  236. mHashCase = U32_MAX;
  237. mHashNoCase = U32_MAX;
  238. mUTF16 = NULL;
  239. mLength = length;
  240. mIsInterned = interned;
  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. AssertFatal( mRefCount == 0, "StringData::~StringData invalid refcount" );
  255. if( mUTF16 )
  256. delete [] mUTF16;
  257. }
  258. static StringData* Create(const StringChar* data, U32 len, bool interned = false)
  259. {
  260. void* memory = dMalloc(sizeof(StringData) + sizeof(StringChar) * len);
  261. StringData* result = new(memory) StringData(data, len, interned);
  262. return result;
  263. }
  264. static StringData* Create(const StringChar* data, U32 len, DataChunker& chunker, bool interned = false)
  265. {
  266. void* memory = chunker.alloc( sizeof(StringData) + len * sizeof(StringChar));
  267. StringData* result = new(memory) StringData(data, len, interned);
  268. return result;
  269. }
  270. bool isShared() const
  271. {
  272. return ( mRefCount > 1 );
  273. }
  274. void addRef()
  275. {
  276. if( mRefCount != U32_MAX )
  277. mRefCount ++;
  278. }
  279. void release()
  280. {
  281. if( mRefCount != U32_MAX )
  282. {
  283. -- mRefCount;
  284. if( !mRefCount )
  285. delete this;
  286. }
  287. }
  288. U32 getLength() const
  289. {
  290. return mLength;
  291. }
  292. U32 getDataSize() const
  293. {
  294. return ( mLength + 1 );
  295. }
  296. U32 getDataSizeUTF16() const
  297. {
  298. return ( mLength * sizeof( UTF16 ) );
  299. }
  300. UTF8 operator []( U32 index ) const
  301. {
  302. AssertFatal( index < mLength, "String::StringData::operator []() - index out of range" );
  303. return mData[ index ];
  304. }
  305. UTF8* utf8()
  306. {
  307. return mData;
  308. }
  309. const UTF8* utf8() const
  310. {
  311. return mData;
  312. }
  313. UTF16* utf16() const
  314. {
  315. if( !mUTF16 )
  316. {
  317. // Do this atomically to protect interned strings.
  318. UTF16* utf16 = createUTF16string( mData );
  319. if( !dCompareAndSwap( mUTF16,( UTF16* ) NULL, utf16 ) )
  320. delete [] utf16;
  321. }
  322. return mUTF16;
  323. }
  324. U32 getHashCase() const
  325. {
  326. return mHashCase;
  327. }
  328. U32 getOrCreateHashCase() const
  329. {
  330. if( mHashCase == U32_MAX )
  331. {
  332. PROFILE_SCOPE(StringData_getOrCreateHashCase);
  333. mHashCase = Torque::hash((const U8 *)(mData), mLength, 0);
  334. }
  335. return mHashCase;
  336. }
  337. U32 getHashNoCase() const
  338. {
  339. return mHashNoCase;
  340. }
  341. U32 getOrCreateHashNoCase() const
  342. {
  343. if( mHashNoCase == U32_MAX)
  344. {
  345. PROFILE_SCOPE(StringData_getOrCreateHashNoCase);
  346. UTF8 *lower = new UTF8[ mLength + 1 ];
  347. dStrncpy( lower, utf8(), mLength );
  348. lower[ mLength ] = 0;
  349. dStrlwr( lower );
  350. mHashNoCase = Torque::hash( (const U8*)lower, mLength, 0 );
  351. delete [] lower;
  352. }
  353. return mHashNoCase;
  354. }
  355. U32 getNumChars() const
  356. {
  357. if( mNumChars == U32_MAX )
  358. mNumChars = dStrlen( utf16() );
  359. return mNumChars;
  360. }
  361. bool isInterned() const
  362. {
  363. return mIsInterned;
  364. }
  365. static StringData* Empty()
  366. {
  367. static UTF16 emptyUTF16[1] = { 0 };
  368. static UTF8 emptyUTF8[1] = { 0 };
  369. static StringDataImpl empty =
  370. {
  371. #ifdef TORQUE_DEBUG
  372. emptyUTF8, // mString
  373. #endif
  374. U32_MAX, // mRefCount
  375. 0, // mLength
  376. 0, // mNumChars
  377. 0, // mHashCase
  378. 0, // mHashNoCase
  379. emptyUTF16, // mUTF16
  380. true, // mIsInterned
  381. { 0 } // mData
  382. };
  383. return ( StringData* ) &empty;
  384. }
  385. };
  386. //-----------------------------------------------------------------------------
  387. namespace DictHash
  388. {
  389. inline U32 hash( String::StringData* data )
  390. {
  391. return data->getOrCreateHashCase();
  392. }
  393. }
  394. namespace KeyCmp
  395. {
  396. template<>
  397. inline bool equals<>( String::StringData* const& d1, String::StringData* const& d2 )
  398. {
  399. return ( String::compare( d1->utf8(), d2->utf8() ) == 0 );
  400. }
  401. }
  402. /// Type for the intern string table. We don't want String instances directly
  403. /// on the table so that destructors don't run when the table is destroyed. This
  404. /// is because we really shouldn't depend on dtor ordering within this file and thus
  405. /// we can't tell whether the intern string memory is freed before or after the
  406. /// table is destroyed.
  407. struct StringInternTable : public HashTable< String::StringData*, String::StringData* >
  408. {
  409. Mutex mMutex;
  410. DataChunker mChunker;
  411. };
  412. static StringInternTable* sInternTable;
  413. struct KillInternTable
  414. {
  415. ~KillInternTable()
  416. {
  417. if( sInternTable )
  418. delete sInternTable;
  419. }
  420. };
  421. static KillInternTable sKillInternTable;
  422. //-----------------------------------------------------------------------------
  423. #ifdef TORQUE_DEBUG
  424. /// Tracks the number of bytes allocated for strings.
  425. /// @bug This currently does not include UTF16 allocations.
  426. static U32 sgStringMemBytes;
  427. /// Tracks the number of Strings which are currently instantiated.
  428. static U32 sgStringInstances;
  429. #endif
  430. DefineEngineFunction( dumpStringMemStats, void, (), , "()"
  431. "@brief Dumps information about String memory usage\n\n"
  432. "@ingroup Debugging\n"
  433. "@ingroup Strings\n")
  434. {
  435. #ifdef TORQUE_DEBUG
  436. Con::printf( "String Data: %i instances, %i bytes", sgStringInstances, sgStringMemBytes );
  437. #endif
  438. }
  439. //-----------------------------------------------------------------------------
  440. String::String()
  441. {
  442. PROFILE_SCOPE(String_default_constructor);
  443. _string = StringData::Empty();
  444. }
  445. String::String(const String &str)
  446. {
  447. PROFILE_SCOPE(String_String_constructor);
  448. _string = str._string;
  449. _string->addRef();
  450. }
  451. String::String(const StringChar *str)
  452. {
  453. PROFILE_SCOPE(String_char_constructor);
  454. if( str && *str )
  455. {
  456. U32 len = dStrlen(str);
  457. _string = StringData::Create(str, len);
  458. }
  459. else
  460. _string = StringData::Empty();
  461. }
  462. String::String(const StringChar *str, SizeType len)
  463. {
  464. PROFILE_SCOPE(String_char_len_constructor);
  465. if (str && *str && len!=0)
  466. {
  467. _string = StringData::Create(str, len);
  468. }
  469. else
  470. _string = StringData::Empty();
  471. }
  472. String::String(const UTF16 *str)
  473. {
  474. PROFILE_SCOPE(String_UTF16_constructor);
  475. if( str && str[ 0 ] )
  476. {
  477. UTF8* utf8 = createUTF8string( str );
  478. U32 len = dStrlen( utf8 );
  479. _string = StringData::Create(utf8, len);
  480. delete [] utf8;
  481. }
  482. else
  483. _string = StringData::Empty();
  484. }
  485. String::~String()
  486. {
  487. if (_string && _string != StringData::Empty())
  488. _string->release();
  489. }
  490. //-----------------------------------------------------------------------------
  491. String String::intern() const
  492. {
  493. if( isInterned() )
  494. return *this;
  495. // Create the intern table, if we haven't already.
  496. if( !sInternTable )
  497. sInternTable = new StringInternTable;
  498. // Lock the string table.
  499. MutexHandle mutex;
  500. mutex.lock( &sInternTable->mMutex );
  501. // Lookup.
  502. StringInternTable::Iterator iter = sInternTable->find( _string );
  503. if( iter != sInternTable->end() )
  504. return ( *iter ).value;
  505. // Create new.
  506. StringData* data = StringData::Create(c_str(), length(), sInternTable->mChunker, true);
  507. iter = sInternTable->insertUnique( data, data );
  508. return ( *iter ).value;
  509. }
  510. //-----------------------------------------------------------------------------
  511. const StringChar* String::c_str() const
  512. {
  513. return _string->utf8();
  514. }
  515. const UTF16 *String::utf16() const
  516. {
  517. return _string->utf16();
  518. }
  519. String::SizeType String::length() const
  520. {
  521. return _string->getLength();
  522. }
  523. String::SizeType String::size() const
  524. {
  525. return _string->getDataSize();
  526. }
  527. String::SizeType String::numChars() const
  528. {
  529. return _string->getNumChars();
  530. }
  531. bool String::isEmpty() const
  532. {
  533. return ( _string == StringData::Empty() );
  534. }
  535. bool String::isEmpty(const char* str)
  536. {
  537. return str == 0 || str[0] == '\0';
  538. }
  539. bool String::isShared() const
  540. {
  541. return _string->isShared();
  542. }
  543. bool String::isSame( const String& str ) const
  544. {
  545. return ( _string == str._string );
  546. }
  547. bool String::isInterned() const
  548. {
  549. return ( _string->isInterned() );
  550. }
  551. U32 String::getHashCaseSensitive() const
  552. {
  553. return _string->getOrCreateHashCase();
  554. }
  555. U32 String::getHashCaseInsensitive() const
  556. {
  557. return _string->getOrCreateHashNoCase();
  558. }
  559. //-----------------------------------------------------------------------------
  560. String::SizeType String::find(const String &str, SizeType pos, U32 mode) const
  561. {
  562. return find(str._string->utf8(), pos, mode);
  563. }
  564. String& String::insert(SizeType pos, const String &str)
  565. {
  566. return insert(pos, str._string->utf8());
  567. }
  568. String& String::replace(SizeType pos, SizeType len, const String &str)
  569. {
  570. return replace(pos, len, str._string->utf8());
  571. }
  572. //-----------------------------------------------------------------------------
  573. String& String::operator=(StringChar c)
  574. {
  575. _string->release();
  576. _string = StringData::Create(NULL, 2);
  577. _string->utf8()[ 0 ] = c;
  578. _string->utf8()[ 1 ] = '\0';
  579. return *this;
  580. }
  581. String& String::operator+=(StringChar c)
  582. {
  583. // Append the given string into a new string
  584. U32 len = _string->getLength();
  585. StringData* sub = StringData::Create(NULL, len + 1);
  586. copy( sub->utf8(), _string->utf8(), len );
  587. sub->utf8()[len] = c;
  588. sub->utf8()[len+1] = 0;
  589. _string->release();
  590. _string = sub;
  591. return *this;
  592. }
  593. //-----------------------------------------------------------------------------
  594. String& String::operator=(const StringChar *str)
  595. {
  596. // Protect against self assignment which is not only a
  597. // waste of time, but can also lead to the string being
  598. // freed before it can be reassigned.
  599. if ( _string->utf8() == str )
  600. return *this;
  601. _string->release();
  602. if (str && *str)
  603. {
  604. U32 len = dStrlen(str);
  605. _string = StringData::Create(str, len);
  606. }
  607. else
  608. _string = StringData::Empty();
  609. return *this;
  610. }
  611. String& String::operator=(const String &src)
  612. {
  613. // Inc src first to avoid assignment to self problems.
  614. src._string->addRef();
  615. _string->release();
  616. _string = src._string;
  617. return *this;
  618. }
  619. String& String::operator+=(const StringChar *src)
  620. {
  621. if( src == NULL || !*src )
  622. return *this;
  623. // Append the given string into a new string
  624. U32 lena = _string->getLength();
  625. U32 lenb = dStrlen(src);
  626. U32 newlen = lena + lenb;
  627. StringData* sub;
  628. if( !newlen )
  629. sub = StringData::Empty();
  630. else
  631. {
  632. sub = StringData::Create(NULL, newlen);
  633. copy(sub->utf8(),_string->utf8(),lena);
  634. copy(sub->utf8() + lena,src,lenb + 1);
  635. }
  636. _string->release();
  637. _string = sub;
  638. return *this;
  639. }
  640. String& String::operator+=(const String &src)
  641. {
  642. if( src.isEmpty() )
  643. return *this;
  644. // Append the given string into a new string
  645. U32 lena = _string->getLength();
  646. U32 lenb = src._string->getLength();
  647. U32 newlen = lena + lenb;
  648. StringData* sub;
  649. if( !newlen )
  650. sub = StringData::Empty();
  651. else
  652. {
  653. sub = StringData::Create(NULL, newlen);
  654. copy(sub->utf8(),_string->utf8(),lena);
  655. copy(sub->utf8() + lena,src._string->utf8(),lenb + 1);
  656. }
  657. _string->release();
  658. _string = sub;
  659. return *this;
  660. }
  661. //-----------------------------------------------------------------------------
  662. String operator+(const String &a, const String &b)
  663. {
  664. PROFILE_SCOPE( String_String_plus_String );
  665. if( a.isEmpty() )
  666. return b;
  667. else if( b.isEmpty() )
  668. return a;
  669. U32 lena = a.length();
  670. U32 lenb = b.length();
  671. String::StringData* sub = String::StringData::Create(NULL, lena + lenb);
  672. String::copy(sub->utf8(),a._string->utf8(),lena);
  673. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  674. return String(sub);
  675. }
  676. String operator+(const String &a, StringChar c)
  677. {
  678. //PROFILE_SCOPE( String_String_plus_Char );
  679. U32 lena = a.length();
  680. String::StringData* sub = String::StringData::Create(NULL, lena + 1);
  681. String::copy(sub->utf8(),a._string->utf8(),lena);
  682. sub->utf8()[lena] = c;
  683. sub->utf8()[lena+1] = 0;
  684. return String(sub);
  685. }
  686. String operator+(StringChar c, const String &a)
  687. {
  688. //PROFILE_SCOPE( String_Char_plus_String );
  689. U32 lena = a.length();
  690. String::StringData* sub = String::StringData::Create(NULL, lena + 1);
  691. String::copy(sub->utf8() + 1,a._string->utf8(),lena + 1);
  692. sub->utf8()[0] = c;
  693. return String(sub);
  694. }
  695. String operator+(const String &a, const StringChar *b)
  696. {
  697. //PROFILE_SCOPE( String_String_plus_CString );
  698. AssertFatal(b,"String:: Invalid null ptr argument");
  699. if( a.isEmpty() )
  700. return String( b );
  701. U32 lena = a.length();
  702. U32 lenb = dStrlen(b);
  703. if( !lenb )
  704. return a;
  705. String::StringData* sub = String::StringData::Create(NULL, lena + lenb);
  706. String::copy(sub->utf8(),a._string->utf8(),lena);
  707. String::copy(sub->utf8() + lena,b,lenb + 1);
  708. return String(sub);
  709. }
  710. String operator+(const StringChar *a, const String &b)
  711. {
  712. //PROFILE_SCOPE( String_CString_plus_String );
  713. AssertFatal(a,"String:: Invalid null ptr argument");
  714. if( b.isEmpty() )
  715. return String( a );
  716. U32 lena = dStrlen(a);
  717. if( !lena )
  718. return b;
  719. U32 lenb = b.length();
  720. String::StringData* sub = String::StringData::Create(NULL, lena + lenb);
  721. String::copy(sub->utf8(),a,lena);
  722. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  723. return String(sub);
  724. }
  725. bool String::operator==(const String &str) const
  726. {
  727. //PROFILE_SCOPE( String_op_equal );
  728. if( str._string == _string )
  729. return true;
  730. else if( str._string->isInterned() && _string->isInterned() )
  731. return false;
  732. else if( str.length() != length() )
  733. return false;
  734. else if( str._string->getHashCase() != U32_MAX
  735. && _string->getHashCase() != U32_MAX
  736. && str._string->getHashCase() != _string->getHashCase() )
  737. return false;
  738. else
  739. return ( dMemcmp( str._string->utf8(), _string->utf8(), _string->getLength() ) == 0 );
  740. }
  741. bool String::operator==( StringChar c ) const
  742. {
  743. if( !_string || _string->getLength() != 1 )
  744. return false;
  745. else
  746. return ( _string->utf8()[ 0 ] == c );
  747. }
  748. bool String::operator<(const String &str) const
  749. {
  750. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) < 0 );
  751. }
  752. bool String::operator>(const String &str) const
  753. {
  754. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) > 0 );
  755. }
  756. bool String::operator<=(const String &str) const
  757. {
  758. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) <= 0 );
  759. }
  760. bool String::operator>=(const String &str) const
  761. {
  762. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) >= 0 );
  763. }
  764. //-----------------------------------------------------------------------------
  765. // Base functions for string comparison
  766. S32 String::compare(const StringChar *str, SizeType len, U32 mode) const
  767. {
  768. PROFILE_SCOPE( String_compare );
  769. AssertFatal(str,"String:: Invalid null ptr argument");
  770. const StringChar *p1 = _string->utf8();
  771. const StringChar *p2 = str;
  772. if (p1 == p2)
  773. return 0;
  774. if( mode & String::Right )
  775. {
  776. U32 n = len;
  777. if( n > length() )
  778. n = length();
  779. p1 += length() - n;
  780. p2 += dStrlen( str ) - n;
  781. }
  782. if (mode & String::NoCase)
  783. {
  784. if (len)
  785. {
  786. for (;--len; p1++,p2++)
  787. {
  788. if (dTolower(*p1) != dTolower(*p2) || !*p1)
  789. break;
  790. }
  791. }
  792. else
  793. {
  794. while (dTolower(*p1) == dTolower(*p2) && *p1)
  795. {
  796. p1++;
  797. p2++;
  798. }
  799. }
  800. return dTolower(*p1) - dTolower(*p2);
  801. }
  802. if (len)
  803. return dMemcmp(p1,p2,len);
  804. while (*p1 == *p2 && *p1)
  805. {
  806. p1++;
  807. p2++;
  808. }
  809. return *p1 - *p2;
  810. }
  811. S32 String::compare(const String &str, SizeType len, U32 mode) const
  812. {
  813. if ( str._string == _string )
  814. return 0;
  815. return compare( str.c_str(), len, mode );
  816. }
  817. S32 String::compare(const char *str1, const char *str2)
  818. {
  819. return strcmp(str1, str2);
  820. }
  821. S32 String::compare(const UTF16 *str1, const UTF16 *str2)
  822. {
  823. #if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)
  824. return wcscmp(reinterpret_cast<const wchar_t *>(str1), reinterpret_cast<const wchar_t *>(str2));
  825. #else
  826. S32 ret;
  827. const UTF16 *a, *b;
  828. a = str1;
  829. b = str2;
  830. while (((ret = *a - *b) == 0) && *a && *b)
  831. a++, b++;
  832. return ret;
  833. #endif
  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 = StringData::Create(NULL, newlen);
  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 = StringData::Create(NULL, newlen);
  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 = StringData::Create(NULL, newlen);
  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 = StringData::Create(_string->utf8(), length());
  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 = StringData::Create(NULL, newSize - 1);
  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 = StringData::Create(_string->utf8() + pos, len);
  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 = StringData::Create(start, len);
  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)
  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, va_list args )
  1151. {
  1152. _len=0;
  1153. return formatAppend(format,args);
  1154. }
  1155. S32 String::StrFormat::formatAppend( const char *format, va_list 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, 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, va_list 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 = StringData::Create(NULL, len);
  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. String::StringData* sub = StringData::Create(start, len);
  1259. return sub;
  1260. }
  1261. String String::ToLower(const String &string)
  1262. {
  1263. if ( string.isEmpty() )
  1264. return String();
  1265. String::StringData* sub = StringData::Create(string, string.length());
  1266. dStrlwr( sub->utf8() );
  1267. return sub;
  1268. }
  1269. String String::ToUpper(const String &string)
  1270. {
  1271. if ( string.isEmpty() )
  1272. return String();
  1273. String::StringData* sub = StringData::Create(string, string.length());
  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 = (isdigit(*p) ? 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. }
  1304. String String::GetFirstNumber(const char* str, U32& startPos, U32& endPos)
  1305. {
  1306. // Check for trivial strings
  1307. if (!str || !str[0])
  1308. return String::EmptyString;
  1309. // Find the number at the end of the string
  1310. String base(str);
  1311. const char* p = base.c_str();
  1312. const char* end = base.c_str() + base.length() - 1;
  1313. bool dec = false;
  1314. startPos = 0;
  1315. //Check if we are just a digit
  1316. if(p == end && isdigit(*p))
  1317. return base;
  1318. //Look for the first digit
  1319. while ((p != end) && (dIsspace(*p) || !isdigit(*p)))
  1320. {
  1321. p++;
  1322. startPos++;
  1323. }
  1324. //Handle if we are at the end and found nothing
  1325. if(p == end && !isdigit(*p))
  1326. return "";
  1327. //update our end position at least to the start of our number
  1328. endPos = startPos;
  1329. //Backup our ptr
  1330. const char* backup = p;
  1331. //Check for any negative or decimal values
  1332. if(startPos > 0)
  1333. {
  1334. p--;
  1335. startPos--;
  1336. if(*p == '.')
  1337. {
  1338. dec = true;
  1339. //ignore any duplicate periods
  1340. while ((p != base.c_str()) && (*p == '.'))
  1341. {
  1342. p--;
  1343. startPos--;
  1344. }
  1345. //Found a decimal lets still check for negative sign
  1346. if(startPos > 0)
  1347. {
  1348. p--;
  1349. startPos--;
  1350. if((*p != '-') && (*p != '_'))
  1351. {
  1352. startPos++;
  1353. p++;
  1354. }
  1355. }
  1356. }
  1357. else if((*p != '-') && (*p != '_'))
  1358. {
  1359. //go back to where we where cause no decimal or negative sign found
  1360. startPos++;
  1361. p++;
  1362. }
  1363. }
  1364. //Restore where we were
  1365. p = backup;
  1366. //look for the end of the digits
  1367. bool justFoundDec = false;
  1368. while (p != end)
  1369. {
  1370. if(*p == '.')
  1371. {
  1372. if(dec && !justFoundDec)
  1373. break;
  1374. else
  1375. {
  1376. dec = true;
  1377. justFoundDec = true;
  1378. }
  1379. }
  1380. else if(!isdigit(*p))
  1381. break;
  1382. else if(justFoundDec)
  1383. justFoundDec = false;
  1384. p++;
  1385. endPos++;
  1386. }
  1387. U32 len = (!isdigit(*p)) ? endPos - startPos : (endPos + 1) - startPos;
  1388. return base.substr(startPos, len);
  1389. }