blob: 2c4a01b456d5e060324c3116d7d784d5c9352781 [file] [log] [blame]
Eric Caruso627d2c42018-03-08 14:46:35 -08001// 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 Caruso75578a92018-03-29 11:33:59 -07008#include <base/files/scoped_file.h>
9#include <base/macros.h>
10
Eric Caruso627d2c42018-03-08 14:46:35 -080011namespace brillo {
12namespace 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 Caruso75578a92018-03-29 11:33:59 -070018//
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 Caruso627d2c42018-03-08 14:46:35 -080023struct FileDescriptor {
Eric Caruso75578a92018-03-29 11:33:59 -070024 FileDescriptor() = default;
25 FileDescriptor(int fd) : fd(dup(fd)) {}
26 FileDescriptor(FileDescriptor&& other) : fd(std::move(other.fd)) {}
Eric Caruso627d2c42018-03-08 14:46:35 -080027
28 inline FileDescriptor& operator=(int new_fd) {
Eric Caruso75578a92018-03-29 11:33:59 -070029 fd.reset(dup(new_fd));
Eric Caruso627d2c42018-03-08 14:46:35 -080030 return *this;
31 }
32
Eric Caruso75578a92018-03-29 11:33:59 -070033 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 Caruso627d2c42018-03-08 14:46:35 -080044};
45
46} // namespace dbus_utils
47} // namespace brillo
48
49#endif // LIBBRILLO_BRILLO_DBUS_FILE_DESCRIPTOR_H_