1/*
2 * Copyright (c) 2024 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 COMMUNICATIONNETSTACK_EPOLLER_H
17#define COMMUNICATIONNETSTACK_EPOLLER_H
18
19#include <sys/epoll.h>
20
21#include <string.h>
22#include <unistd.h>
23
24#include "file_descriptor.h"
25
26namespace OHOS::NetStack::HttpOverCurl {
27
28struct Epoller {
29    Epoller()
30    {
31        underlying_ = epoll_create1(EPOLL_CLOEXEC);
32    }
33
34    ~Epoller()
35    {
36        close(underlying_);
37    }
38
39    Epoller(const Epoller &) = delete;
40    Epoller(Epoller &&other) = default;
41
42    void RegisterMe(FileDescriptor descriptor) const
43    {
44        RegisterMe(descriptor, EPOLLIN);
45    }
46
47    void RegisterMe(FileDescriptor descriptor, uint32_t flags) const
48    {
49        epoll_event ev{};
50        ev.events = flags;
51        ev.data.fd = descriptor;
52        epoll_ctl(underlying_, EPOLL_CTL_ADD, descriptor, &ev);
53    }
54
55    void UnregisterMe(FileDescriptor descriptor) const
56    {
57        if (descriptor) {
58            epoll_ctl(underlying_, EPOLL_CTL_DEL, descriptor, nullptr);
59        }
60    }
61
62    int Wait(epoll_event *events, int maxEvents, int timeout) const
63    {
64        return epoll_wait(underlying_, events, maxEvents, timeout);
65    }
66
67private:
68    FileDescriptor underlying_;
69};
70
71} // namespace OHOS::NetStack::HttpOverCurl
72
73#endif // COMMUNICATIONNETSTACK_EPOLLER_H
74