1 /*
2  * Copyright (C) 2017 The Android Open Source Project
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 NETUTILS_FD_H
18 #define NETUTILS_FD_H
19 
20 #include <ostream>
21 
22 #include "netdutils/Status.h"
23 
24 namespace android {
25 namespace netdutils {
26 
27 // Strongly typed wrapper for file descriptors with value semantics.
28 // This class should typically hold unowned file descriptors.
29 class Fd {
30   public:
31     constexpr Fd() = default;
32 
Fd(int fd)33     constexpr Fd(int fd) : mFd(fd) {}
34 
get()35     int get() const { return mFd; }
36 
37     bool operator==(const Fd& other) const { return get() == other.get(); }
38     bool operator!=(const Fd& other) const { return get() != other.get(); }
39 
40   private:
41     int mFd = -1;
42 };
43 
44 // Return true if fd appears valid (non-negative)
isWellFormed(const Fd fd)45 inline bool isWellFormed(const Fd fd) {
46     return fd.get() >= 0;
47 }
48 
49 std::ostream& operator<<(std::ostream& os, const Fd& fd);
50 
51 }  // namespace netdutils
52 }  // namespace android
53 
54 #endif /* NETUTILS_FD_H */
55