String.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. // Copyright (C) 2009-2015, Panagiotis Christopoulos Charitos.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #ifndef ANKI_UTIL_STRING_H
  6. #define ANKI_UTIL_STRING_H
  7. #include "anki/util/DArray.h"
  8. #include "anki/util/Array.h"
  9. #include "anki/util/NonCopyable.h"
  10. #include "anki/util/ScopeDestroyer.h"
  11. #include <cstring>
  12. #include <cmath> // For HUGE_VAL
  13. #include <climits> // For LLONG_MAX
  14. #include <cstdarg> // For var args
  15. namespace anki {
  16. // Forward
  17. template<typename TAlloc>
  18. class StringBase;
  19. /// @addtogroup util_private
  20. /// @{
  21. namespace detail {
  22. template<typename TNumber>
  23. constexpr const char* toStringFormat()
  24. {
  25. return nullptr;
  26. }
  27. #define ANKI_DEPLOY_TO_STRING(type_, string_) \
  28. template<> \
  29. constexpr const char* toStringFormat<type_>() \
  30. { \
  31. return string_; \
  32. }
  33. ANKI_DEPLOY_TO_STRING(I8, "%d")
  34. ANKI_DEPLOY_TO_STRING(I16, "%d")
  35. ANKI_DEPLOY_TO_STRING(I32, "%d")
  36. ANKI_DEPLOY_TO_STRING(I64, "%lld")
  37. ANKI_DEPLOY_TO_STRING(U8, "%u")
  38. ANKI_DEPLOY_TO_STRING(U16, "%u")
  39. ANKI_DEPLOY_TO_STRING(U32, "%u")
  40. ANKI_DEPLOY_TO_STRING(U64, "%llu")
  41. ANKI_DEPLOY_TO_STRING(F32, "%f")
  42. ANKI_DEPLOY_TO_STRING(F64, "%f")
  43. #undef ANKI_DEPLOY_TO_STRING
  44. } // end namespace detail
  45. /// @}
  46. /// @addtogroup util_containers
  47. /// @{
  48. /// A wrapper on top of C strings. Used mainly for safety.
  49. class CString
  50. {
  51. template<typename TAlloc>
  52. friend class StringBase; // For the secret constructor
  53. public:
  54. using Char = char;
  55. static const PtrSize NPOS = MAX_PTR_SIZE;
  56. CString() = default;
  57. CString(const Char* ptr)
  58. : m_ptr(ptr)
  59. {
  60. checkInit();
  61. }
  62. /// Copy constructor.
  63. CString(const CString& b)
  64. : m_ptr(b.m_ptr),
  65. m_length(b.m_length)
  66. {
  67. checkInit();
  68. }
  69. /// Copy.
  70. CString& operator=(const CString& b)
  71. {
  72. m_ptr = b.m_ptr;
  73. m_length = b.m_length;
  74. return *this;
  75. }
  76. /// Return true if the string is initialized.
  77. operator Bool() const
  78. {
  79. return !isEmpty();
  80. }
  81. /// Return char at the specified position.
  82. const Char& operator[](U pos) const
  83. {
  84. checkInit();
  85. ANKI_ASSERT(pos <= getLength());
  86. return m_ptr[pos];
  87. }
  88. const Char* begin() const
  89. {
  90. checkInit();
  91. return &m_ptr[0];
  92. }
  93. const Char* end() const
  94. {
  95. checkInit();
  96. return &m_ptr[getLength()];
  97. }
  98. /// Return true if the string is not initialized.
  99. Bool isEmpty() const
  100. {
  101. return m_ptr == nullptr || getLength() == 0;
  102. }
  103. Bool operator==(const CString& b) const
  104. {
  105. if(m_ptr == nullptr || b.m_ptr == nullptr)
  106. {
  107. return m_ptr == b.m_ptr;
  108. }
  109. else
  110. {
  111. return std::strcmp(m_ptr, b.m_ptr) == 0;
  112. }
  113. }
  114. Bool operator!=(const CString& b) const
  115. {
  116. return !((*this) == b);
  117. }
  118. Bool operator<(const CString& b) const
  119. {
  120. if(m_ptr == nullptr || b.m_ptr == nullptr)
  121. {
  122. return false;
  123. }
  124. else
  125. {
  126. return std::strcmp(m_ptr, b.m_ptr) < 0;
  127. }
  128. }
  129. Bool operator<=(const CString& b) const
  130. {
  131. if(m_ptr == nullptr || b.m_ptr == nullptr)
  132. {
  133. return m_ptr == b.m_ptr;
  134. }
  135. else
  136. {
  137. return std::strcmp(m_ptr, b.m_ptr) <= 0;
  138. }
  139. }
  140. Bool operator>(const CString& b) const
  141. {
  142. if(m_ptr == nullptr || b.m_ptr == nullptr)
  143. {
  144. return false;
  145. }
  146. else
  147. {
  148. return std::strcmp(m_ptr, b.m_ptr) > 0;
  149. }
  150. }
  151. Bool operator>=(const CString& b) const
  152. {
  153. if(m_ptr == nullptr || b.m_ptr == nullptr)
  154. {
  155. return m_ptr == b.m_ptr;
  156. }
  157. else
  158. {
  159. return std::strcmp(m_ptr, b.m_ptr) >= 0;
  160. }
  161. }
  162. /// Get the underlying C string.
  163. const char* get() const
  164. {
  165. checkInit();
  166. return m_ptr;
  167. }
  168. /// Get the string length.
  169. U getLength() const
  170. {
  171. if(m_length == 0 && m_ptr != nullptr)
  172. {
  173. m_length = std::strlen(m_ptr);
  174. }
  175. return m_length;
  176. }
  177. PtrSize find(const CString& cstr, PtrSize position = 0) const
  178. {
  179. checkInit();
  180. ANKI_ASSERT(position < getLength());
  181. const Char* out = std::strstr(m_ptr, &cstr[0]);
  182. return (out == nullptr) ? NPOS : (out - m_ptr);
  183. }
  184. /// Convert to F64.
  185. ANKI_USE_RESULT Error toF64(F64& out) const
  186. {
  187. checkInit();
  188. Error err = ErrorCode::NONE;
  189. out = std::strtod(m_ptr, nullptr);
  190. if(out == HUGE_VAL)
  191. {
  192. ANKI_LOGE("Conversion failed");
  193. err = ErrorCode::USER_DATA;
  194. }
  195. return err;
  196. }
  197. /// Convert to F32.
  198. ANKI_USE_RESULT Error toF32(F32& out) const
  199. {
  200. F64 d;
  201. Error err = toF64(d);
  202. if(!err)
  203. {
  204. out = d;
  205. }
  206. return err;
  207. }
  208. /// Convert to I64.
  209. ANKI_USE_RESULT Error toI64(I64& out) const
  210. {
  211. checkInit();
  212. Error err = ErrorCode::NONE;
  213. out = std::strtoll(m_ptr, nullptr, 10);
  214. if(out == LLONG_MAX || out == LLONG_MIN)
  215. {
  216. ANKI_LOGE("Conversion failed");
  217. err = ErrorCode::USER_DATA;
  218. }
  219. return err;
  220. }
  221. private:
  222. const Char* m_ptr = nullptr;
  223. mutable U32 m_length = 0;
  224. /// Constructor for friends
  225. CString(const Char* ptr, U32 length)
  226. : m_ptr(ptr),
  227. m_length(length)
  228. {
  229. checkInit();
  230. ANKI_ASSERT(std::strlen(ptr) == length);
  231. }
  232. void checkInit() const
  233. {
  234. ANKI_ASSERT(m_ptr != nullptr);
  235. }
  236. };
  237. template<typename TAlloc>
  238. using StringScopeDestroyer = ScopeDestroyer<StringBase<TAlloc>, TAlloc>;
  239. /// The base class for strings.
  240. template<typename TAlloc>
  241. class StringBase: public NonCopyable
  242. {
  243. public:
  244. using Char = char; ///< Character type
  245. using Allocator = TAlloc; ///< Allocator type
  246. using Self = StringBase;
  247. using CStringType = CString;
  248. using Iterator = Char*;
  249. using ConstIterator = const Char*;
  250. using ScopeDestroyer = StringScopeDestroyer<Allocator>;
  251. static const PtrSize NPOS = MAX_PTR_SIZE;
  252. /// Default constructor.
  253. StringBase()
  254. {}
  255. /// Move constructor.
  256. StringBase(StringBase&& b)
  257. : m_data(std::move(b.m_data))
  258. {}
  259. /// Requires manual destruction.
  260. ~StringBase()
  261. {}
  262. /// Initialize using a const string.
  263. ANKI_USE_RESULT Error create(Allocator alloc, const CStringType& cstr);
  264. /// Initialize using a range. Copies the range of [first, last)
  265. ANKI_USE_RESULT Error create(Allocator alloc,
  266. ConstIterator first, ConstIterator last);
  267. /// Initialize using a character.
  268. ANKI_USE_RESULT Error create(Allocator alloc, Char c, PtrSize length);
  269. /// Copy one string to this one.
  270. ANKI_USE_RESULT Error create(Allocator alloc, const Self& b)
  271. {
  272. return create(alloc, b.toCString());
  273. }
  274. /// Destroy the string.
  275. void destroy(Allocator alloc)
  276. {
  277. m_data.destroy(alloc);
  278. }
  279. /// Move one string to this one.
  280. Self& operator=(Self&& b)
  281. {
  282. ANKI_ASSERT(this != &b);
  283. m_data = std::move(b.m_data);
  284. return *this;
  285. }
  286. /// Return char at the specified position.
  287. const Char& operator[](U pos) const
  288. {
  289. checkInit();
  290. return m_data[pos];
  291. }
  292. /// Return char at the specified position as a modifiable reference.
  293. Char& operator[](U pos)
  294. {
  295. checkInit();
  296. return m_data[pos];
  297. }
  298. Iterator begin()
  299. {
  300. checkInit();
  301. return &m_data[0];
  302. }
  303. ConstIterator begin() const
  304. {
  305. checkInit();
  306. return &m_data[0];
  307. }
  308. Iterator end()
  309. {
  310. checkInit();
  311. return &m_data[m_data.getSize() - 1];
  312. }
  313. ConstIterator end() const
  314. {
  315. checkInit();
  316. return &m_data[m_data.getSize() - 1];
  317. }
  318. /// Return true if strings are equal
  319. Bool operator==(const Self& b) const
  320. {
  321. checkInit();
  322. b.checkInit();
  323. return std::strcmp(&m_data[0], &b.m_data[0]) == 0;
  324. }
  325. /// Return true if strings are not equal
  326. Bool operator!=(const Self& b) const
  327. {
  328. return !(*this == b);
  329. }
  330. /// Return true if this is less than b
  331. Bool operator<(const Self& b) const
  332. {
  333. checkInit();
  334. b.checkInit();
  335. return std::strcmp(&m_data[0], &b.m_data[0]) < 0;
  336. }
  337. /// Return true if this is less or equal to b
  338. Bool operator<=(const Self& b) const
  339. {
  340. checkInit();
  341. b.checkInit();
  342. return std::strcmp(&m_data[0], &b.m_data[0]) <= 0;
  343. }
  344. /// Return true if this is greater than b
  345. Bool operator>(const Self& b) const
  346. {
  347. checkInit();
  348. b.checkInit();
  349. return std::strcmp(&m_data[0], &b.m_data[0]) > 0;
  350. }
  351. /// Return true if this is greater or equal to b
  352. Bool operator>=(const Self& b) const
  353. {
  354. checkInit();
  355. b.checkInit();
  356. return std::strcmp(&m_data[0], &b.m_data[0]) >= 0;
  357. }
  358. /// Return true if strings are equal
  359. Bool operator==(const CStringType& cstr) const
  360. {
  361. checkInit();
  362. return std::strcmp(&m_data[0], cstr.get()) == 0;
  363. }
  364. /// Return true if strings are not equal
  365. Bool operator!=(const CStringType& cstr) const
  366. {
  367. return !(*this == cstr);
  368. }
  369. /// Return true if this is less than cstr.
  370. Bool operator<(const CStringType& cstr) const
  371. {
  372. checkInit();
  373. return std::strcmp(&m_data[0], cstr.get()) < 0;
  374. }
  375. /// Return true if this is less or equal to cstr.
  376. Bool operator<=(const CStringType& cstr) const
  377. {
  378. checkInit();
  379. return std::strcmp(&m_data[0], cstr.get()) <= 0;
  380. }
  381. /// Return true if this is greater than cstr.
  382. Bool operator>(const CStringType& cstr) const
  383. {
  384. checkInit();
  385. return std::strcmp(&m_data[0], cstr.get()) > 0;
  386. }
  387. /// Return true if this is greater or equal to cstr.
  388. Bool operator>=(const CStringType& cstr) const
  389. {
  390. checkInit();
  391. return std::strcmp(&m_data[0], cstr.get()) >= 0;
  392. }
  393. /// Return the string's length. It doesn't count the terminating character.
  394. PtrSize getLength() const
  395. {
  396. auto size = m_data.getSize();
  397. auto out = (size != 0) ? (size - 1) : 0;
  398. ANKI_ASSERT(std::strlen(&m_data[0]) == out);
  399. return out;
  400. }
  401. /// Return the CString.
  402. CStringType toCString() const
  403. {
  404. checkInit();
  405. return CStringType(&m_data[0], getLength());
  406. }
  407. /// Append another string to this one.
  408. template<typename TTAlloc>
  409. ANKI_USE_RESULT Error append(Allocator alloc, const StringBase<TTAlloc>& b)
  410. {
  411. Error err = ErrorCode::NONE;
  412. if(!b.isEmpty())
  413. {
  414. err = appendInternal(alloc, &b.m_data[0], b.m_data.getSize());
  415. }
  416. return err;
  417. }
  418. /// Append a const string to this one.
  419. ANKI_USE_RESULT Error append(Allocator alloc, const CStringType& cstr)
  420. {
  421. Error err = ErrorCode::NONE;
  422. if(!cstr.isEmpty())
  423. {
  424. err = appendInternal(alloc, &cstr[0], cstr.getLength() + 1);
  425. }
  426. return err;
  427. }
  428. /// Create formated string.
  429. ANKI_USE_RESULT Error sprintf(Allocator alloc, CString fmt, ...);
  430. /// Return true if it's empty.
  431. Bool isEmpty() const
  432. {
  433. return m_data.isEmpty();
  434. }
  435. /// Find a substring of this string.
  436. /// @param[in] cstr The substring to search.
  437. /// @param position Position of the first character in the string to be
  438. /// considered in the search.
  439. /// @return A valid position if the string is found or NPOS if not found.
  440. PtrSize find(const CStringType& cstr, PtrSize position = 0) const
  441. {
  442. checkInit();
  443. return toCString().find(cstr, position);
  444. }
  445. /// Find a substring of this string.
  446. /// @param[in] str The substring to search.
  447. /// @param position Position of the first character in the string to be
  448. /// considered in the search.
  449. /// @return A valid position if the string is found or NPOS if not found.
  450. template<typename TTAlloc>
  451. PtrSize find(
  452. const StringBase<TTAlloc>& str, PtrSize position) const
  453. {
  454. str.chechInit();
  455. return find(str.toCString(), position);
  456. }
  457. /// Convert a number to a string.
  458. template<typename TNumber>
  459. ANKI_USE_RESULT Error toString(Allocator alloc, TNumber number);
  460. /// Convert to F64.
  461. ANKI_USE_RESULT Error toF64(F64& out) const
  462. {
  463. return toCString().toF64(out);
  464. }
  465. /// Convert to I64.
  466. ANKI_USE_RESULT Error toI64(I64& out) const
  467. {
  468. return toCString().toI64(out);
  469. }
  470. private:
  471. DArray<Char> m_data;
  472. void checkInit() const
  473. {
  474. ANKI_ASSERT(m_data.getSize() > 1);
  475. }
  476. /// Append to this string.
  477. ANKI_USE_RESULT Error appendInternal(
  478. Allocator alloc, const Char* str, PtrSize strSize);
  479. };
  480. /// A common string type that uses heap allocator.
  481. using String = StringBase<HeapAllocator<char>>;
  482. /// @}
  483. } // end namespace anki
  484. #include "anki/util/String.inl.h"
  485. #endif