xref: /aosp_15_r20/external/cronet/base/scoped_environment_variable_override.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2017 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #ifndef BASE_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_
6 #define BASE_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_
7 
8 #include <memory>
9 #include <string>
10 
11 #include "base/base_export.h"
12 
13 namespace base {
14 
15 class Environment;
16 
17 // Helper class to override |variable_name| environment variable to |value| for
18 // the lifetime of this class. Upon destruction, the previous value is restored.
19 class BASE_EXPORT ScopedEnvironmentVariableOverride final {
20  public:
21   ScopedEnvironmentVariableOverride(const std::string& variable_name,
22                                     const std::string& value);
23   // Unset the variable.
24   explicit ScopedEnvironmentVariableOverride(const std::string& variable_name);
25   ScopedEnvironmentVariableOverride(ScopedEnvironmentVariableOverride&&);
26   ScopedEnvironmentVariableOverride& operator=(
27       ScopedEnvironmentVariableOverride&&);
28   ~ScopedEnvironmentVariableOverride();
29 
GetEnv()30   base::Environment* GetEnv() { return environment_.get(); }
IsOverridden()31   bool IsOverridden() { return overridden_; }
32 
33  private:
34   ScopedEnvironmentVariableOverride(const std::string& variable_name,
35                                     const std::string& value,
36                                     bool unset_var);
37   std::unique_ptr<Environment> environment_;
38   std::string variable_name_;
39   bool overridden_;
40   bool was_set_;
41   std::string old_value_;
42 };
43 
44 }  // namespace base
45 
46 #endif  // BASE_SCOPED_ENVIRONMENT_VARIABLE_OVERRIDE_H_
47