Imported Upstream version 14.48.2
[platform/upstream/libzypp.git] / zypp / base / LocaleGuard.h
1 /*---------------------------------------------------------------------\
2 |                          ____ _   __ __ ___                          |
3 |                         |__  / \ / / . \ . \                         |
4 |                           / / \ V /|  _/  _/                         |
5 |                          / /__ | | | | | |                           |
6 |                         /_____||_| |_| |_|                           |
7 |                                                                      |
8 \---------------------------------------------------------------------*/
9 /** \file       zypp/base/LocaleGuard.h
10  */
11 #ifndef ZYPP_BASE_LOCALEGUARD_H
12 #define ZYPP_BASE_LOCALEGUARD_H
13
14 #include <locale.h>
15 #include <string>
16
17 #include "zypp/base/Easy.h"
18
19 ///////////////////////////////////////////////////////////////////
20 namespace zypp
21 {
22   ///////////////////////////////////////////////////////////////////
23   /// \class LocaleGuard
24   /// \brief Temorarily change a locale category value
25   /// \ingroup g_RAII
26   ///////////////////////////////////////////////////////////////////
27   class LocaleGuard
28   {
29     NON_COPYABLE(LocaleGuard);
30     NON_MOVABLE(LocaleGuard);
31
32   public:
33     /** Ctor saving the current locale category value. */
34     LocaleGuard( int category_r, const std::string & value_r = "C" )
35     : _category( -1 )
36     {
37       const char * ovalue = ::setlocale( category_r, nullptr );
38       if ( ovalue && ovalue != value_r )
39       {
40         _category = category_r;
41         _value    = ovalue;
42         ::setlocale( _category, value_r.c_str() );
43       }
44     }
45
46     /** Dtor asserts the saved locale category value is restored. */
47     ~LocaleGuard()
48     { restore(); }
49
50     /** immediately restore the saved locale category value. */
51     void restore()
52     {
53       if ( _category != -1 )
54       {
55         ::setlocale( _category, _value.c_str() );
56         _category = -1;
57       }
58     }
59
60   private:
61     int         _category;      ///< saved category or -1 if no restore needed
62     std::string _value;         ///< saved category value
63   };
64 } // namespace zypp
65 ///////////////////////////////////////////////////////////////////
66 #endif // ZYPP_BASE_LOCALEGUARD_H