scoped_set_env.cc
Go to the documentation of this file.
00001 // Copyright 2019 The Abseil Authors.
00002 //
00003 // Licensed under the Apache License, Version 2.0 (the "License");
00004 // you may not use this file except in compliance with the License.
00005 // You may obtain a copy of the License at
00006 //
00007 //      https://www.apache.org/licenses/LICENSE-2.0
00008 //
00009 // Unless required by applicable law or agreed to in writing, software
00010 // distributed under the License is distributed on an "AS IS" BASIS,
00011 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00012 // See the License for the specific language governing permissions and
00013 // limitations under the License.
00014 
00015 #include "absl/base/internal/scoped_set_env.h"
00016 
00017 #ifdef _WIN32
00018 #include <windows.h>
00019 #endif
00020 
00021 #include <cstdlib>
00022 
00023 #include "absl/base/internal/raw_logging.h"
00024 
00025 namespace absl {
00026 namespace base_internal {
00027 
00028 namespace {
00029 
00030 #ifdef _WIN32
00031 const int kMaxEnvVarValueSize = 1024;
00032 #endif
00033 
00034 void SetEnvVar(const char* name, const char* value) {
00035 #ifdef _WIN32
00036   SetEnvironmentVariableA(name, value);
00037 #else
00038   if (value == nullptr) {
00039     ::unsetenv(name);
00040   } else {
00041     ::setenv(name, value, 1);
00042   }
00043 #endif
00044 }
00045 
00046 }  // namespace
00047 
00048 ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value)
00049     : var_name_(var_name), was_unset_(false) {
00050 #ifdef _WIN32
00051   char buf[kMaxEnvVarValueSize];
00052   auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf));
00053   ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size");
00054 
00055   if (get_res == 0) {
00056     was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
00057   } else {
00058     old_value_.assign(buf, get_res);
00059   }
00060 
00061   SetEnvironmentVariableA(var_name_.c_str(), new_value);
00062 #else
00063   const char* val = ::getenv(var_name_.c_str());
00064   if (val == nullptr) {
00065     was_unset_ = true;
00066   } else {
00067     old_value_ = val;
00068   }
00069 #endif
00070 
00071   SetEnvVar(var_name_.c_str(), new_value);
00072 }
00073 
00074 ScopedSetEnv::~ScopedSetEnv() {
00075   SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str());
00076 }
00077 
00078 }  // namespace base_internal
00079 }  // namespace absl


abseil_cpp
Author(s):
autogenerated on Wed Jun 19 2019 19:42:15