string.h 1.56 KB
Newer Older
Tim Moon's avatar
Tim Moon committed
1
/*************************************************************************
2
 * Copyright (c) 2022-2024, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
Tim Moon's avatar
Tim Moon committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 *
 * See LICENSE for license information.
 ************************************************************************/

#ifndef TRANSFORMER_ENGINE_COMMON_UTIL_STRING_H_
#define TRANSFORMER_ENGINE_COMMON_UTIL_STRING_H_

#include <regex>  // NOLINT(*)
#include <string>
#include <type_traits>

namespace transformer_engine {

/*! \brief Convert to C-style or C++-style string */
17
template <typename T, typename = typename std::enable_if<std::is_arithmetic<T>::value>::type>
Tim Moon's avatar
Tim Moon committed
18
19
20
21
inline std::string to_string_like(const T &val) {
  return std::to_string(val);
}

22
inline const std::string &to_string_like(const std::string &val) noexcept { return val; }
Tim Moon's avatar
Tim Moon committed
23

24
constexpr const char *to_string_like(const char *val) noexcept { return val; }
Tim Moon's avatar
Tim Moon committed
25
26
27

/*! \brief Convert arguments to strings and concatenate */
template <typename... Ts>
28
inline std::string concat_strings(const Ts &...args) {
Tim Moon's avatar
Tim Moon committed
29
30
31
32
33
34
35
36
37
38
39
  std::string str;
  str.reserve(1024);  // Assume strings are <1 KB
  (..., (str += to_string_like(args)));
  return str;
}

/*! \brief Substitute regex occurances in string
 *
 * This is a convenience wrapper around std::regex_replace.
 */
template <typename T>
40
inline std::string regex_replace(const std::string &str, const std::string &pattern,
Tim Moon's avatar
Tim Moon committed
41
                                 const T &replacement) {
42
  return std::regex_replace(str, std::regex(pattern), to_string_like(replacement));
Tim Moon's avatar
Tim Moon committed
43
44
45
46
47
}

}  // namespace transformer_engine

#endif  // TRANSFORMER_ENGINE_COMMON_UTIL_STRING_H_