str.cpp 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631
  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 ( dStrcmp( d1->utf8(), d2->utf8() ) == 0 );
  389. }
  390. }
  391. /// Type for the intern string table. We don't want String instances directly
  392. /// on the table so that destructors don't run when the table is destroyed. This
  393. /// is because we really shouldn't depend on dtor ordering within this file and thus
  394. /// we can't tell whether the intern string memory is freed before or after the
  395. /// table is destroyed.
  396. struct StringInternTable : public HashTable< String::StringData*, String::StringData* >
  397. {
  398. Mutex mMutex;
  399. DataChunker mChunker;
  400. };
  401. static StringInternTable* sInternTable;
  402. struct KillInternTable
  403. {
  404. ~KillInternTable()
  405. {
  406. if( sInternTable )
  407. delete sInternTable;
  408. }
  409. };
  410. static KillInternTable sKillInternTable;
  411. //-----------------------------------------------------------------------------
  412. #ifdef TORQUE_DEBUG
  413. /// Tracks the number of bytes allocated for strings.
  414. /// @bug This currently does not include UTF16 allocations.
  415. static U32 sgStringMemBytes;
  416. /// Tracks the number of Strings which are currently instantiated.
  417. static U32 sgStringInstances;
  418. #endif
  419. DefineConsoleFunction( dumpStringMemStats, void, (), , "()"
  420. "@brief Dumps information about String memory usage\n\n"
  421. "@ingroup Debugging\n"
  422. "@ingroup Strings\n")
  423. {
  424. #ifdef TORQUE_DEBUG
  425. Con::printf( "String Data: %i instances, %i bytes", sgStringInstances, sgStringMemBytes );
  426. #endif
  427. }
  428. //-----------------------------------------------------------------------------
  429. void* String::StringData::operator new( size_t size, U32 len )
  430. {
  431. AssertFatal( len != 0, "String::StringData::operator new() - string must not be empty" );
  432. StringData *str = 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. AssertFatal(len<=dStrlen(str), "String::String: string too short");
  490. _string = new ( len ) StringData( str );
  491. }
  492. else
  493. _string = StringData::Empty();
  494. }
  495. String::String(const UTF16 *str)
  496. {
  497. PROFILE_SCOPE(String_UTF16_constructor);
  498. if( str && str[ 0 ] )
  499. {
  500. UTF8* utf8 = createUTF8string( str );
  501. U32 len = dStrlen( utf8 );
  502. _string = new ( len ) StringData( utf8 );
  503. delete [] utf8;
  504. }
  505. else
  506. _string = StringData::Empty();
  507. }
  508. String::~String()
  509. {
  510. _string->release();
  511. }
  512. //-----------------------------------------------------------------------------
  513. String String::intern() const
  514. {
  515. if( isInterned() )
  516. return *this;
  517. // Create the intern table, if we haven't already.
  518. if( !sInternTable )
  519. sInternTable = new StringInternTable;
  520. // Lock the string table.
  521. MutexHandle mutex;
  522. mutex.lock( &sInternTable->mMutex );
  523. // Lookup.
  524. StringInternTable::Iterator iter = sInternTable->find( _string );
  525. if( iter != sInternTable->end() )
  526. return ( *iter ).value;
  527. // Create new.
  528. StringData* data = new ( length(), sInternTable->mChunker ) StringData( c_str(), true );
  529. iter = sInternTable->insertUnique( data, data );
  530. return ( *iter ).value;
  531. }
  532. //-----------------------------------------------------------------------------
  533. const StringChar* String::c_str() const
  534. {
  535. return _string->utf8();
  536. }
  537. const UTF16 *String::utf16() const
  538. {
  539. return _string->utf16();
  540. }
  541. String::SizeType String::length() const
  542. {
  543. return _string->getLength();
  544. }
  545. String::SizeType String::size() const
  546. {
  547. return _string->getDataSize();
  548. }
  549. String::SizeType String::numChars() const
  550. {
  551. return _string->getNumChars();
  552. }
  553. bool String::isEmpty() const
  554. {
  555. return ( _string == StringData::Empty() );
  556. }
  557. bool String::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. bool String::equal(const String &str, U32 mode) const
  840. {
  841. if( !mode )
  842. return ( *this == str );
  843. else
  844. {
  845. if( _string == str._string )
  846. return true;
  847. else if( _string->isInterned() && str._string->isInterned() )
  848. return false;
  849. else if( length() != str.length() )
  850. return false;
  851. else if( _string->getHashNoCase() != U32_MAX
  852. && str._string->getHashNoCase() != U32_MAX
  853. && _string->getHashNoCase() != str._string->getHashNoCase() )
  854. return false;
  855. else
  856. return ( compare( str.c_str(), length(), mode ) == 0 );
  857. }
  858. }
  859. //-----------------------------------------------------------------------------
  860. String::SizeType String::find(StringChar c, SizeType pos, U32 mode) const
  861. {
  862. const StringChar* ptr = StrFind(_string->utf8(),c,pos,mode);
  863. return ptr? SizeType(ptr - _string->utf8()): NPos;
  864. }
  865. String::SizeType String::find(const StringChar *str, SizeType pos, U32 mode) const
  866. {
  867. AssertFatal(str,"String:: Invalid null ptr argument");
  868. const StringChar* ptr = StrFind(_string->utf8(),str,pos,mode);
  869. return ptr? SizeType(ptr - _string->utf8()): NPos;
  870. }
  871. //-----------------------------------------------------------------------------
  872. String& String::insert(SizeType pos, const StringChar *str)
  873. {
  874. AssertFatal(str,"String:: Invalid null ptr argument");
  875. return insert(pos,str,dStrlen(str));
  876. }
  877. ///@todo review for error checking
  878. String& String::insert(SizeType pos, const StringChar *str, SizeType len)
  879. {
  880. if( !len )
  881. return *this;
  882. AssertFatal( str, "String:: Invalid null ptr argument" );
  883. SizeType lena = length();
  884. AssertFatal((pos <= lena),"Calling String::insert with position greater than length");
  885. U32 newlen = lena + len;
  886. StringData *sub;
  887. if( !newlen )
  888. sub = StringData::Empty();
  889. else
  890. {
  891. sub = new ( newlen ) StringData( NULL );
  892. String::copy(sub->utf8(),_string->utf8(),pos);
  893. String::copy(sub->utf8() + pos,str,len);
  894. String::copy(sub->utf8() + pos + len,_string->utf8() + pos,lena - pos + 1);
  895. }
  896. _string->release();
  897. _string = sub;
  898. return *this;
  899. }
  900. String& String::erase(SizeType pos, SizeType len)
  901. {
  902. AssertFatal( len != 0, "String::erase() - Calling String::erase with 0 length" );
  903. AssertFatal( ( pos + len ) <= length(), "String::erase() - Invalid string region" );
  904. if( !len )
  905. return *this;
  906. SizeType slen = length();
  907. U32 newlen = slen - len;
  908. StringData *sub;
  909. if( !newlen )
  910. sub = StringData::Empty();
  911. else
  912. {
  913. sub = new ( newlen ) StringData( NULL );
  914. if (pos > 0)
  915. String::copy(sub->utf8(),_string->utf8(),pos);
  916. String::copy(sub->utf8() + pos, _string->utf8() + pos + len, slen - (pos + len) + 1);
  917. }
  918. _string->release();
  919. _string = sub;
  920. return *this;
  921. }
  922. ///@todo review for error checking
  923. String& String::replace(SizeType pos, SizeType len, const StringChar *str)
  924. {
  925. AssertFatal( str, "String::replace() - Invalid null ptr argument" );
  926. AssertFatal( len != 0, "String::replace() - Zero length" );
  927. AssertFatal( ( pos + len ) <= length(), "String::replace() - Invalid string region" );
  928. SizeType slen = length();
  929. SizeType rlen = dStrlen(str);
  930. U32 newlen = slen - len + rlen;
  931. StringData *sub;
  932. if( !newlen )
  933. sub = StringData::Empty();
  934. else
  935. {
  936. sub = new ( newlen ) StringData( NULL );
  937. String::copy(sub->utf8(),_string->utf8(), pos);
  938. String::copy(sub->utf8() + pos,str,rlen);
  939. String::copy(sub->utf8() + pos + rlen,_string->utf8() + pos + len,slen - pos - len + 1);
  940. }
  941. _string->release();
  942. _string = sub;
  943. return *this;
  944. }
  945. String& String::replace( StringChar c1, StringChar c2 )
  946. {
  947. if( isEmpty() )
  948. return *this;
  949. // Create the new string lazily so that we don't needlessly
  950. // dup strings when there is nothing to replace.
  951. StringData* sub = NULL;
  952. bool foundReplacement = false;
  953. StringChar* c = _string->utf8();
  954. while( *c )
  955. {
  956. if( *c == c1 )
  957. {
  958. if( !foundReplacement )
  959. {
  960. sub = new ( length() ) StringData( _string->utf8() );
  961. c = &sub->utf8()[ c - _string->utf8() ];
  962. foundReplacement = true;
  963. }
  964. *c = c2;
  965. }
  966. c++;
  967. }
  968. if( foundReplacement )
  969. {
  970. _string->release();
  971. _string = sub;
  972. }
  973. return *this;
  974. }
  975. String &String::replace(const String &s1, const String &s2)
  976. {
  977. // Find number of occurrences of s1 and
  978. // Calculate length of the new string...
  979. const U32 &s1len = s1.length();
  980. const U32 &s2len = s2.length();
  981. U32 pos = 0;
  982. Vector<U32> indices;
  983. StringChar *walk = _string->utf8();
  984. while ( walk )
  985. {
  986. // Casting away the const... was there a better way?
  987. walk = (StringChar*)StrFind( _string->utf8(), s1.c_str(), pos, Case|Left );
  988. if ( walk )
  989. {
  990. pos = SizeType(walk - _string->utf8());
  991. indices.push_back( pos );
  992. pos += s1len;
  993. }
  994. }
  995. // Early-out, no StringDatas found.
  996. if ( indices.size() == 0 )
  997. return *this;
  998. U32 newSize = size() - ( indices.size() * s1len ) + ( indices.size() * s2len );
  999. StringData *sub;
  1000. if( newSize == 1 )
  1001. sub = StringData::Empty();
  1002. else
  1003. {
  1004. sub = new (newSize - 1 ) StringData( NULL );
  1005. // Now assemble the new string from the pieces of the old...
  1006. // Index into the old string
  1007. pos = 0;
  1008. // Index into the new string
  1009. U32 newPos = 0;
  1010. // Used to store a character count to be memcpy'd
  1011. U32 copyCharCount = 0;
  1012. for ( U32 i = 0; i < indices.size(); i++ )
  1013. {
  1014. const U32 &index = indices[i];
  1015. // Number of chars (if any) before the next indexed StringData
  1016. copyCharCount = index - pos;
  1017. // Copy chars before the StringData if we have any.
  1018. if ( copyCharCount > 0 )
  1019. {
  1020. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1021. newPos += copyCharCount;
  1022. }
  1023. // Copy over the replacement string.
  1024. if ( s2len > 0 )
  1025. dMemcpy( sub->utf8() + newPos, s2._string->utf8(), s2len * sizeof(StringChar) );
  1026. newPos += s2len;
  1027. pos = index + s1len;
  1028. }
  1029. // There could be characters left in the original string after the last
  1030. // StringData occurrence, which we need to copy now - outside the loop.
  1031. copyCharCount = length() - indices.last() - s1len;
  1032. if ( copyCharCount != 0 )
  1033. dMemcpy( sub->utf8() + newPos, _string->utf8() + pos, copyCharCount * sizeof(StringChar) );
  1034. // Null terminate it!
  1035. sub->utf8()[newSize-1] = 0;
  1036. }
  1037. _string->release();
  1038. _string = sub;
  1039. return *this;
  1040. }
  1041. //-----------------------------------------------------------------------------
  1042. String String::substr(SizeType pos, SizeType len) const
  1043. {
  1044. //PROFILE_SCOPE( String_substr );
  1045. AssertFatal( pos <= length(), "String::substr - Invalid position!" );
  1046. if ( len == -1 )
  1047. len = length() - pos;
  1048. AssertFatal( len + pos <= length(), "String::substr - Invalid length!" );
  1049. StringData* sub;
  1050. if( !len )
  1051. sub = StringData::Empty();
  1052. else
  1053. sub = new ( len ) StringData( _string->utf8() + pos );
  1054. return sub;
  1055. }
  1056. //-----------------------------------------------------------------------------
  1057. String String::trim() const
  1058. {
  1059. if( isEmpty() )
  1060. return *this;
  1061. const StringChar* start = _string->utf8();
  1062. while( *start && dIsspace( *start ) )
  1063. start ++;
  1064. const StringChar* end = _string->utf8() + length() - 1;
  1065. while( end > start && dIsspace( *end ) )
  1066. end --;
  1067. end ++;
  1068. const U32 len = end - start;
  1069. if( len == length() )
  1070. return *this;
  1071. StringData* sub;
  1072. if( !len )
  1073. sub = StringData::Empty();
  1074. else
  1075. sub = new ( len ) StringData( start );
  1076. return sub;
  1077. }
  1078. //-----------------------------------------------------------------------------
  1079. String String::expandEscapes() const
  1080. {
  1081. char* tmp = ( char* ) dMalloc( length() * 2 + 1 ); // worst-case situation.
  1082. expandEscape( tmp, c_str() );
  1083. String str( tmp );
  1084. dFree( tmp );
  1085. return str;
  1086. }
  1087. //-----------------------------------------------------------------------------
  1088. String String::collapseEscapes() const
  1089. {
  1090. char* tmp = dStrdup( c_str() );
  1091. collapseEscape( tmp );
  1092. String str( tmp );
  1093. dFree( tmp );
  1094. return str;
  1095. }
  1096. //-----------------------------------------------------------------------------
  1097. void String::split( const char* delimiter, Vector< String >& outElements ) const
  1098. {
  1099. const char* ptr = _string->utf8();
  1100. const char* start = ptr;
  1101. while( *ptr )
  1102. {
  1103. // Search for start of delimiter.
  1104. if( *ptr != delimiter[ 0 ] )
  1105. ptr ++;
  1106. else
  1107. {
  1108. // Skip delimiter.
  1109. const char* end = ptr;
  1110. const char* del = delimiter;
  1111. while( *del && *del == *ptr )
  1112. {
  1113. ptr ++;
  1114. del ++;
  1115. }
  1116. // If we didn't match all of delimiter,
  1117. // continue with search.
  1118. if( *del != '\0' )
  1119. continue;
  1120. // Extract component.
  1121. outElements.push_back( String( start, end - start ) );
  1122. start = ptr;
  1123. }
  1124. }
  1125. // Add rest of string if there is any.
  1126. if( start != ptr )
  1127. outElements.push_back( start );
  1128. }
  1129. //-----------------------------------------------------------------------------
  1130. bool String::startsWith( const char* text ) const
  1131. {
  1132. return dStrStartsWith( _string->utf8(), text );
  1133. }
  1134. //-----------------------------------------------------------------------------
  1135. bool String::endsWith( const char* text ) const
  1136. {
  1137. return dStrEndsWith( _string->utf8(), text );
  1138. }
  1139. //-----------------------------------------------------------------------------
  1140. void String::copy(StringChar* dst, const StringChar *src, U32 len)
  1141. {
  1142. dMemcpy(dst, src, len * sizeof(StringChar));
  1143. }
  1144. //-----------------------------------------------------------------------------
  1145. #if defined(TORQUE_OS_WIN) || defined(TORQUE_OS_XBOX) || defined(TORQUE_OS_XENON)
  1146. // This standard function is not defined when compiling with VC7...
  1147. #define vsnprintf _vsnprintf
  1148. #endif
  1149. String::StrFormat::~StrFormat()
  1150. {
  1151. if( _dynamicBuffer )
  1152. dFree( _dynamicBuffer );
  1153. }
  1154. S32 String::StrFormat::format( const char *format, va_list args )
  1155. {
  1156. _len=0;
  1157. return formatAppend(format,args);
  1158. }
  1159. S32 String::StrFormat::formatAppend( const char *format, va_list args )
  1160. {
  1161. // Format into the fixed buffer first.
  1162. S32 startLen = _len;
  1163. if (_dynamicBuffer == NULL)
  1164. {
  1165. _len += vsnprintf(_fixedBuffer + _len, sizeof(_fixedBuffer) - _len, format, args);
  1166. if (_len >= 0 && _len < sizeof(_fixedBuffer))
  1167. return _len;
  1168. // Start off the dynamic buffer at twice fixed buffer size
  1169. _len = startLen;
  1170. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1171. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1172. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1173. }
  1174. // Format into the dynamic buffer, if the buffer is not large enough, then
  1175. // keep doubling it's size until it is. The buffer is not reallocated
  1176. // using reallocate() to avoid unnecessary buffer copying.
  1177. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1178. while (_len < 0 || _len >= _dynamicSize)
  1179. {
  1180. _len = startLen;
  1181. _dynamicBuffer = (char*)dRealloc(_dynamicBuffer, _dynamicSize *= 2);
  1182. _len += vsnprintf(_dynamicBuffer + _len, _dynamicSize - _len, format, *(va_list*)args);
  1183. }
  1184. return _len;
  1185. }
  1186. S32 String::StrFormat::append(const char * str, S32 len)
  1187. {
  1188. if (_dynamicBuffer == NULL)
  1189. {
  1190. if (_len+len >= 0 && _len+len < sizeof(_fixedBuffer))
  1191. {
  1192. dMemcpy(_fixedBuffer + _len, str, len);
  1193. _len += len;
  1194. _fixedBuffer[_len] = '\0';
  1195. return _len;
  1196. }
  1197. _dynamicSize = sizeof(_fixedBuffer) * 2;
  1198. _dynamicBuffer = (char*)dMalloc(_dynamicSize);
  1199. dMemcpy(_dynamicBuffer, _fixedBuffer, _len + 1);
  1200. }
  1201. S32 newSize = _dynamicSize;
  1202. while (newSize < _len+len)
  1203. newSize *= 2;
  1204. if (newSize != _dynamicSize)
  1205. _dynamicBuffer = (char*) dRealloc(_dynamicBuffer, newSize);
  1206. _dynamicSize = newSize;
  1207. dMemcpy(_dynamicBuffer + _len, str, len);
  1208. _len += len;
  1209. _dynamicBuffer[_len] = '\0';
  1210. return _len;
  1211. }
  1212. S32 String::StrFormat::append(const char * str)
  1213. {
  1214. return append(str, dStrlen(str));
  1215. }
  1216. char* String::StrFormat::copy( char *buffer ) const
  1217. {
  1218. dMemcpy(buffer, _dynamicBuffer? _dynamicBuffer: _fixedBuffer, _len+1);
  1219. return buffer;
  1220. }
  1221. //-----------------------------------------------------------------------------
  1222. String String::ToString( bool value )
  1223. {
  1224. static String sTrue = "true";
  1225. static String sFalse = "false";
  1226. if( value )
  1227. return sTrue;
  1228. return sFalse;
  1229. }
  1230. String String::ToString(const char *str, ...)
  1231. {
  1232. AssertFatal(str,"String:: Invalid null ptr argument");
  1233. // Use the format object
  1234. va_list args;
  1235. va_start(args, str);
  1236. String ret = VToString(str, args);
  1237. va_end(args);
  1238. return ret;
  1239. }
  1240. String String::VToString(const char* str, va_list args)
  1241. {
  1242. StrFormat format(str,args);
  1243. // Copy it into a string
  1244. U32 len = format.length();
  1245. StringData* sub;
  1246. if( !len )
  1247. sub = StringData::Empty();
  1248. else
  1249. {
  1250. sub = new ( len ) StringData( NULL );
  1251. format.copy( sub->utf8() );
  1252. sub->utf8()[ len ] = 0;
  1253. }
  1254. return sub;
  1255. }
  1256. String String::SpanToString(const char *start, const char *end)
  1257. {
  1258. if ( end == start )
  1259. return String();
  1260. AssertFatal( end > start, "Invalid arguments to String::SpanToString - end is before start" );
  1261. U32 len = U32(end - start);
  1262. StringData* sub = new ( len ) StringData( start );
  1263. return sub;
  1264. }
  1265. String String::ToLower(const String &string)
  1266. {
  1267. if ( string.isEmpty() )
  1268. return String();
  1269. StringData* sub = new ( string.length() ) StringData( string );
  1270. dStrlwr( sub->utf8() );
  1271. return sub;
  1272. }
  1273. String String::ToUpper(const String &string)
  1274. {
  1275. if ( string.isEmpty() )
  1276. return String();
  1277. StringData* sub = new ( string.length() ) StringData( string );
  1278. dStrupr( sub->utf8() );
  1279. return sub;
  1280. }
  1281. String String::GetTrailingNumber(const char* str, S32& number)
  1282. {
  1283. // Check for trivial strings
  1284. if (!str || !str[0])
  1285. return String::EmptyString;
  1286. // Find the number at the end of the string
  1287. String base(str);
  1288. const char* p = base.c_str() + base.length() - 1;
  1289. // Ignore trailing whitespace
  1290. while ((p != base.c_str()) && dIsspace(*p))
  1291. p--;
  1292. // Need at least one digit!
  1293. if (!isdigit(*p))
  1294. return base;
  1295. // Back up to the first non-digit character
  1296. while ((p != base.c_str()) && isdigit(*p))
  1297. p--;
  1298. // Convert number => allow negative numbers, treat '_' as '-' for Maya
  1299. if ((*p == '-') || (*p == '_'))
  1300. number = -dAtoi(p + 1);
  1301. else
  1302. number = ((p == base.c_str()) ? dAtoi(p) : dAtoi(++p));
  1303. // Remove space between the name and the number
  1304. while ((p > base.c_str()) && dIsspace(*(p-1)))
  1305. p--;
  1306. return base.substr(0, p - base.c_str());
  1307. }