string_utils.h 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. /*
  2. * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #pragma once
  17. #include <memory> // std::make_unique
  18. #include <sstream> // std::stringstream
  19. #include <string>
  20. #include <vector>
  21. namespace fastertransformer {
  22. template<typename... Args>
  23. inline std::string fmtstr(const std::string& format, Args... args)
  24. {
  25. // This function came from a code snippet in stackoverflow under cc-by-1.0
  26. // https://stackoverflow.com/questions/2342162/stdstring-formatting-like-sprintf
  27. // Disable format-security warning in this function.
  28. #if defined(_MSC_VER) // for visual studio
  29. #pragma warning(push)
  30. #pragma warning(warning(disable : 4996))
  31. #elif defined(__GNUC__) || defined(__clang__) // for gcc or clang
  32. #pragma GCC diagnostic push
  33. #pragma GCC diagnostic ignored "-Wformat-security"
  34. #endif
  35. int size_s = std::snprintf(nullptr, 0, format.c_str(), args...) + 1; // Extra space for '\0'
  36. if (size_s <= 0) {
  37. throw std::runtime_error("Error during formatting.");
  38. }
  39. auto size = static_cast<size_t>(size_s);
  40. auto buf = std::make_unique<char[]>(size);
  41. std::snprintf(buf.get(), size, format.c_str(), args...);
  42. #if defined(_MSC_VER)
  43. #pragma warning(pop)
  44. #elif defined(__GNUC__) || defined(__clang__)
  45. #pragma GCC diagnostic pop
  46. #endif
  47. return std::string(buf.get(), buf.get() + size - 1); // We don't want the '\0' inside
  48. }
  49. } // namespace fastertransformer