aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/case_insensitive_string/ut_gtest/util/locale_guard.h
blob: 802a83f39246a1710c881996902b6f487d2d0d4e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <util/generic/string.h>
#include <util/system/yassert.h>

#include <cerrno>
#include <clocale>
#include <cstring>

struct [[nodiscard]] TLocaleGuard {
    TLocaleGuard(const char* loc) {
        PrevLoc_ = std::setlocale(LC_ALL, nullptr);
        const char* res = std::setlocale(LC_ALL, loc);
        if (!res) {
            Error_ = std::strerror(errno);
        }
    }

    ~TLocaleGuard() {
        if (!Error_) {
            Y_ABORT_UNLESS(std::setlocale(LC_ALL, PrevLoc_.c_str()));
        }
    }

    const TString& Error() const noexcept {
        return Error_;
    }

private:
    // "POSIX also specifies that the returned pointer, not just the contents of the pointed-to string, may be invalidated by subsequent calls to setlocale".
    TString PrevLoc_;
    TString Error_;
};