blob: 3ff1e4e216673c661b37f22131e9dc17ee8db2f5 [file] [log] [blame]
Rolf Badorekef2bf512019-08-20 11:17:15 +03001/*
2 Copyright (c) 2018-2019 Nokia.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15*/
16
17#ifndef SHAREDDATALAYER_FILEDESCRIPTOR_HPP_
18#define SHAREDDATALAYER_FILEDESCRIPTOR_HPP_
19
20#include <functional>
21
22namespace shareddatalayer
23{
24 class System;
25
26 /**
27 * @brief Wrapper for native file descriptor
28 *
29 * FileDescriptor provides a clever wrapper for native file descriptor and
30 * takes care of closing it in destructor.
31 */
32 class FileDescriptor
33 {
34 public:
35 /**
36 * Take ownership of the given native file descriptor.
37 *
38 * @param fd The native file descriptor to wrap.
39 */
40 explicit FileDescriptor(int fd) noexcept;
41
42 /**
43 * Take ownership of the given native file descriptor.
44 *
45 * @param fd The native file descriptor to wrap.
46 * @param system System instance to use.
47 */
48 FileDescriptor(System& system, int fd) noexcept;
49
50 /**
51 * Move ownership of the given fd.
52 *
53 * @param fd The file descriptor to move.
54 */
55 FileDescriptor(FileDescriptor&& fd) noexcept;
56
57 /**
58 * Move ownership of the given fd.
59 *
60 * @param fd The file descriptor to move.
61 */
62 FileDescriptor& operator = (FileDescriptor&& fd) noexcept;
63
64 /**
65 * Close the wrapped native file descriptor. If <i>at close</i> function
66 * is set, then it is called just before closing the file descriptor.
67 *
68 * @see atClose
69 */
70 ~FileDescriptor();
71
72 /**
73 * Get the wrapped native file descriptor.
74 *
75 * @return The wrapped native file descriptor.
76 */
77 operator int() const noexcept { return fd; }
78
79 /**
80 * Set function to be called just before closing the native file
81 * descriptor.
82 */
83 void atClose(std::function<void(int)>);
84
85 /**
86 * Close the native file descriptor.
87 */
88 void close();
89
90 FileDescriptor(const FileDescriptor&) = delete;
91 FileDescriptor& operator = (const FileDescriptor&) = delete;
92
93 private:
94 System* system;
95 int fd;
96 std::function<void(int)> atCloseCb;
97 };
98}
99
100#endif