1 // Copyright 2018 The Chromium OS 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 LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_ 6 #define LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_ 7 8 #include <utility> 9 10 #include <base/files/scoped_file.h> 11 #include <base/macros.h> 12 13 namespace brillo { 14 namespace dbus_utils { 15 16 // This struct wraps file descriptors to give them a type other than int. 17 // Implicit conversions are provided because this should be as transparent 18 // a wrapper as possible to match the libchrome bindings below when this 19 // class is used by chromeos-dbus-bindings. 20 // 21 // Because we might pass these around and the calling code neither passes 22 // ownership nor knows when this will be destroyed, it actually dups the FD 23 // so that the calling code and binding code both have a clear handle on the 24 // lifetimes of their respective copies of the FD. 25 struct FileDescriptor { 26 FileDescriptor() = default; FileDescriptorFileDescriptor27 FileDescriptor(int fd) : fd(dup(fd)) {} FileDescriptorFileDescriptor28 FileDescriptor(FileDescriptor&& other) : fd(std::move(other.fd)) {} FileDescriptorFileDescriptor29 FileDescriptor(base::ScopedFD&& other) : fd(std::move(other)) {} 30 31 inline FileDescriptor& operator=(int new_fd) { 32 fd.reset(dup(new_fd)); 33 return *this; 34 } 35 36 FileDescriptor& operator=(FileDescriptor&& other) { 37 fd = std::move(other.fd); 38 return *this; 39 } 40 41 FileDescriptor& operator=(base::ScopedFD&& other) { 42 fd = std::move(other); 43 return *this; 44 } 45 releaseFileDescriptor46 int release() { return fd.release(); } 47 getFileDescriptor48 int get() const { return fd.get(); } 49 50 private: 51 DISALLOW_COPY_AND_ASSIGN(FileDescriptor); 52 53 base::ScopedFD fd; 54 }; 55 56 } // namespace dbus_utils 57 } // namespace brillo 58 59 #endif // LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_ 60