xref: /aosp_15_r20/external/cronet/base/scoped_clear_last_error.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2018 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_CLEAR_LAST_ERROR_H_
6 #define BASE_SCOPED_CLEAR_LAST_ERROR_H_
7 
8 #include <errno.h>
9 
10 #include "base/base_export.h"
11 #include "build/build_config.h"
12 
13 namespace base {
14 
15 // ScopedClearLastError stores and resets the value of thread local error codes
16 // (errno, GetLastError()), and restores them in the destructor. This is useful
17 // to avoid side effects on these values in instrumentation functions that
18 // interact with the OS.
19 
20 // Common implementation of ScopedClearLastError for all platforms. Use
21 // ScopedClearLastError instead.
22 class BASE_EXPORT ScopedClearLastErrorBase {
23  public:
ScopedClearLastErrorBase()24   ScopedClearLastErrorBase() : last_errno_(errno) { errno = 0; }
25   ScopedClearLastErrorBase(const ScopedClearLastErrorBase&) = delete;
26   ScopedClearLastErrorBase& operator=(const ScopedClearLastErrorBase&) = delete;
~ScopedClearLastErrorBase()27   ~ScopedClearLastErrorBase() { errno = last_errno_; }
28 
29  private:
30   const int last_errno_;
31 };
32 
33 #if BUILDFLAG(IS_WIN)
34 
35 // Windows specific implementation of ScopedClearLastError.
36 class BASE_EXPORT ScopedClearLastError : public ScopedClearLastErrorBase {
37  public:
38   ScopedClearLastError();
39   ScopedClearLastError(const ScopedClearLastError&) = delete;
40   ScopedClearLastError& operator=(const ScopedClearLastError&) = delete;
41   ~ScopedClearLastError();
42 
43  private:
44   const unsigned long last_system_error_;
45 };
46 
47 #elif BUILDFLAG(IS_POSIX) || BUILDFLAG(IS_FUCHSIA)
48 
49 using ScopedClearLastError = ScopedClearLastErrorBase;
50 
51 #endif  // BUILDFLAG(IS_WIN)
52 
53 }  // namespace base
54 
55 #endif  // BASE_SCOPED_CLEAR_LAST_ERROR_H_
56