util.h 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #include "fmt/os.h"
  12. #ifdef _MSC_VER
  13. # define FMT_VSNPRINTF vsprintf_s
  14. #else
  15. # define FMT_VSNPRINTF vsnprintf
  16. #endif
  17. template <size_t SIZE>
  18. void safe_sprintf(char (&buffer)[SIZE], const char* format, ...) {
  19. std::va_list args;
  20. va_start(args, format);
  21. FMT_VSNPRINTF(buffer, SIZE, format, args);
  22. va_end(args);
  23. }
  24. extern const char* const file_content;
  25. // Opens a buffered file for reading.
  26. fmt::buffered_file open_buffered_file(FILE** fp = nullptr);
  27. inline FILE* safe_fopen(const char* filename, const char* mode) {
  28. #if defined(_WIN32) && !defined(__MINGW32__)
  29. // Fix MSVC warning about "unsafe" fopen.
  30. FILE* f = nullptr;
  31. errno = fopen_s(&f, filename, mode);
  32. return f;
  33. #else
  34. return std::fopen(filename, mode);
  35. #endif
  36. }
  37. template <typename Char> class basic_test_string {
  38. private:
  39. std::basic_string<Char> value_;
  40. static const Char empty[];
  41. public:
  42. explicit basic_test_string(const Char* value = empty) : value_(value) {}
  43. const std::basic_string<Char>& value() const { return value_; }
  44. };
  45. template <typename Char> const Char basic_test_string<Char>::empty[] = {0};
  46. typedef basic_test_string<char> test_string;
  47. typedef basic_test_string<wchar_t> test_wstring;
  48. template <typename Char>
  49. std::basic_ostream<Char>& operator<<(std::basic_ostream<Char>& os,
  50. const basic_test_string<Char>& s) {
  51. os << s.value();
  52. return os;
  53. }
  54. class date {
  55. int year_, month_, day_;
  56. public:
  57. date(int year, int month, int day) : year_(year), month_(month), day_(day) {}
  58. int year() const { return year_; }
  59. int month() const { return month_; }
  60. int day() const { return day_; }
  61. };
  62. // Returns a locale with the given name if available or classic locale otherwise.
  63. std::locale get_locale(const char* name, const char* alt_name = nullptr);