0d1526abf57785c2ed3822d7bbb85db037bf11da
[folly.git] / folly / portability / Event.h
1 /*
2  * Copyright 2017 Facebook, Inc.
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 #pragma once
18
19 #include <event.h>
20
21 #ifdef _MSC_VER
22 # include <event2/event_compat.h>
23 # include <folly/portability/Fcntl.h>
24 # include <folly/portability/Windows.h>
25 #endif
26
27 namespace folly {
28 #ifdef _MSC_VER
29 using libevent_fd_t = evutil_socket_t;
30 #else
31 using libevent_fd_t = int;
32 #endif
33
34 inline libevent_fd_t getLibeventFd(int fd) {
35 #ifdef _MSC_VER
36   if (fd == -1) {
37     return (libevent_fd_t)INVALID_HANDLE_VALUE;
38   }
39   return _get_osfhandle(fd);
40 #else
41   return fd;
42 #endif
43 }
44
45 inline int libeventFdToFd(libevent_fd_t fd) {
46 #ifdef _MSC_VER
47   if (fd == (libevent_fd_t)INVALID_HANDLE_VALUE) {
48     return -1;
49   }
50   return _open_osfhandle((intptr_t)fd, O_RDWR | O_BINARY);
51 #else
52   return fd;
53 #endif
54 }
55
56 using EventSetCallback = void (*)(libevent_fd_t, short, void*);
57 inline void
58 folly_event_set(event* e, int fd, short s, EventSetCallback f, void* arg) {
59   auto lfd = getLibeventFd(fd);
60   event_set(e, lfd, s, f, arg);
61 }
62 }