1/*
2 * Copyright (c) 2023 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 UTILS_EVENT_HANDLER_H
17#define UTILS_EVENT_HANDLER_H
18
19#include "errors.h"
20#include "io_event_common.h"
21namespace OHOS {
22namespace Utils {
23
24class IOEventReactor;
25
26class IOEventHandler {
27public:
28    IOEventHandler();
29    explicit IOEventHandler(int fd, EventId events = Events::EVENT_NONE, const EventCallback& cb = nullptr);
30    IOEventHandler& operator=(const IOEventHandler&) = delete;
31    IOEventHandler(const IOEventHandler&) = delete;
32    IOEventHandler& operator=(const IOEventHandler&&) = delete;
33    IOEventHandler(const IOEventHandler&&) = delete;
34    virtual ~IOEventHandler();
35
36    bool Start(IOEventReactor* reactor);
37    bool Stop(IOEventReactor* reactor);
38    bool Update(IOEventReactor* reactor);
39
40    inline void SetFd(int fd)
41    {
42        fd_ = fd;
43    }
44
45    inline void SetEvents(EventId events)
46    {
47        events_ = events;
48    }
49
50    inline void SetCallback(const EventCallback& cb)
51    {
52        cb_ = cb;
53    }
54
55    inline int GetFd() const
56    {
57        return fd_;
58    }
59
60    inline EventId GetEvents() const
61    {
62        return events_;
63    }
64
65    inline EventCallback GetCallback() const
66    {
67        return cb_;
68    }
69
70    inline IOEventHandler* Prev() const
71    {
72        return prev_;
73    }
74
75    inline IOEventHandler* Next() const
76    {
77        return next_;
78    }
79
80    void EnableRead();
81    void EnableWrite();
82    void DisableWrite();
83    void DisableAll();
84
85    inline bool IsActive()
86    {
87        return (prev_ != nullptr && enabled_);
88    }
89private:
90    IOEventHandler* prev_;
91    IOEventHandler* next_;
92
93    int fd_;
94    EventId events_;
95    EventCallback cb_;
96    bool enabled_;
97
98    friend class IOEventReactor;
99};
100
101} // namespace Utils
102} // namespace OHOS
103#endif /* UTILS_EVENT_HANDLER_H_ */
104