Str.h 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  1. // Copyright (c) 2008-2023 the Urho3D project
  2. // License: MIT
  3. #pragma once
  4. #include "../Container/Vector.h"
  5. #include <cstdarg>
  6. #include <cstring>
  7. #include <cctype>
  8. namespace Urho3D
  9. {
  10. static const int CONVERSION_BUFFER_LENGTH = 128;
  11. static const int MATRIX_CONVERSION_BUFFER_LENGTH = 256;
  12. class WString;
  13. class StringHash;
  14. template <class T, class U> class HashMap;
  15. /// Map of strings.
  16. using StringMap = HashMap<StringHash, String>;
  17. /// %String class.
  18. class URHO3D_API String
  19. {
  20. public:
  21. using Iterator = RandomAccessIterator<char>;
  22. using ConstIterator = RandomAccessConstIterator<char>;
  23. /// Construct empty.
  24. String() noexcept
  25. {
  26. SetShortStringLength(0);
  27. data_.shortString_.buffer_[0] = '\0';
  28. }
  29. /// Construct from another string.
  30. String(const String& str)
  31. : String()
  32. {
  33. *this = str;
  34. }
  35. /// Move-construct from another string.
  36. String(String&& str) noexcept
  37. : String()
  38. {
  39. Swap(str);
  40. }
  41. /// Construct from a C string.
  42. String(const char* str) // NOLINT(google-explicit-constructor)
  43. : String()
  44. {
  45. *this = str;
  46. }
  47. /// Construct from a C string.
  48. String(char* str) // NOLINT(google-explicit-constructor)
  49. : String()
  50. {
  51. *this = (const char*)str;
  52. }
  53. /// Construct from a char array and length.
  54. String(const char* str, i32 length)
  55. : String()
  56. {
  57. Resize(length);
  58. CopyChars(GetBuffer(), str, length);
  59. }
  60. /// Construct from a null-terminated wide character array.
  61. explicit String(const wchar_t* str)
  62. : String()
  63. {
  64. SetUTF8FromWChar(str);
  65. }
  66. /// Construct from a null-terminated wide character array.
  67. explicit String(wchar_t* str)
  68. : String()
  69. {
  70. SetUTF8FromWChar(str);
  71. }
  72. /// Construct from a wide character string.
  73. explicit String(const WString& str);
  74. /// Construct from an integer.
  75. explicit String(int value);
  76. /// Construct from a short integer.
  77. explicit String(short value);
  78. /// Construct from a long integer.
  79. /// @nobind
  80. explicit String(long value);
  81. /// Construct from a long long integer.
  82. explicit String(long long value);
  83. /// Construct from an unsigned integer.
  84. explicit String(unsigned value);
  85. /// Construct from an unsigned short integer.
  86. explicit String(unsigned short value);
  87. /// Construct from an unsigned long integer.
  88. /// @nobind
  89. explicit String(unsigned long value);
  90. /// Construct from an unsigned long long integer.
  91. explicit String(unsigned long long value);
  92. /// Construct from a float.
  93. explicit String(float value);
  94. /// Construct from a double.
  95. explicit String(double value);
  96. /// Construct from a bool.
  97. explicit String(bool value);
  98. /// Construct from a character.
  99. explicit String(char value);
  100. /// Construct from a character and fill length.
  101. explicit String(char value, i32 length);
  102. /// Construct from a convertible value.
  103. template <class T> explicit String(const T& value)
  104. : String()
  105. {
  106. *this = value.ToString();
  107. }
  108. /// Destruct.
  109. ~String()
  110. {
  111. if (!IsShort())
  112. delete[] data_.longString_.buffer_;
  113. }
  114. /// Assign a string.
  115. String& operator =(const String& rhs)
  116. {
  117. if (&rhs != this)
  118. {
  119. Resize(rhs.Length());
  120. CopyChars(GetBuffer(), rhs.GetBuffer(), rhs.Length());
  121. }
  122. return *this;
  123. }
  124. /// Move-assign a string.
  125. String& operator =(String&& rhs) noexcept
  126. {
  127. Swap(rhs);
  128. return *this;
  129. }
  130. /// Assign a C string.
  131. String& operator =(const char* rhs)
  132. {
  133. i32 rhsLength = CStringLength(rhs);
  134. Resize(rhsLength);
  135. CopyChars(GetBuffer(), rhs, rhsLength);
  136. return *this;
  137. }
  138. /// Add-assign a string.
  139. String& operator +=(const String& rhs)
  140. {
  141. i32 oldLength = Length();
  142. i32 rhsLength = rhs.Length();
  143. Resize(oldLength + rhsLength);
  144. CopyChars(GetBuffer() + oldLength, rhs.GetBuffer(), rhsLength);
  145. return *this;
  146. }
  147. /// Add-assign a C string.
  148. String& operator +=(const char* rhs)
  149. {
  150. i32 rhsLength = CStringLength(rhs);
  151. i32 oldLength = Length();
  152. Resize(oldLength + rhsLength);
  153. CopyChars(GetBuffer() + oldLength, rhs, rhsLength);
  154. return *this;
  155. }
  156. /// Add-assign a character.
  157. String& operator +=(char rhs)
  158. {
  159. i32 oldLength = Length();
  160. Resize(oldLength + 1);
  161. GetBuffer()[oldLength] = rhs;
  162. return *this;
  163. }
  164. /// Add-assign (concatenate as string) an integer.
  165. String& operator +=(int rhs);
  166. /// Add-assign (concatenate as string) a short integer.
  167. String& operator +=(short rhs);
  168. /// Add-assign (concatenate as string) a long integer.
  169. /// @nobind
  170. String& operator +=(long rhs);
  171. /// Add-assign (concatenate as string) a long long integer.
  172. String& operator +=(long long rhs);
  173. /// Add-assign (concatenate as string) an unsigned integer.
  174. String& operator +=(unsigned rhs);
  175. /// Add-assign (concatenate as string) a short unsigned integer.
  176. String& operator +=(unsigned short rhs);
  177. /// Add-assign (concatenate as string) a long unsigned integer.
  178. /// @nobind
  179. String& operator +=(unsigned long rhs);
  180. /// Add-assign (concatenate as string) a long long unsigned integer.
  181. String& operator +=(unsigned long long rhs);
  182. /// Add-assign (concatenate as string) a float.
  183. String& operator +=(float rhs);
  184. /// Add-assign (concatenate as string) a bool.
  185. String& operator +=(bool rhs);
  186. /// Add-assign (concatenate as string) an arbitrary type.
  187. template <class T> String& operator +=(const T& rhs) { return *this += rhs.ToString(); }
  188. /// Add a string.
  189. String operator +(const String& rhs) const
  190. {
  191. String ret;
  192. i32 length = Length();
  193. i32 rhsLength = rhs.Length();
  194. ret.Resize(length + rhsLength);
  195. char* retBuffer = ret.GetBuffer();
  196. CopyChars(retBuffer, GetBuffer(), length);
  197. CopyChars(retBuffer + length, rhs.GetBuffer(), rhsLength);
  198. return ret;
  199. }
  200. /// Add a C string.
  201. String operator +(const char* rhs) const
  202. {
  203. i32 length = Length();
  204. i32 rhsLength = CStringLength(rhs);
  205. String ret;
  206. ret.Resize(length + rhsLength);
  207. char* retBuffer = ret.GetBuffer();
  208. CopyChars(retBuffer, GetBuffer(), length);
  209. CopyChars(retBuffer + length, rhs, rhsLength);
  210. return ret;
  211. }
  212. /// Test for equality with another string.
  213. bool operator ==(const String& rhs) const { return strcmp(CString(), rhs.CString()) == 0; }
  214. /// Test for inequality with another string.
  215. bool operator !=(const String& rhs) const { return strcmp(CString(), rhs.CString()) != 0; }
  216. /// Test if string is less than another string.
  217. bool operator <(const String& rhs) const { return strcmp(CString(), rhs.CString()) < 0; }
  218. /// Test if string is greater than another string.
  219. bool operator >(const String& rhs) const { return strcmp(CString(), rhs.CString()) > 0; }
  220. /// Test for equality with a C string.
  221. bool operator ==(const char* rhs) const { return strcmp(CString(), rhs) == 0; }
  222. /// Test for inequality with a C string.
  223. bool operator !=(const char* rhs) const { return strcmp(CString(), rhs) != 0; }
  224. /// Test if string is less than a C string.
  225. bool operator <(const char* rhs) const { return strcmp(CString(), rhs) < 0; }
  226. /// Test if string is greater than a C string.
  227. bool operator >(const char* rhs) const { return strcmp(CString(), rhs) > 0; }
  228. /// Return char at index.
  229. char& operator [](i32 index)
  230. {
  231. assert(index >= 0 && index < Length());
  232. return GetBuffer()[index];
  233. }
  234. /// Return const char at index.
  235. const char& operator [](i32 index) const
  236. {
  237. assert(index >= 0 && index < Length());
  238. return GetBuffer()[index];
  239. }
  240. /// Return char at index.
  241. char& At(i32 index)
  242. {
  243. assert(index >= 0 && index < Length());
  244. return GetBuffer()[index];
  245. }
  246. /// Return const char at index.
  247. const char& At(i32 index) const
  248. {
  249. assert(index >= 0 && index < Length());
  250. return GetBuffer()[index];
  251. }
  252. /// Replace all occurrences of a character.
  253. void Replace(char replaceThis, char replaceWith, bool caseSensitive = true);
  254. /// Replace all occurrences of a string.
  255. void Replace(const String& replaceThis, const String& replaceWith, bool caseSensitive = true);
  256. /// Replace a substring.
  257. void Replace(i32 pos, i32 length, const String& replaceWith);
  258. /// Replace a substring with a C string.
  259. void Replace(i32 pos, i32 length, const char* replaceWith);
  260. /// Replace a substring by iterators.
  261. Iterator Replace(const Iterator& start, const Iterator& end, const String& replaceWith);
  262. /// Return a string with all occurrences of a character replaced.
  263. String Replaced(char replaceThis, char replaceWith, bool caseSensitive = true) const;
  264. /// Return a string with all occurrences of a string replaced.
  265. String Replaced(const String& replaceThis, const String& replaceWith, bool caseSensitive = true) const;
  266. /// Append a string.
  267. String& Append(const String& str);
  268. /// Append a C string.
  269. String& Append(const char* str);
  270. /// Append a character.
  271. String& Append(char c);
  272. /// Append characters.
  273. String& Append(const char* str, i32 length);
  274. /// Insert a string.
  275. void Insert(i32 pos, const String& str);
  276. /// Insert a character.
  277. void Insert(i32 pos, char c);
  278. /// Insert a string by iterator.
  279. Iterator Insert(const Iterator& dest, const String& str);
  280. /// Insert a string partially by iterators.
  281. Iterator Insert(const Iterator& dest, const Iterator& start, const Iterator& end);
  282. /// Insert a character by iterator.
  283. Iterator Insert(const Iterator& dest, char c);
  284. /// Erase a substring.
  285. void Erase(i32 pos, i32 length = 1);
  286. /// Erase a character by iterator.
  287. Iterator Erase(const Iterator& it);
  288. /// Erase a substring by iterators.
  289. Iterator Erase(const Iterator& start, const Iterator& end);
  290. /// Resize the string. Can increase capacity, but never decrease.
  291. void Resize(i32 newLength);
  292. /// Set new capacity. New capacity may differ from requested.
  293. void Reserve(i32 newCapacity);
  294. /// Reallocate so that no extra memory is used.
  295. void Compact();
  296. /// Clear the string.
  297. void Clear();
  298. /// Swap with another string.
  299. void Swap(String& str);
  300. /// Return iterator to the beginning.
  301. Iterator Begin() { return Iterator(GetBuffer()); }
  302. /// Return const iterator to the beginning.
  303. ConstIterator Begin() const { return ConstIterator(GetBuffer()); }
  304. /// Return iterator to the end.
  305. Iterator End() { return Iterator(GetBuffer() + Length()); }
  306. /// Return const iterator to the end.
  307. ConstIterator End() const { return ConstIterator(GetBuffer() + Length()); }
  308. /// Return first char, or 0 if empty.
  309. char Front() const { return GetBuffer()[0]; }
  310. /// Return last char, or 0 if empty.
  311. char Back() const
  312. {
  313. i32 length = Length();
  314. return length ? GetBuffer()[length - 1] : GetBuffer()[0];
  315. }
  316. /// Return a substring from position to end.
  317. String Substring(i32 pos) const;
  318. /// Return a substring with length from position.
  319. String Substring(i32 pos, i32 length) const;
  320. /// Return string with whitespace trimmed from the beginning and the end.
  321. String Trimmed() const;
  322. /// Return string in uppercase.
  323. String ToUpper() const;
  324. /// Return string in lowercase.
  325. String ToLower() const;
  326. /// Return substrings split by a separator char. By default don't return empty strings.
  327. Vector<String> Split(char separator, bool keepEmptyStrings = false) const;
  328. /// Join substrings with a 'glue' string.
  329. void Join(const Vector<String>& subStrings, const String& glue);
  330. /// Return index to the first occurrence of a string, or NPOS if not found.
  331. i32 Find(const String& str, i32 startPos = 0, bool caseSensitive = true) const;
  332. /// Return index to the first occurrence of a character, or NPOS if not found.
  333. i32 Find(char c, i32 startPos = 0, bool caseSensitive = true) const;
  334. /// Return index to the last occurrence of a string, or NPOS if not found.
  335. i32 FindLast(const String& str, i32 startPos = NPOS, bool caseSensitive = true) const;
  336. /// Return index to the last occurrence of a character, or NPOS if not found.
  337. i32 FindLast(char c, i32 startPos = NPOS, bool caseSensitive = true) const;
  338. /// Return whether starts with a string.
  339. bool StartsWith(const String& str, bool caseSensitive = true) const;
  340. /// Return whether ends with a string.
  341. bool EndsWith(const String& str, bool caseSensitive = true) const;
  342. /// Return pointer to buffer.
  343. char* GetBuffer() { return IsShort() ? data_.shortString_.buffer_ : data_.longString_.buffer_; }
  344. /// Return pointer to buffer.
  345. const char* GetBuffer() const { return IsShort() ? data_.shortString_.buffer_ : data_.longString_.buffer_; }
  346. /// Return the C string.
  347. const char* CString() const { return GetBuffer(); }
  348. /// Return length.
  349. /// @property
  350. i32 Length() const { return IsShort() ? GetShortStringLength() : data_.longString_.length_; }
  351. /// Return buffer capacity.
  352. i32 Capacity() const { return IsShort() ? SHORT_STRING_CAPACITY : data_.longString_.capacity_; }
  353. /// Return whether the string is empty.
  354. /// @property
  355. bool Empty() const { return Length() == 0; }
  356. /// Return comparison result with a string.
  357. int Compare(const String& str, bool caseSensitive = true) const;
  358. /// Return comparison result with a C string.
  359. int Compare(const char* str, bool caseSensitive = true) const;
  360. /// Return whether contains a specific occurrence of a string.
  361. bool Contains(const String& str, bool caseSensitive = true) const { return Find(str, 0, caseSensitive) != NPOS; }
  362. /// Return whether contains a specific character.
  363. bool Contains(char c, bool caseSensitive = true) const { return Find(c, 0, caseSensitive) != NPOS; }
  364. /// Construct UTF8 content from Latin1.
  365. void SetUTF8FromLatin1(const char* str);
  366. /// Construct UTF8 content from wide characters.
  367. void SetUTF8FromWChar(const wchar_t* str);
  368. /// Calculate number of characters in UTF8 content.
  369. /// @property{get_utf8Length}
  370. i32 LengthUTF8() const;
  371. /// Return byte offset to char in UTF8 content.
  372. i32 ByteOffsetUTF8(i32 index) const;
  373. /// Return next Unicode character from UTF8 content and increase byte offset.
  374. c32 NextUTF8Char(i32& byteOffset) const;
  375. /// Return Unicode character at index from UTF8 content.
  376. c32 AtUTF8(i32 index) const;
  377. /// Replace Unicode character at index from UTF8 content.
  378. void ReplaceUTF8(i32 index, c32 unicodeChar);
  379. /// Append Unicode character at the end as UTF8.
  380. String& AppendUTF8(c32 unicodeChar);
  381. /// Return a UTF8 substring from position to end.
  382. String SubstringUTF8(i32 pos) const;
  383. /// Return a UTF8 substring with length from position.
  384. String SubstringUTF8(i32 pos, i32 length) const;
  385. /// Return hash value for HashSet & HashMap.
  386. hash32 ToHash() const
  387. {
  388. hash32 hash = 0;
  389. const char* ptr = GetBuffer();
  390. while (*ptr)
  391. {
  392. hash = *ptr + (hash << 6u) + (hash << 16u) - hash;
  393. ++ptr;
  394. }
  395. return hash;
  396. }
  397. /// Return substrings split by a separator char. By default don't return empty strings.
  398. static Vector<String> Split(const char* str, char separator, bool keepEmptyStrings = false);
  399. /// Return a string by joining substrings with a 'glue' string.
  400. /// @manualbind
  401. static String Joined(const Vector<String>& subStrings, const String& glue);
  402. /// Encode Unicode character to UTF8. Pointer will be incremented.
  403. static void EncodeUTF8(char*& dest, c32 unicodeChar);
  404. /// Decode Unicode character from UTF8. Pointer will be incremented.
  405. static c32 DecodeUTF8(const char*& src);
  406. #ifdef _WIN32
  407. /// Encode Unicode character to UTF16. Pointer will be incremented.
  408. static void EncodeUTF16(wchar_t*& dest, c32 unicodeChar);
  409. /// Decode Unicode character from UTF16. Pointer will be incremented.
  410. static c32 DecodeUTF16(const wchar_t*& src);
  411. #endif
  412. /// Return length of a C string.
  413. static i32 CStringLength(const char* str) { return str ? (i32)strlen(str) : 0; }
  414. /// Append to string using formatting.
  415. String& AppendWithFormat(const char* formatString, ...);
  416. /// Append to string using variable arguments.
  417. String& AppendWithFormatArgs(const char* formatString, va_list args);
  418. /// Compare two C strings.
  419. static int Compare(const char* lhs, const char* rhs, bool caseSensitive);
  420. /// Position for "not found".
  421. static inline constexpr i32 NPOS = -1;
  422. /// Empty string.
  423. static const String EMPTY;
  424. /// Is the string stored on the stack?
  425. bool IsShort() const
  426. {
  427. u8 lastByte = data_.shortString_.length_;
  428. return !!(lastByte & SSO_MASK);
  429. }
  430. private:
  431. struct LongString
  432. {
  433. /// Data.
  434. char* buffer_;
  435. /// Number of bytes without null terminator.
  436. i32 length_;
  437. /// Size of buffer_.
  438. i32 capacity_;
  439. };
  440. /// 11 bytes on 32-bit platform, 15 bytes on 64-bit platform
  441. inline static constexpr i32 SHORT_STRING_CAPACITY = sizeof(LongString) - 1;
  442. struct ShortString
  443. {
  444. /// Data.
  445. char buffer_[SHORT_STRING_CAPACITY];
  446. /// Number of bytes without null terminator.
  447. u8 length_;
  448. };
  449. static_assert(sizeof(LongString) == sizeof(ShortString));
  450. // https://github.com/doxygen/doxygen/issues/7623
  451. union
  452. {
  453. /// @nobind
  454. LongString longString_;
  455. /// @nobind
  456. ShortString shortString_;
  457. } data_;
  458. /// MSB of the last byte is used as a flag.
  459. inline static constexpr u8 SSO_MASK = 0b10000000u;
  460. inline static constexpr u8 INVERTED_SSO_MASK = static_cast<u8>(~SSO_MASK);
  461. i32 GetShortStringLength() const
  462. {
  463. return data_.shortString_.length_ & INVERTED_SSO_MASK;
  464. }
  465. void SetShortStringLength(u8 value)
  466. {
  467. data_.shortString_.length_ = value | SSO_MASK;
  468. }
  469. /// Move a range of characters within the string.
  470. void MoveRange(i32 dest, i32 src, i32 count)
  471. {
  472. if (count)
  473. {
  474. char* buffer = GetBuffer();
  475. memmove(buffer + dest, buffer + src, count);
  476. }
  477. }
  478. /// Copy chars from one buffer to another.
  479. static void CopyChars(char* dest, const char* src, i32 count)
  480. {
  481. #ifdef _MSC_VER
  482. if (count)
  483. memcpy(dest, src, count);
  484. #else
  485. char* end = dest + count;
  486. while (dest != end)
  487. {
  488. *dest = *src;
  489. ++dest;
  490. ++src;
  491. }
  492. #endif
  493. }
  494. /// Replace a substring with another substring.
  495. void Replace(i32 pos, i32 length, const char* srcStart, i32 srcLength);
  496. };
  497. /// Add a string to a C string.
  498. inline String operator +(const char* lhs, const String& rhs)
  499. {
  500. String ret(lhs);
  501. ret += rhs;
  502. return ret;
  503. }
  504. /// Add a string to a wide char C string.
  505. inline String operator +(const wchar_t* lhs, const String& rhs)
  506. {
  507. String ret(lhs);
  508. ret += rhs;
  509. return ret;
  510. }
  511. /// Wide character string. Only meant for converting from String and passing to the operating system where necessary.
  512. /// @nobind
  513. class URHO3D_API WString
  514. {
  515. public:
  516. /// Construct empty.
  517. WString();
  518. /// Construct from a string.
  519. explicit WString(const String& str);
  520. /// Destruct.
  521. ~WString();
  522. /// Return char at index.
  523. wchar_t& operator [](i32 index)
  524. {
  525. assert(index >= 0 && index < length_);
  526. return buffer_[index];
  527. }
  528. /// Return const char at index.
  529. const wchar_t& operator [](i32 index) const
  530. {
  531. assert(index >= 0 && index < length_);
  532. return buffer_[index];
  533. }
  534. /// Return char at index.
  535. wchar_t& At(i32 index)
  536. {
  537. assert(index >= 0 && index < length_);
  538. return buffer_[index];
  539. }
  540. /// Return const char at index.
  541. const wchar_t& At(i32 index) const
  542. {
  543. assert(index >= 0 && index < length_);
  544. return buffer_[index];
  545. }
  546. /// Resize the string.
  547. void Resize(i32 newLength);
  548. /// Return whether the string is empty.
  549. bool Empty() const { return length_ == 0; }
  550. /// Return length.
  551. i32 Length() const { return length_; }
  552. /// Return character data.
  553. const wchar_t* CString() const { return buffer_; }
  554. private:
  555. /// String length.
  556. i32 length_;
  557. /// String buffer, null if not allocated.
  558. wchar_t* buffer_;
  559. };
  560. }