Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 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 | |
Eric Caruso | 75578a9 | 2018-03-29 11:33:59 -0700 | [diff] [blame^] | 8 | #include <base/files/scoped_file.h> |
| 9 | #include <base/macros.h> |
| 10 | |
Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 11 | namespace brillo { |
| 12 | namespace dbus_utils { |
| 13 | |
| 14 | // This struct wraps file descriptors to give them a type other than int. |
| 15 | // Implicit conversions are provided because this should be as transparent |
| 16 | // a wrapper as possible to match the libchrome bindings below when this |
| 17 | // class is used by chromeos-dbus-bindings. |
Eric Caruso | 75578a9 | 2018-03-29 11:33:59 -0700 | [diff] [blame^] | 18 | // |
| 19 | // Because we might pass these around and the calling code neither passes |
| 20 | // ownership nor knows when this will be destroyed, it actually dups the FD |
| 21 | // so that the calling code and binding code both have a clear handle on the |
| 22 | // lifetimes of their respective copies of the FD. |
Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 23 | struct FileDescriptor { |
Eric Caruso | 75578a9 | 2018-03-29 11:33:59 -0700 | [diff] [blame^] | 24 | FileDescriptor() = default; |
| 25 | FileDescriptor(int fd) : fd(dup(fd)) {} |
| 26 | FileDescriptor(FileDescriptor&& other) : fd(std::move(other.fd)) {} |
Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 27 | |
| 28 | inline FileDescriptor& operator=(int new_fd) { |
Eric Caruso | 75578a9 | 2018-03-29 11:33:59 -0700 | [diff] [blame^] | 29 | fd.reset(dup(new_fd)); |
Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 30 | return *this; |
| 31 | } |
| 32 | |
Eric Caruso | 75578a9 | 2018-03-29 11:33:59 -0700 | [diff] [blame^] | 33 | FileDescriptor& operator=(FileDescriptor&& other) { |
| 34 | fd = std::move(other.fd); |
| 35 | return *this; |
| 36 | } |
| 37 | |
| 38 | int get() const { return fd.get(); } |
| 39 | |
| 40 | private: |
| 41 | DISALLOW_COPY_AND_ASSIGN(FileDescriptor); |
| 42 | |
| 43 | base::ScopedFD fd; |
Eric Caruso | 627d2c4 | 2018-03-08 14:46:35 -0800 | [diff] [blame] | 44 | }; |
| 45 | |
| 46 | } // namespace dbus_utils |
| 47 | } // namespace brillo |
| 48 | |
| 49 | #endif // LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_ |