• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <base/files/scoped_file.h>
9 #include <base/macros.h>
10 
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.
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.
23 struct FileDescriptor {
24   FileDescriptor() = default;
FileDescriptorFileDescriptor25   FileDescriptor(int fd) : fd(dup(fd)) {}
FileDescriptorFileDescriptor26   FileDescriptor(FileDescriptor&& other) : fd(std::move(other.fd)) {}
FileDescriptorFileDescriptor27   FileDescriptor(base::ScopedFD&& other) : fd(std::move(other)) {}
28 
29   inline FileDescriptor& operator=(int new_fd) {
30     fd.reset(dup(new_fd));
31     return *this;
32   }
33 
34   FileDescriptor& operator=(FileDescriptor&& other) {
35     fd = std::move(other.fd);
36     return *this;
37   }
38 
39   FileDescriptor& operator=(base::ScopedFD&& other) {
40     fd = std::move(other);
41     return *this;
42   }
43 
releaseFileDescriptor44   int release() { return fd.release(); }
45 
getFileDescriptor46   int get() const { return fd.get(); }
47 
48  private:
49   DISALLOW_COPY_AND_ASSIGN(FileDescriptor);
50 
51   base::ScopedFD fd;
52 };
53 
54 }  // namespace dbus_utils
55 }  // namespace brillo
56 
57 #endif  // LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_
58