cmStringAlgorithms.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #pragma once
  4. #include "cmConfigure.h" // IWYU pragma: keep
  5. #include <cctype>
  6. #include <cstring>
  7. #include <initializer_list>
  8. #include <iterator>
  9. #include <numeric>
  10. #include <sstream>
  11. #include <string>
  12. #include <utility>
  13. #include <vector>
  14. #include <cm/string_view>
  15. #include "cmRange.h"
  16. #include "cmValue.h"
  17. /** String range type. */
  18. using cmStringRange = cmRange<std::vector<std::string>::const_iterator>;
  19. /** Returns length of a literal string. */
  20. template <size_t N>
  21. constexpr size_t cmStrLen(const char (&)[N])
  22. {
  23. return N - 1;
  24. }
  25. /** Callable string comparison struct. */
  26. struct cmStrCmp
  27. {
  28. cmStrCmp(std::string str)
  29. : Test_(std::move(str))
  30. {
  31. }
  32. bool operator()(cm::string_view sv) const { return this->Test_ == sv; }
  33. private:
  34. std::string const Test_;
  35. };
  36. /**
  37. * Test if two strings are identical, ignoring case.
  38. *
  39. * Note that this is not guaranteed to work correctly on non-ASCII strings.
  40. */
  41. bool cmStrCaseEq(cm::string_view a, cm::string_view b);
  42. /** Returns true if the character @a ch is a whitespace character. **/
  43. inline bool cmIsSpace(char ch)
  44. {
  45. // isspace takes 'int' but documents that the value must be representable
  46. // by 'unsigned char', or be EOF. Cast to 'unsigned char' to avoid sign
  47. // extension while converting to 'int'.
  48. return std::isspace(static_cast<unsigned char>(ch));
  49. }
  50. /** Returns a string that has whitespace removed from the start and the end. */
  51. std::string cmTrimWhitespace(cm::string_view str);
  52. /** Returns a string that has quotes removed from the start and the end. */
  53. std::string cmRemoveQuotes(cm::string_view str);
  54. /** Escape quotes in a string. */
  55. std::string cmEscapeQuotes(cm::string_view str);
  56. /** Joins elements of a range with separator into a single string. */
  57. template <typename Range>
  58. std::string cmJoin(Range const& rng, cm::string_view separator)
  59. {
  60. if (rng.empty()) {
  61. return std::string();
  62. }
  63. std::ostringstream os;
  64. auto it = rng.begin();
  65. auto const end = rng.end();
  66. os << *it;
  67. while (++it != end) {
  68. os << separator << *it;
  69. }
  70. return os.str();
  71. }
  72. /** Generic function to join strings range with separator
  73. * and initial leading string into a single string.
  74. */
  75. template <typename Range>
  76. std::string cmJoinStrings(Range const& rng, cm::string_view separator,
  77. cm::string_view initial)
  78. {
  79. if (rng.empty()) {
  80. return { std::begin(initial), std::end(initial) };
  81. }
  82. std::string result;
  83. result.reserve(std::accumulate(
  84. std::begin(rng), std::end(rng),
  85. initial.size() + (rng.size() - 1) * separator.size(),
  86. [](std::size_t sum, typename Range::value_type const& item) {
  87. return sum + item.size();
  88. }));
  89. result.append(std::begin(initial), std::end(initial));
  90. auto begin = std::begin(rng);
  91. auto end = std::end(rng);
  92. result += *begin;
  93. for (++begin; begin != end; ++begin) {
  94. result.append(std::begin(separator), std::end(separator));
  95. result += *begin;
  96. }
  97. return result;
  98. }
  99. /**
  100. * Faster overloads for std::string ranges.
  101. * If @a initial is provided, it prepends the resulted string without
  102. * @a separator between them.
  103. */
  104. std::string cmJoin(std::vector<std::string> const& rng,
  105. cm::string_view separator, cm::string_view initial = {});
  106. std::string cmJoin(cmStringRange const& rng, cm::string_view separator,
  107. cm::string_view initial = {});
  108. enum class cmTokenizerMode
  109. {
  110. /// A backward-compatible behavior when in the case of no
  111. /// tokens have found in an input text it'll return one empty
  112. /// token in the result container (vector).
  113. Legacy,
  114. /// The new behavior is to return an empty vector.
  115. New
  116. };
  117. /**
  118. * \brief A generic version of a tokenizer.
  119. *
  120. * Extract tokens from the input string separated by any
  121. * of the characters in `sep` and assign them to the
  122. * given output iterator.
  123. *
  124. * The `mode` parameter defines the behavior in the case when
  125. * no tokens have found in the input text.
  126. *
  127. */
  128. template <typename StringT, typename OutIt, typename Sep = char>
  129. void cmTokenize(OutIt outIt, cm::string_view str, Sep sep,
  130. cmTokenizerMode mode)
  131. {
  132. auto hasTokens = false;
  133. // clang-format off
  134. for (auto start = str.find_first_not_of(sep)
  135. , end = str.find_first_of(sep, start)
  136. ; start != cm::string_view::npos
  137. ; start = str.find_first_not_of(sep, end)
  138. , end = str.find_first_of(sep, start)
  139. , hasTokens = true
  140. ) {
  141. *outIt++ = StringT{ str.substr(start, end - start) };
  142. }
  143. // clang-format on
  144. if (!hasTokens && mode == cmTokenizerMode::Legacy) {
  145. *outIt = {};
  146. }
  147. }
  148. /**
  149. * \brief Extract tokens that are separated by any of the
  150. * characters in `sep`.
  151. *
  152. * Backward compatible signature.
  153. *
  154. * \return A vector of strings.
  155. */
  156. template <typename Sep = char>
  157. std::vector<std::string> cmTokenize(
  158. cm::string_view str, Sep sep, cmTokenizerMode mode = cmTokenizerMode::Legacy)
  159. {
  160. using StringType = std::string;
  161. std::vector<StringType> tokens;
  162. cmTokenize<StringType>(std::back_inserter(tokens), str, sep, mode);
  163. return tokens;
  164. }
  165. /**
  166. * \brief Extract tokens that are separated by any of the
  167. * characters in `sep`.
  168. *
  169. * \return A vector of string views.
  170. */
  171. template <typename Sep = char>
  172. std::vector<cm::string_view> cmTokenizedView(
  173. cm::string_view str, Sep sep, cmTokenizerMode mode = cmTokenizerMode::Legacy)
  174. {
  175. using StringType = cm::string_view;
  176. std::vector<StringType> tokens;
  177. cmTokenize<StringType>(std::back_inserter(tokens), str, sep, mode);
  178. return tokens;
  179. }
  180. /** Concatenate string pieces into a single string. */
  181. std::string cmCatViews(
  182. std::initializer_list<std::pair<cm::string_view, std::string*>> views);
  183. /** Utility class for cmStrCat. */
  184. class cmAlphaNum
  185. {
  186. public:
  187. cmAlphaNum(cm::string_view view)
  188. : View_(view)
  189. {
  190. }
  191. cmAlphaNum(std::string const& str)
  192. : View_(str)
  193. {
  194. }
  195. cmAlphaNum(std::string&& str)
  196. : RValueString_(&str)
  197. {
  198. }
  199. cmAlphaNum(const char* str)
  200. : View_(str ? cm::string_view(str) : cm::string_view())
  201. {
  202. }
  203. cmAlphaNum(char ch)
  204. : View_(this->Digits_, 1)
  205. {
  206. this->Digits_[0] = ch;
  207. }
  208. cmAlphaNum(int val);
  209. cmAlphaNum(unsigned int val);
  210. cmAlphaNum(long int val);
  211. cmAlphaNum(unsigned long int val);
  212. cmAlphaNum(long long int val);
  213. cmAlphaNum(unsigned long long int val);
  214. cmAlphaNum(float val);
  215. cmAlphaNum(double val);
  216. cmAlphaNum(cmValue value)
  217. : View_(*value)
  218. {
  219. }
  220. cm::string_view View() const
  221. {
  222. if (this->RValueString_) {
  223. return *this->RValueString_;
  224. }
  225. return this->View_;
  226. }
  227. std::string* RValueString() const { return this->RValueString_; }
  228. private:
  229. std::string* RValueString_ = nullptr;
  230. cm::string_view View_;
  231. char Digits_[32];
  232. };
  233. /** Concatenate string pieces and numbers into a single string. */
  234. template <typename A, typename B, typename... AV>
  235. inline std::string cmStrCat(A&& a, B&& b, AV&&... args)
  236. {
  237. static auto const makePair =
  238. [](const cmAlphaNum& arg) -> std::pair<cm::string_view, std::string*> {
  239. return { arg.View(), arg.RValueString() };
  240. };
  241. return cmCatViews({ makePair(std::forward<A>(a)),
  242. makePair(std::forward<B>(b)),
  243. makePair(std::forward<AV>(args))... });
  244. }
  245. /** Joins wrapped elements of a range with separator into a single string. */
  246. template <typename Range>
  247. std::string cmWrap(cm::string_view prefix, Range const& rng,
  248. cm::string_view suffix, cm::string_view sep)
  249. {
  250. if (rng.empty()) {
  251. return std::string();
  252. }
  253. return cmCatViews({ { prefix, nullptr },
  254. { cmJoin(rng,
  255. cmCatViews({ { suffix, nullptr },
  256. { sep, nullptr },
  257. { prefix, nullptr } })),
  258. nullptr },
  259. { suffix, nullptr } });
  260. }
  261. /** Joins wrapped elements of a range with separator into a single string. */
  262. template <typename Range>
  263. std::string cmWrap(char prefix, Range const& rng, char suffix,
  264. cm::string_view sep)
  265. {
  266. return cmWrap(cm::string_view(&prefix, 1), rng, cm::string_view(&suffix, 1),
  267. sep);
  268. }
  269. /** Returns true if string @a str starts with the character @a prefix. */
  270. inline bool cmHasPrefix(cm::string_view str, char prefix)
  271. {
  272. return !str.empty() && (str.front() == prefix);
  273. }
  274. /** Returns true if string @a str starts with string @a prefix. */
  275. inline bool cmHasPrefix(cm::string_view str, cm::string_view prefix)
  276. {
  277. return str.compare(0, prefix.size(), prefix) == 0;
  278. }
  279. /** Returns true if string @a str starts with string @a prefix. */
  280. inline bool cmHasPrefix(cm::string_view str, cmValue prefix)
  281. {
  282. if (!prefix) {
  283. return false;
  284. }
  285. return str.compare(0, prefix->size(), *prefix) == 0;
  286. }
  287. /** Returns true if string @a str starts with string @a prefix. */
  288. template <size_t N>
  289. inline bool cmHasLiteralPrefix(cm::string_view str, const char (&prefix)[N])
  290. {
  291. return cmHasPrefix(str, cm::string_view(prefix, N - 1));
  292. }
  293. /** Returns true if string @a str ends with the character @a suffix. */
  294. inline bool cmHasSuffix(cm::string_view str, char suffix)
  295. {
  296. return !str.empty() && (str.back() == suffix);
  297. }
  298. /** Returns true if string @a str ends with string @a suffix. */
  299. inline bool cmHasSuffix(cm::string_view str, cm::string_view suffix)
  300. {
  301. return str.size() >= suffix.size() &&
  302. str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
  303. }
  304. /** Returns true if string @a str ends with string @a suffix. */
  305. inline bool cmHasSuffix(cm::string_view str, cmValue suffix)
  306. {
  307. if (!suffix) {
  308. return false;
  309. }
  310. return str.size() >= suffix->size() &&
  311. str.compare(str.size() - suffix->size(), suffix->size(), *suffix) == 0;
  312. }
  313. /** Returns true if string @a str ends with string @a suffix. */
  314. template <size_t N>
  315. inline bool cmHasLiteralSuffix(cm::string_view str, const char (&suffix)[N])
  316. {
  317. return cmHasSuffix(str, cm::string_view(suffix, N - 1));
  318. }
  319. /** Removes an existing suffix character of from the string @a str. */
  320. inline void cmStripSuffixIfExists(std::string& str, char suffix)
  321. {
  322. if (cmHasSuffix(str, suffix)) {
  323. str.pop_back();
  324. }
  325. }
  326. /** Removes an existing suffix string of from the string @a str. */
  327. inline void cmStripSuffixIfExists(std::string& str, cm::string_view suffix)
  328. {
  329. if (cmHasSuffix(str, suffix)) {
  330. str.resize(str.size() - suffix.size());
  331. }
  332. }
  333. /** Converts a string to long. Expects that the whole string is an integer. */
  334. bool cmStrToLong(const char* str, long* value);
  335. bool cmStrToLong(std::string const& str, long* value);
  336. /** Converts a string to unsigned long. Expects that the whole string is an
  337. * integer */
  338. bool cmStrToULong(const char* str, unsigned long* value);
  339. bool cmStrToULong(std::string const& str, unsigned long* value);
  340. /** Converts a string to long long. Expects that the whole string
  341. * is an integer */
  342. bool cmStrToLongLong(const char* str, long long* value);
  343. bool cmStrToLongLong(std::string const& str, long long* value);
  344. /** Converts a string to unsigned long long. Expects that the whole string
  345. * is an integer */
  346. bool cmStrToULongLong(const char* str, unsigned long long* value);
  347. bool cmStrToULongLong(std::string const& str, unsigned long long* value);