/src/connectedhomeip/src/lib/support/FileDescriptor.h
Line | Count | Source |
1 | | /* |
2 | | * |
3 | | * Copyright (c) 2024 Project CHIP Authors |
4 | | * |
5 | | * Licensed under the Apache License, Version 2.0 (the "License"); |
6 | | * you may not use this file except in compliance with the License. |
7 | | * You may obtain a copy of the License at |
8 | | * |
9 | | * http://www.apache.org/licenses/LICENSE-2.0 |
10 | | * |
11 | | * Unless required by applicable law or agreed to in writing, software |
12 | | * distributed under the License is distributed on an "AS IS" BASIS, |
13 | | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
14 | | * See the License for the specific language governing permissions and |
15 | | * limitations under the License. |
16 | | */ |
17 | | |
18 | | #pragma once |
19 | | |
20 | | #include <unistd.h> |
21 | | #include <utility> |
22 | | |
23 | | namespace chip { |
24 | | |
25 | | /// Unix file descriptor wrapper with RAII semantics. |
26 | | class FileDescriptor |
27 | | { |
28 | | public: |
29 | 0 | FileDescriptor() = default; |
30 | 0 | explicit FileDescriptor(int fd) : mFd(fd) {} |
31 | 0 | ~FileDescriptor() { Close(); } |
32 | | |
33 | | /// Disallow copy and assignment. |
34 | | FileDescriptor(const FileDescriptor &) = delete; |
35 | | FileDescriptor & operator=(const FileDescriptor &) = delete; |
36 | | |
37 | 0 | FileDescriptor(FileDescriptor && other) noexcept : mFd(other.Release()) {} |
38 | | FileDescriptor & operator=(FileDescriptor && other) noexcept |
39 | 0 | { |
40 | 0 | Close(); |
41 | 0 | mFd = other.Release(); |
42 | 0 | return *this; |
43 | 0 | } |
44 | | |
45 | 0 | int Get() const { return mFd; } |
46 | | |
47 | 0 | int Release() { return std::exchange(mFd, -1); } |
48 | | |
49 | | int Close() |
50 | 0 | { |
51 | 0 | if (mFd != -1) |
52 | 0 | { |
53 | 0 | return close(std::exchange(mFd, -1)); |
54 | 0 | } |
55 | 0 | return 0; |
56 | 0 | } |
57 | | |
58 | | private: |
59 | | int mFd = -1; |
60 | | }; |
61 | | |
62 | | } // namespace chip |