1 // Copyright (c) 2013 The Chromium Authors. All rights reserved. 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 PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ 6 #define PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ 7 8 #include <string.h> 9 10 #include "ppapi/c/private/pp_file_handle.h" 11 #include "ppapi/cpp/output_traits.h" 12 13 namespace pp { 14 15 // A wrapper class for PP_FileHandle to make sure a file handle is 16 // closed. This object takes the ownership of the file handle when it 17 // is constructed. This loses the ownership when this object is 18 // assigned to another object, just like auto_ptr. 19 class PassFileHandle { 20 public: 21 PassFileHandle(); 22 // This constructor takes the ownership of |handle|. 23 explicit PassFileHandle(PP_FileHandle handle); 24 // Moves the ownership of |handle| to this object. 25 PassFileHandle(PassFileHandle& handle); 26 ~PassFileHandle(); 27 28 // Releases |handle_|. The caller must close the file handle returned. 29 PP_FileHandle Release(); 30 31 private: 32 // PassFileHandleRef allows users to return PassFileHandle as a 33 // value. This technique is also used by auto_ptr_ref. 34 struct PassFileHandleRef { 35 PP_FileHandle handle; 36 explicit PassFileHandleRef(PP_FileHandle h) 37 : handle(h) { 38 } 39 }; 40 41 public: 42 PassFileHandle(PassFileHandleRef ref) 43 : handle_(ref.handle) { 44 } 45 46 operator PassFileHandleRef() { 47 return PassFileHandleRef(Release()); 48 } 49 50 private: 51 void operator=(const PassFileHandle&); 52 53 void Close(); 54 55 PP_FileHandle handle_; 56 }; 57 58 namespace internal { 59 60 template<> 61 struct CallbackOutputTraits<PassFileHandle> { 62 typedef PP_FileHandle* APIArgType; 63 typedef PP_FileHandle StorageType; 64 65 static inline APIArgType StorageToAPIArg(StorageType& t) { 66 return &t; 67 } 68 69 static inline PassFileHandle StorageToPluginArg(StorageType& t) { 70 return PassFileHandle(t); 71 } 72 73 static inline void Initialize(StorageType* t) { 74 memset(t, 0, sizeof(*t)); 75 } 76 }; 77 78 } // namespace internal 79 } // namespace pp 80 81 #endif // PPAPI_CPP_PRIVATE_PASS_FILE_HANDLE_H_ 82