cmStringAlgorithms.h 11 KB

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