util.h 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Formatting library for C++ - test utilities
  2. //
  3. // Copyright (c) 2012 - present, Victor Zverovich
  4. // All rights reserved.
  5. //
  6. // For the license information refer to format.h.
  7. #include <cstdarg>
  8. #include <cstdio>
  9. #include <locale>
  10. #include <string>
  11. #ifdef FMT_MODULE_TEST
  12. import fmt;
  13. #else
  14. # include "fmt/os.h"
  15. #endif // FMT_MODULE_TEST
  16. #ifdef _MSC_VER
  17. # define FMT_VSNPRINTF vsprintf_s
  18. #else
  19. # define FMT_VSNPRINTF vsnprintf
  20. #endif
  21. template <size_t SIZE>
  22. void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {
  23. std::va_list args;
  24. va_start(args, format);
  25. FMT_VSNPRINTF(buffer, SIZE, format, args);
  26. va_end(args);
  27. }
  28. extern const char* const file_content;
  29. // Opens a buffered file for reading.
  30. fmt::buffered_file open_buffered_file(FILE** fp = nullptr);
  31. inline FILE* safe_fopen(const char* filename, const char* mode) {
  32. #if defined(_WIN32) && !defined(__MINGW32__)
  33. // Fix MSVC warning about "unsafe" fopen.
  34. FILE* f = nullptr;
  35. errno = fopen_s(&f, filename, mode);
  36. return f;
  37. #else
  38. return std::fopen(filename, mode);
  39. #endif
  40. }
  41. template <typename Char> class basic_test_string {
  42. private:
  43. std::basic_string<Char> value_;
  44. static const Char empty[];
  45. public:
  46. explicit basic_test_string(const Char* value = empty) : value_(value) {}
  47. const std::basic_string<Char>& value() const { return value_; }
  48. };
  49. template <typename Char> const Char basic_test_string<Char>::empty[] = {0};
  50. typedef basic_test_string<char> test_string;
  51. typedef basic_test_string<wchar_t> test_wstring;
  52. template <typename Char>
  53. std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os,
  54. const basic_test_string<Char>& s) {
  55. os << s.value();
  56. return os;
  57. }
  58. class date {
  59. int year_, month_, day_;
  60. public:
  61. date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
  62. int year() const { return year_; }
  63. int month() const { return month_; }
  64. int day() const { return day_; }
  65. };
  66. // Returns a locale with the given name if available or classic locale othewise.
  67. std::locale get_locale(const char* name, const char* alt_name = nullptr);