xref: /openbmc/gpioplus/src/gpioplus/internal/fd.hpp (revision 7ba248ad685c8a2029f9cfdbae98d161e9664a3b)
1 #pragma once
2 #include <gpioplus/internal/sys.hpp>
3 
4 #include <type_traits>
5 
6 namespace gpioplus
7 {
8 namespace internal
9 {
10 
11 /** @class Fd
12  *  @brief Holds references to file descriptors
13  *  @details Provides RAII semantics for file descriptors
14  */
15 class Fd
16 {
17   public:
18     /** @brief Opens a file and holds the file descriptor
19      *
20      *  @param[in] pathname - The path to the file being opened
21      *  @param[in] flags    - Flags passed to open(2)
22      *  @param[in] sys      - Optional underlying syscall implementation
23      *  @throws std::system_error for underlying syscall failures
24      */
25     Fd(const char* pathname, int flags, const Sys* sys);
26 
27     /** @brief Duplicates and holds a file descriptor
28      *        Does not automatically close the input descriptor
29      *
30      *  @param[in] fd  - File descriptor being duplicated
31      *  @param[in] sys - Optional underlying syscall implementation
32      *  @throws std::system_error for underlying syscall failures
33      */
34     Fd(int fd, const Sys* sys);
35 
36     /** @brief Holds the input file descriptor
37      *        Becomes the sole owner of the file descriptor
38      *
39      *  @param[in] fd  - File descriptor being duplicated
40      *  @param[in]     - Denotes that the fd is directly used
41      *  @param[in] sys - Optional underlying syscall implementation
42      */
43     Fd(int fd, std::false_type, const Sys* sys);
44 
45     virtual ~Fd();
46     Fd(const Fd& other);
47     Fd& operator=(const Fd& other);
48     Fd(Fd&& other);
49     Fd& operator=(Fd&& other);
50 
51     /** @brief Gets the managed file descriptor
52      *
53      *  @return The file descriptor
54      */
55     int operator*() const;
56 
57     /** @brief Gets the syscall interface implementation
58      *
59      *  @return The syscall implementation
60      */
61     const Sys* getSys() const;
62 
63     void setBlocking(bool enabled) const;
64 
65   private:
66     const Sys* sys;
67     int fd;
68 
69     /** @brief Sets flags on the file descriptor
70      *
71      *  @param[in] flags - The flags to set
72      *  @throws std::system_error for underlying syscall failures
73      */
74     void setFlags(int flags) const;
75 
76     /** @brief Gets the flags from the file descriptor
77      *
78      *  @throws std::system_error for underlying syscall failures
79      *  @return The file descriptor flags
80      */
81     int getFlags() const;
82 
83     /** @brief Cleans up the held file descriptor
84      *
85      *  @throws std::system_error for underlying syscall failures
86      */
87     void reset();
88 };
89 
90 } // namespace internal
91 } // namespace gpioplus
92