1 /*
2  * Copyright (c) 2021 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef EVENT_FD_H
17 #define EVENT_FD_H
18 
19 #include "platform_specific.h"
20 
21 #if defined EVLOOP_TIMER_ONLY
22 using Handle = int;
23 static const int INVALID_HANDLE = -1;
24 #define IS_VALID_HANDLE(h) false
25 #define CLOSE_HANDLE(h)
26 #else
27 #include <unistd.h>
28 using Handle = int;
29 static const int INVALID_HANDLE = -1;
30 #define IS_VALID_HANDLE(h) ((h) > 0)
31 #define CLOSE_HANDLE(h) do { close(h); } while (0)
32 #endif
33 
34 namespace DistributedDB {
35 class EventFd final {
36 public:
EventFd()37     EventFd() : fd_(INVALID_HANDLE) {}
EventFd(Handle handle)38     explicit EventFd(Handle handle) : fd_(handle) {}
39 
~EventFd()40     ~EventFd()
41     {
42         // we can't close it.
43         fd_ = INVALID_HANDLE;
44     }
45 
IsValid()46     bool IsValid() const
47     {
48         return IS_VALID_HANDLE(fd_);
49     }
50 
Handle()51     operator Handle() const
52     {
53         return fd_;
54     }
55 
56     bool operator==(const EventFd &other) const
57     {
58         return other.fd_ == fd_;
59     }
60 
Close()61     void Close()
62     {
63         if (IsValid()) {
64             CLOSE_HANDLE(fd_);
65             fd_ = INVALID_HANDLE;
66         }
67     }
68 
69 private:
70     Handle fd_;
71 };
72 }
73 
74 #endif // EVENT_FD_H
75