str.cpp 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753
  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 = createUTF16string( 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 ( String::compare( 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. DefineEngineFunction( 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 = static_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 = static_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. _string = new ( len ) StringData( str );
  490. }
  491. else
  492. _string = StringData::Empty();
  493. }
  494. String::String(const UTF16 *str)
  495. {
  496. PROFILE_SCOPE(String_UTF16_constructor);
  497. if( str && str[ 0 ] )
  498. {
  499. UTF8* utf8 = createUTF8string( str );
  500. U32 len = dStrlen( utf8 );
  501. _string = new ( len ) StringData( utf8 );
  502. delete [] utf8;
  503. }
  504. else
  505. _string = StringData::Empty();
  506. }
  507. String::~String()
  508. {
  509. if (_string && _string != StringData::Empty())
  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::isEmpty(const char* str)
  558. {
  559. return str == 0 || str[0] == '\0';
  560. }
  561. bool String::isShared() const
  562. {
  563. return _string->isShared();
  564. }
  565. bool String::isSame( const String& str ) const
  566. {
  567. return ( _string == str._string );
  568. }
  569. bool String::isInterned() const
  570. {
  571. return ( _string->isInterned() );
  572. }
  573. U32 String::getHashCaseSensitive() const
  574. {
  575. return _string->getOrCreateHashCase();
  576. }
  577. U32 String::getHashCaseInsensitive() const
  578. {
  579. return _string->getOrCreateHashNoCase();
  580. }
  581. //-----------------------------------------------------------------------------
  582. String::SizeType String::find(const String &str, SizeType pos, U32 mode) const
  583. {
  584. return find(str._string->utf8(), pos, mode);
  585. }
  586. String& String::insert(SizeType pos, const String &str)
  587. {
  588. return insert(pos, str._string->utf8());
  589. }
  590. String& String::replace(SizeType pos, SizeType len, const String &str)
  591. {
  592. return replace(pos, len, str._string->utf8());
  593. }
  594. //-----------------------------------------------------------------------------
  595. String& String::operator=(StringChar c)
  596. {
  597. _string->release();
  598. _string = new ( 2 ) StringData( 0 );
  599. _string->utf8()[ 0 ] = c;
  600. _string->utf8()[ 1 ] = '\0';
  601. return *this;
  602. }
  603. String& String::operator+=(StringChar c)
  604. {
  605. // Append the given string into a new string
  606. U32 len = _string->getLength();
  607. StringData* sub = new ( len + 1 ) StringData( NULL );
  608. copy( sub->utf8(), _string->utf8(), len );
  609. sub->utf8()[len] = c;
  610. sub->utf8()[len+1] = 0;
  611. _string->release();
  612. _string = sub;
  613. return *this;
  614. }
  615. //-----------------------------------------------------------------------------
  616. String& String::operator=(const StringChar *str)
  617. {
  618. // Protect against self assignment which is not only a
  619. // waste of time, but can also lead to the string being
  620. // freed before it can be reassigned.
  621. if ( _string->utf8() == str )
  622. return *this;
  623. _string->release();
  624. if (str && *str)
  625. {
  626. U32 len = dStrlen(str);
  627. _string = new ( len ) StringData( str );
  628. }
  629. else
  630. _string = StringData::Empty();
  631. return *this;
  632. }
  633. String& String::operator=(const String &src)
  634. {
  635. // Inc src first to avoid assignment to self problems.
  636. src._string->addRef();
  637. _string->release();
  638. _string = src._string;
  639. return *this;
  640. }
  641. String& String::operator+=(const StringChar *src)
  642. {
  643. if( src == NULL || !*src )
  644. return *this;
  645. // Append the given string into a new string
  646. U32 lena = _string->getLength();
  647. U32 lenb = dStrlen(src);
  648. U32 newlen = lena + lenb;
  649. StringData* sub;
  650. if( !newlen )
  651. sub = StringData::Empty();
  652. else
  653. {
  654. sub = new ( newlen ) StringData( NULL );
  655. copy(sub->utf8(),_string->utf8(),lena);
  656. copy(sub->utf8() + lena,src,lenb + 1);
  657. }
  658. _string->release();
  659. _string = sub;
  660. return *this;
  661. }
  662. String& String::operator+=(const String &src)
  663. {
  664. if( src.isEmpty() )
  665. return *this;
  666. // Append the given string into a new string
  667. U32 lena = _string->getLength();
  668. U32 lenb = src._string->getLength();
  669. U32 newlen = lena + lenb;
  670. StringData* sub;
  671. if( !newlen )
  672. sub = StringData::Empty();
  673. else
  674. {
  675. sub = new ( newlen ) StringData( NULL );
  676. copy(sub->utf8(),_string->utf8(),lena);
  677. copy(sub->utf8() + lena,src._string->utf8(),lenb + 1);
  678. }
  679. _string->release();
  680. _string = sub;
  681. return *this;
  682. }
  683. //-----------------------------------------------------------------------------
  684. String operator+(const String &a, const String &b)
  685. {
  686. PROFILE_SCOPE( String_String_plus_String );
  687. if( a.isEmpty() )
  688. return b;
  689. else if( b.isEmpty() )
  690. return a;
  691. U32 lena = a.length();
  692. U32 lenb = b.length();
  693. String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
  694. String::copy(sub->utf8(),a._string->utf8(),lena);
  695. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  696. return String(sub);
  697. }
  698. String operator+(const String &a, StringChar c)
  699. {
  700. //PROFILE_SCOPE( String_String_plus_Char );
  701. U32 lena = a.length();
  702. String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
  703. String::copy(sub->utf8(),a._string->utf8(),lena);
  704. sub->utf8()[lena] = c;
  705. sub->utf8()[lena+1] = 0;
  706. return String(sub);
  707. }
  708. String operator+(StringChar c, const String &a)
  709. {
  710. //PROFILE_SCOPE( String_Char_plus_String );
  711. U32 lena = a.length();
  712. String::StringData *sub = new ( lena + 1 ) String::StringData( NULL );
  713. String::copy(sub->utf8() + 1,a._string->utf8(),lena + 1);
  714. sub->utf8()[0] = c;
  715. return String(sub);
  716. }
  717. String operator+(const String &a, const StringChar *b)
  718. {
  719. //PROFILE_SCOPE( String_String_plus_CString );
  720. AssertFatal(b,"String:: Invalid null ptr argument");
  721. if( a.isEmpty() )
  722. return String( b );
  723. U32 lena = a.length();
  724. U32 lenb = dStrlen(b);
  725. if( !lenb )
  726. return a;
  727. String::StringData *sub = new ( lena + lenb ) String::StringData( NULL );
  728. String::copy(sub->utf8(),a._string->utf8(),lena);
  729. String::copy(sub->utf8() + lena,b,lenb + 1);
  730. return String(sub);
  731. }
  732. String operator+(const StringChar *a, const String &b)
  733. {
  734. //PROFILE_SCOPE( String_CString_plus_String );
  735. AssertFatal(a,"String:: Invalid null ptr argument");
  736. if( b.isEmpty() )
  737. return String( a );
  738. U32 lena = dStrlen(a);
  739. if( !lena )
  740. return b;
  741. U32 lenb = b.length();
  742. String::StringData* sub = new ( lena + lenb ) String::StringData( NULL );
  743. String::copy(sub->utf8(),a,lena);
  744. String::copy(sub->utf8() + lena,b._string->utf8(),lenb + 1);
  745. return String(sub);
  746. }
  747. bool String::operator==(const String &str) const
  748. {
  749. //PROFILE_SCOPE( String_op_equal );
  750. if( str._string == _string )
  751. return true;
  752. else if( str._string->isInterned() && _string->isInterned() )
  753. return false;
  754. else if( str.length() != length() )
  755. return false;
  756. else if( str._string->getHashCase() != U32_MAX
  757. && _string->getHashCase() != U32_MAX
  758. && str._string->getHashCase() != _string->getHashCase() )
  759. return false;
  760. else
  761. return ( dMemcmp( str._string->utf8(), _string->utf8(), _string->getLength() ) == 0 );
  762. }
  763. bool String::operator==( StringChar c ) const
  764. {
  765. if( !_string || _string->getLength() != 1 )
  766. return false;
  767. else
  768. return ( _string->utf8()[ 0 ] == c );
  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. bool String::operator>=(const String &str) const
  783. {
  784. return ( dStrnatcmp( _string->utf8(), str._string->utf8() ) >= 0 );
  785. }
  786. //-----------------------------------------------------------------------------
  787. // Base functions for string comparison
  788. S32 String::compare(const StringChar *str, SizeType len, U32 mode) const
  789. {
  790. PROFILE_SCOPE( String_compare );
  791. AssertFatal(str,"String:: Invalid null ptr argument");
  792. const StringChar *p1 = _string->utf8();
  793. const StringChar *p2 = str;
  794. if (p1 == p2)
  795. return 0;
  796. if( mode & String::Right )
  797. {
  798. U32 n = len;
  799. if( n > length() )
  800. n = length();
  801. p1 += length() - n;
  802. p2 += dStrlen( str ) - n;
  803. }
  804. if (mode & String::NoCase)
  805. {
  806. if (len)
  807. {
  808. for (;--len; p1++,p2++)
  809. {
  810. if (dTolower(*p1) != dTolower(*p2) || !*p1)
  811. break;
  812. }
  813. }
  814. else
  815. {
  816. while (dTolower(*p1) == dTolower(*p2) && *p1)
  817. {
  818. p1++;
  819. p2++;
  820. }
  821. }
  822. return dTolower(*p1) - dTolower(*p2);
  823. }
  824. if (len)
  825. return dMemcmp(p1,p2,len);
  826. while (*p1 == *p2 && *p1)
  827. {
  828. p1++;
  829. p2++;
  830. }
  831. return *p1 - *p2;
  832. }
  833. S32 String::compare(const String &str, SizeType len, U32 mode) const
  834. {
  835. if ( str._string == _string )
  836. return 0;
  837. return compare( str.c_str(), len, mode );
  838. }
  839. S32 String::compare(const char *str1, const char *str2)
  840. {
  841. return strcmp(str1, str2);
  842. }
  843. S32 String::compare(const UTF16 *str1, const UTF16 *str2)
  844. {
  845. #if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)
  846. return wcscmp(reinterpret_cast<const wchar_t *>(str1), reinterpret_cast<const wchar_t *>(str2));
  847. #else
  848. S32 ret;
  849. const UTF16 *a, *b;
  850. a = str1;
  851. b = str2;
  852. while (((ret = *a - *b) == 0) && *a && *b)
  853. a++, b++;
  854. return ret;
  855. #endif
  856. }
  857. bool String::equal(const String &str, U32 mode) const
  858. {
  859. if( !mode )
  860. return ( *this == str );
  861. else
  862. {
  863. if( _string == str._string )
  864. return true;
  865. else if( _string->isInterned() && str._string->isInterned() )
  866. return false;
  867. else if( length() != str.length() )
  868. return false;
  869. else if( _string->getHashNoCase() != U32_MAX
  870. && str._string->getHashNoCase() != U32_MAX
  871. && _string->getHashNoCase() != str._string->getHashNoCase() )
  872. return false;
  873. else
  874. return ( compare( str.c_str(), length(), mode ) == 0 );
  875. }
  876. }
  877. //-----------------------------------------------------------------------------
  878. String::SizeType String::find(StringChar c, SizeType pos, U32 mode) const
  879. {
  880. const StringChar* ptr = StrFind(_string->utf8(),c,pos,mode);
  881. return ptr? SizeType(ptr - _string->utf8()): NPos;
  882. }
  883. String::SizeType String::find(const StringChar *str, SizeType pos, U32 mode) const
  884. {
  885. AssertFatal(str,"String:: Invalid null ptr argument");
  886. const StringChar* ptr = StrFind(_string->utf8(),str,pos,mode);
  887. return ptr? SizeType(ptr - _string->utf8()): NPos;
  888. }
  889. //-----------------------------------------------------------------------------
  890. String& String::insert(SizeType pos, const StringChar *str)
  891. {
  892. AssertFatal(str,"String:: Invalid null ptr argument");
  893. return insert(pos,str,dStrlen(str));
  894. }
  895. ///@todo review for error checking
  896. String& String::insert(SizeType pos, const StringChar *str, SizeType len)
  897. {
  898. if( !len )
  899. return *this;
  900. AssertFatal( str, "String:: Invalid null ptr argument" );
  901. SizeType lena = length();
  902. AssertFatal((pos <= lena),"Calling String::insert with position greater than length");
  903. U32 newlen = lena + len;
  904. StringData *sub;
  905. if( !newlen )
  906. sub = StringData::Empty();
  907. else
  908. {
  909. sub = new ( newlen ) StringData( NULL );
  910. String::copy(sub->utf8(),_string->utf8(),pos);
  911. String::copy(sub->utf8() + pos,str,len);
  912. String::copy(sub->utf8() + pos + len,_string->utf8() + pos,lena - pos + 1);
  913. }
  914. _string->release();
  915. _string = sub;
  916. return *this;
  917. }
  918. String& String::erase(SizeType pos, SizeType len)
  919. {
  920. AssertFatal( len != 0, "String::erase() - Calling String::erase with 0 length" );
  921. AssertFatal( ( pos + len ) <= length(), "String::erase() - Invalid string region" );
  922. if( !len )
  923. return *this;
  924. SizeType slen = length();
  925. U32 newlen = slen - len;
  926. StringData *sub;
  927. if( !newlen )
  928. sub = StringData::Empty();
  929. else
  930. {
  931. sub = new ( newlen ) StringData( NULL );
  932. if (pos > 0)
  933. String::copy(sub->utf8(),_string->utf8(),pos);
  934. String::copy(sub->utf8() + pos, _string->utf8() + pos + len, slen - (pos + len) + 1);
  935. }
  936. _string->release();
  937. _string = sub;
  938. return *this;
  939. }
  940. ///@todo review for error checking
  941. String& String::replace(SizeType pos, SizeType len, const StringChar *str)
  942. {
  943. AssertFatal( str, "String::replace() - Invalid null ptr argument" );
  944. AssertFatal( len != 0, "String::replace() - Zero length" );
  945. AssertFatal( ( pos + len ) <= length(), "String::replace() - Invalid string region" );
  946. SizeType slen = length();
  947. SizeType rlen = dStrlen(str);
  948. U32 newlen = slen - len + rlen;
  949. StringData *sub;
  950. if( !newlen )
  951. sub = StringData::Empty();
  952. else
  953. {
  954. sub = new ( newlen ) StringData( NULL );
  955. String::copy(sub->utf8(),_string->utf8(), pos);
  956. String::copy(sub->utf8() + pos,str,rlen);
  957. String::copy(sub->utf8() + pos + rlen,_string->utf8() + pos + len,slen - pos - len + 1);
  958. }
  959. _string->release();
  960. _string = sub;
  961. return *this;
  962. }
  963. String& String::replace( StringChar c1, StringChar c2 )
  964. {
  965. if( isEmpty() )
  966. return *this;
  967. // Create the new string lazily so that we don't needlessly
  968. // dup strings when there is nothing to replace.
  969. StringData* sub = NULL;
  970. bool foundReplacement = false;
  971. StringChar* c = _string->utf8();
  972. while( *c )
  973. {
  974. if( *c == c1 )
  975. {
  976. if( !foundReplacement )
  977. {
  978. sub = new ( length() ) StringData( _string->utf8() );
  979. c = &sub->utf8()[ c - _string->utf8() ];
  980. foundReplacement = true;
  981. }
  982. *c = c2;
  983. }
  984. c++;
  985. }
  986. if( foundReplacement )
  987. {
  988. _string->release();
  989. _string = sub;
  990. }
  991. return *this;
  992. }
  993. String &String::replace(const String &s1, const String &s2)
  994. {
  995. // Find number of occurrences of s1 and
  996. // Calculate length of the new string...
  997. const U32 &s1len = s1.length();
  998. const U32 &s2len = s2.length();
  999. U32 pos = 0;
  1000. Vector<U32> indices;
  1001. StringChar *walk = _string->utf8();
  1002. while ( walk )
  1003. {
  1004. // Casting away the const... was there a better way?
  1005. walk = (StringChar*)StrFind( _string->utf8(), s1.c_str(), pos, Case|Left );
  1006. if ( walk )
  1007. {
  1008. pos = SizeType(walk - _string->utf8());
  1009. indices.push_back( pos );
  1010. pos += s1len;
  1011. }
  1012. }
  1013. // Early-out, no StringDatas found.
  1014. if ( indices.size() == 0 )
  1015. return *this;
  1016. U32 newSize = size() - ( indices.size() * s1len ) + ( indices.size() * s2len );
  1017. StringData *sub;
  1018. if( newSize == 1 )
  1019. sub = StringData::Empty();
  1020. else
  1021. {
  1022. sub = new (newSize - 1 ) StringData( NULL );
  1023. // Now assemble the new string from the pieces of the old...
  1024. // Index into the old string
  1025. pos = 0;
  1026. // Index into the new string
  1027. U32 newPos = 0;
  1028. // Used to store a character count to be memcpy'd
  1029. U32 copyCharCount = 0;
  1030. for ( U32 i = 0; i < indices.size(); i++ )
  1031. {
  1032. const U32 &index = indices[i];
  1033. // Number of chars (if any) before the next indexed StringData
  1034. copyCharCount = index - pos;
  1035. // Copy chars before the StringData if we have any.
  1036. if ( copyCharCount > 0 )
  1037. {
  1038. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1039. newPos += copyCharCount;
  1040. }
  1041. // Copy over the replacement string.
  1042. if ( s2len > 0 )
  1043. dMemcpy( sub->utf8() + newPos, s2._string->utf8(), s2len * sizeof(StringChar) );
  1044. newPos += s2len;
  1045. pos = index + s1len;
  1046. }
  1047. // There could be characters left in the original string after the last
  1048. // StringData occurrence, which we need to copy now - outside the loop.
  1049. copyCharCount = length() - indices.last() - s1len;
  1050. if ( copyCharCount != 0 )
  1051. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1052. // Null terminate it!
  1053. sub->utf8()[newSize-1] = 0;
  1054. }
  1055. _string->release();
  1056. _string = sub;
  1057. return *this;
  1058. }
  1059. //-----------------------------------------------------------------------------
  1060. String String::substr(SizeType pos, SizeType len) const
  1061. {
  1062. //PROFILE_SCOPE( String_substr );
  1063. AssertFatal( pos <= length(), "String::substr - Invalid position!" );
  1064. if ( len == -1 )
  1065. len = length() - pos;
  1066. AssertFatal( len + pos <= length(), "String::substr - Invalid length!" );
  1067. StringData* sub;
  1068. if( !len )
  1069. sub = StringData::Empty();
  1070. else
  1071. sub = new ( len ) StringData( _string->utf8() + pos );
  1072. return sub;
  1073. }
  1074. //-----------------------------------------------------------------------------
  1075. String String::trim() const
  1076. {
  1077. if( isEmpty() )
  1078. return *this;
  1079. const StringChar* start = _string->utf8();
  1080. while( *start && dIsspace( *start ) )
  1081. start ++;
  1082. const StringChar* end = _string->utf8() + length() - 1;
  1083. while( end > start && dIsspace( *end ) )
  1084. end --;
  1085. end ++;
  1086. const U32 len = end - start;
  1087. if( len == length() )
  1088. return *this;
  1089. StringData* sub;
  1090. if( !len )
  1091. sub = StringData::Empty();
  1092. else
  1093. sub = new ( len ) StringData( start );
  1094. return sub;
  1095. }
  1096. //-----------------------------------------------------------------------------
  1097. String String::expandEscapes() const
  1098. {
  1099. char* tmp = ( char* ) dMalloc( length() * 2 + 1 ); // worst-case situation.
  1100. expandEscape( tmp, c_str() );
  1101. String str( tmp );
  1102. dFree( tmp );
  1103. return str;
  1104. }
  1105. //-----------------------------------------------------------------------------
  1106. String String::collapseEscapes() const
  1107. {
  1108. char* tmp = dStrdup( c_str() );
  1109. collapseEscape( tmp );
  1110. String str( tmp );
  1111. dFree( tmp );
  1112. return str;
  1113. }
  1114. //-----------------------------------------------------------------------------
  1115. void String::split( const char* delimiter, Vector< String >& outElements ) const
  1116. {
  1117. const char* ptr = _string->utf8();
  1118. const char* start = ptr;
  1119. while( *ptr )
  1120. {
  1121. // Search for start of delimiter.
  1122. if( *ptr != delimiter[ 0 ] )
  1123. ptr ++;
  1124. else
  1125. {
  1126. // Skip delimiter.
  1127. const char* end = ptr;
  1128. const char* del = delimiter;
  1129. while( *del && *del == *ptr )
  1130. {
  1131. ptr ++;
  1132. del ++;
  1133. }
  1134. // If we didn't match all of delimiter,
  1135. // continue with search.
  1136. if( *del != '\0' )
  1137. continue;
  1138. // Extract component.
  1139. outElements.push_back( String( start, end - start ) );
  1140. start = ptr;
  1141. }
  1142. }
  1143. // Add rest of string if there is any.
  1144. if( start != ptr )
  1145. outElements.push_back( start );
  1146. }
  1147. //-----------------------------------------------------------------------------
  1148. bool String::startsWith( const char* text ) const
  1149. {
  1150. return dStrStartsWith( _string->utf8(), text );
  1151. }
  1152. //-----------------------------------------------------------------------------
  1153. bool String::endsWith( const char* text ) const
  1154. {
  1155. return dStrEndsWith( _string->utf8(), text );
  1156. }
  1157. //-----------------------------------------------------------------------------
  1158. void String::copy(StringChar* dst, const StringChar *src, U32 len)
  1159. {
  1160. dMemcpy(dst, src, len * sizeof(StringChar));
  1161. }
  1162. //-----------------------------------------------------------------------------
  1163. #if defined(TORQUE_OS_WIN)
  1164. // This standard function is not defined when compiling with VC7...
  1165. #define vsnprintf _vsnprintf
  1166. #endif
  1167. String::StrFormat::~StrFormat()
  1168. {
  1169. if( _dynamicBuffer )
  1170. dFree( _dynamicBuffer );
  1171. }
  1172. S32 String::StrFormat::format( const char *format, va_list args )
  1173. {
  1174. _len=0;
  1175. return formatAppend(format,args);
  1176. }
  1177. S32 String::StrFormat::formatAppend( const char *format, va_list args )
  1178. {
  1179. // Format into the fixed buffer first.
  1180. S32 startLen = _len;
  1181. if (_dynamicBuffer == NULL)
  1182. {
  1183. _len += vsnprintf(_fixedBuffer + _len, sizeof(_fixedBuffer) - _len, format, args);
  1184. if (_len >= 0 && _len < sizeof(_fixedBuffer))
  1185. return _len;
  1186. // Start off the dynamic buffer at twice fixed buffer size
  1187. _len = startLen;
  1188. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1189. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1190. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1191. }
  1192. // Format into the dynamic buffer, if the buffer is not large enough, then
  1193. // keep doubling it's size until it is. The buffer is not reallocated
  1194. // using reallocate() to avoid unnecessary buffer copying.
  1195. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1196. while (_len < 0 || _len >= _dynamicSize)
  1197. {
  1198. _len = startLen;
  1199. _dynamicBuffer = (char*)dRealloc(_dynamicBuffer, _dynamicSize *= 2);
  1200. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1201. }
  1202. return _len;
  1203. }
  1204. S32 String::StrFormat::append(const char * str, S32 len)
  1205. {
  1206. if (_dynamicBuffer == NULL)
  1207. {
  1208. if (_len+len >= 0 && _len+len < sizeof(_fixedBuffer))
  1209. {
  1210. dMemcpy(_fixedBuffer + _len, str, len);
  1211. _len += len;
  1212. _fixedBuffer[_len] = '\0';
  1213. return _len;
  1214. }
  1215. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1216. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1217. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1218. }
  1219. S32 newSize = _dynamicSize;
  1220. while (newSize < _len+len)
  1221. newSize *= 2;
  1222. if (newSize != _dynamicSize)
  1223. _dynamicBuffer = (char*) dRealloc(_dynamicBuffer, newSize);
  1224. _dynamicSize = newSize;
  1225. dMemcpy(_dynamicBuffer + _len, str, len);
  1226. _len += len;
  1227. _dynamicBuffer[_len] = '\0';
  1228. return _len;
  1229. }
  1230. S32 String::StrFormat::append(const char * str)
  1231. {
  1232. return append(str, dStrlen(str));
  1233. }
  1234. char* String::StrFormat::copy( char *buffer ) const
  1235. {
  1236. dMemcpy(buffer, _dynamicBuffer? _dynamicBuffer: _fixedBuffer, _len+1);
  1237. return buffer;
  1238. }
  1239. //-----------------------------------------------------------------------------
  1240. String String::ToString( bool value )
  1241. {
  1242. static String sTrue = "true";
  1243. static String sFalse = "false";
  1244. if( value )
  1245. return sTrue;
  1246. return sFalse;
  1247. }
  1248. String String::ToString(const char *str, ...)
  1249. {
  1250. AssertFatal(str,"String:: Invalid null ptr argument");
  1251. // Use the format object
  1252. va_list args;
  1253. va_start(args, str);
  1254. String ret = VToString(str, args);
  1255. va_end(args);
  1256. return ret;
  1257. }
  1258. String String::VToString(const char* str, va_list args)
  1259. {
  1260. StrFormat format(str,args);
  1261. // Copy it into a string
  1262. U32 len = format.length();
  1263. StringData* sub;
  1264. if( !len )
  1265. sub = StringData::Empty();
  1266. else
  1267. {
  1268. sub = new ( len ) StringData( NULL );
  1269. format.copy( sub->utf8() );
  1270. sub->utf8()[ len ] = 0;
  1271. }
  1272. return sub;
  1273. }
  1274. String String::SpanToString(const char *start, const char *end)
  1275. {
  1276. if ( end == start )
  1277. return String();
  1278. AssertFatal( end > start, "Invalid arguments to String::SpanToString - end is before start" );
  1279. U32 len = U32(end - start);
  1280. StringData* sub = new ( len ) StringData( start );
  1281. return sub;
  1282. }
  1283. String String::ToLower(const String &string)
  1284. {
  1285. if ( string.isEmpty() )
  1286. return String();
  1287. StringData* sub = new ( string.length() ) StringData( string );
  1288. dStrlwr( sub->utf8() );
  1289. return sub;
  1290. }
  1291. String String::ToUpper(const String &string)
  1292. {
  1293. if ( string.isEmpty() )
  1294. return String();
  1295. StringData* sub = new ( string.length() ) StringData( string );
  1296. dStrupr( sub->utf8() );
  1297. return sub;
  1298. }
  1299. String String::GetTrailingNumber(const char* str, S32& number)
  1300. {
  1301. // Check for trivial strings
  1302. if (!str || !str[0])
  1303. return String::EmptyString;
  1304. // Find the number at the end of the string
  1305. String base(str);
  1306. const char* p = base.c_str() + base.length() - 1;
  1307. // Ignore trailing whitespace
  1308. while ((p != base.c_str()) && dIsspace(*p))
  1309. p--;
  1310. // Need at least one digit!
  1311. if (!isdigit(*p))
  1312. return base;
  1313. // Back up to the first non-digit character
  1314. while ((p != base.c_str()) && isdigit(*p))
  1315. p--;
  1316. // Convert number => allow negative numbers, treat '_' as '-' for Maya
  1317. if ((*p == '-') || (*p == '_'))
  1318. number = -dAtoi(p + 1);
  1319. else
  1320. number = (isdigit(*p) ? dAtoi(p) : dAtoi(++p));
  1321. // Remove space between the name and the number
  1322. while ((p > base.c_str()) && dIsspace(*(p-1)))
  1323. p--;
  1324. return base.substr(0, p - base.c_str());
  1325. }
  1326. String String::GetFirstNumber(const char* str, U32& startPos, U32& endPos)
  1327. {
  1328. // Check for trivial strings
  1329. if (!str || !str[0])
  1330. return String::EmptyString;
  1331. // Find the number at the end of the string
  1332. String base(str);
  1333. const char* p = base.c_str();
  1334. const char* end = base.c_str() + base.length() - 1;
  1335. bool dec = false;
  1336. startPos = 0;
  1337. //Check if we are just a digit
  1338. if(p == end && isdigit(*p))
  1339. return base;
  1340. //Look for the first digit
  1341. while ((p != end) && (dIsspace(*p) || !isdigit(*p)))
  1342. {
  1343. p++;
  1344. startPos++;
  1345. }
  1346. //Handle if we are at the end and found nothing
  1347. if(p == end && !isdigit(*p))
  1348. return "";
  1349. //update our end position at least to the start of our number
  1350. endPos = startPos;
  1351. //Backup our ptr
  1352. const char* backup = p;
  1353. //Check for any negative or decimal values
  1354. if(startPos > 0)
  1355. {
  1356. p--;
  1357. startPos--;
  1358. if(*p == '.')
  1359. {
  1360. dec = true;
  1361. //ignore any duplicate periods
  1362. while ((p != base.c_str()) && (*p == '.'))
  1363. {
  1364. p--;
  1365. startPos--;
  1366. }
  1367. //Found a decimal lets still check for negative sign
  1368. if(startPos > 0)
  1369. {
  1370. p--;
  1371. startPos--;
  1372. if((*p != '-') && (*p != '_'))
  1373. {
  1374. startPos++;
  1375. p++;
  1376. }
  1377. }
  1378. }
  1379. else if((*p != '-') && (*p != '_'))
  1380. {
  1381. //go back to where we where cause no decimal or negative sign found
  1382. startPos++;
  1383. p++;
  1384. }
  1385. }
  1386. //Restore where we were
  1387. p = backup;
  1388. //look for the end of the digits
  1389. bool justFoundDec = false;
  1390. while (p != end)
  1391. {
  1392. if(*p == '.')
  1393. {
  1394. if(dec && !justFoundDec)
  1395. break;
  1396. else
  1397. {
  1398. dec = true;
  1399. justFoundDec = true;
  1400. }
  1401. }
  1402. else if(!isdigit(*p))
  1403. break;
  1404. else if(justFoundDec)
  1405. justFoundDec = false;
  1406. p++;
  1407. endPos++;
  1408. }
  1409. U32 len = (!isdigit(*p)) ? endPos - startPos : (endPos + 1) - startPos;
  1410. return base.substr(startPos, len);
  1411. }