1 // Copyright 2014 The Android Open Source Project 2 // 3 // This software is licensed under the terms of the GNU General Public 4 // License version 2, as published by the Free Software Foundation, and 5 // may be copied, distributed, and modified under those terms. 6 // 7 // This program is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 // GNU General Public License for more details. 11 12 #ifndef ANDROID_BASE_FILES_SCOPED_HANDLE_H 13 #define ANDROID_BASE_FILES_SCOPED_HANDLE_H 14 15 #if !defined(_WIN32) && !defined(_WIN64) 16 #error "Only compile this file when targetting Windows!" 17 #endif 18 19 #include "android/base/Compiler.h" 20 21 #define WIN32_LEAN_AND_MEAN 1 22 #include <windows.h> 23 24 namespace android { 25 namespace base { 26 27 // Helper class used to wrap a Win32 HANDLE that will be closed when 28 // the instance is destroyed, unless the release() method was called 29 // before that. 30 class ScopedHandle { 31 public: 32 // Default destructor is used to wrap an invalid handle value. 33 ScopedHandle() : handle_(INVALID_HANDLE_VALUE) {} 34 35 // Constructor takes ownership of |handle|. 36 explicit ScopedHandle(HANDLE handle) : handle_(handle) {} 37 38 // Destructor calls close() method. 39 ~ScopedHandle() { close(); } 40 41 // Returns true iff the wrapped HANDLE value is valid. 42 bool valid() const { return handle_ != INVALID_HANDLE_VALUE; } 43 44 // Return current HANDLE value. Does _not_ transfer ownership. 45 HANDLE get() const { return handle_; } 46 47 // Return current HANDLE value, transferring ownership to the caller. 48 HANDLE release() { 49 HANDLE h = handle_; 50 handle_ = INVALID_HANDLE_VALUE; 51 return h; 52 } 53 54 // Close handle if it is not invalid. 55 void close() { 56 if (handle_ != INVALID_HANDLE_VALUE) { 57 ::CloseHandle(handle_); 58 handle_ = INVALID_HANDLE_VALUE; 59 } 60 } 61 62 // Swap the content of two ScopedHandle instances. 63 void swap(ScopedHandle* other) { 64 HANDLE handle = handle_; 65 handle_ = other->handle_; 66 other->handle_ = handle; 67 } 68 69 private: 70 DISALLOW_COPY_AND_ASSIGN(ScopedHandle); 71 72 HANDLE handle_; 73 }; 74 75 } // namespace base 76 } // namespace android 77 78 #endif // ANDROID_BASE_FILES_SCOPED_HANDLE_H 79