scraps

Abandon all hope, ye who enter here.
git clone https://git.neptards.moe/neptards/scraps.git
Log | Files | Refs | Submodules | README | LICENSE

scoped_setenv.hpp (1258B)


      1 #ifndef GUARD_ALINE_HARD_ON_THE_EYES_ROENTGENOLOGIST_UNDERRECORDS_2437
      2 #define GUARD_ALINE_HARD_ON_THE_EYES_ROENTGENOLOGIST_UNDERRECORDS_2437
      3 #pragma once
      4 
      5 #include <libshit/abomination.hpp>
      6 #include <libshit/platform.hpp>
      7 #include <libshit/utils.hpp>
      8 
      9 #include <optional>
     10 #include <string>
     11 #include <type_traits>
     12 
     13 #if LIBSHIT_OS_IS_WINDOWS
     14 #  define tzset _tzset
     15 #endif
     16 
     17 namespace Scraps
     18 {
     19 
     20   class ScopedSetenv
     21   {
     22   public:
     23     ScopedSetenv(std::string key, const char* new_value)
     24       : key{Libshit::Move(key)}
     25     {
     26       auto old = Libshit::Abomination::getenv(this->key.c_str());
     27       if (old) value = old;
     28       Libshit::Abomination::setenv(this->key.c_str(), new_value, true);
     29     }
     30     ScopedSetenv(const ScopedSetenv&) = delete;
     31     void operator=(const ScopedSetenv&) = delete;
     32 
     33     ~ScopedSetenv()
     34     {
     35       if (value.has_value())
     36         Libshit::Abomination::setenv(key.c_str(), value->c_str(), true);
     37       else Libshit::Abomination::unsetenv(key.c_str());
     38     }
     39 
     40   private:
     41     std::string key;
     42     std::optional<std::string> value;
     43   };
     44 
     45   /// Use some random fixed timezone in tests. Do not call in production code!
     46   struct ScopedTzset : ScopedSetenv
     47   {
     48     ScopedTzset(const char* tz, int diff);
     49     ~ScopedTzset();
     50   };
     51 
     52 }
     53 
     54 #endif