locale_guard.h 801 B

12345678910111213141516171819202122232425262728293031
  1. #include <util/generic/string.h>
  2. #include <util/system/yassert.h>
  3. #include <cerrno>
  4. #include <clocale>
  5. #include <cstring>
  6. struct [[nodiscard]] TLocaleGuard {
  7. TLocaleGuard(const char* loc) {
  8. PrevLoc_ = std::setlocale(LC_ALL, nullptr);
  9. const char* res = std::setlocale(LC_ALL, loc);
  10. if (!res) {
  11. Error_ = std::strerror(errno);
  12. }
  13. }
  14. ~TLocaleGuard() {
  15. if (!Error_) {
  16. Y_ABORT_UNLESS(std::setlocale(LC_ALL, PrevLoc_.c_str()));
  17. }
  18. }
  19. const TString& Error() const noexcept {
  20. return Error_;
  21. }
  22. private:
  23. // "POSIX also specifies that the returned pointer, not just the contents of the pointed-to string, may be invalidated by subsequent calls to setlocale".
  24. TString PrevLoc_;
  25. TString Error_;
  26. };