Skip to content

Commit e5534d2

Browse files
committed
Added std::unique_ptr<> wrappers with deleters for libevent modules.
1 parent 7f72568 commit e5534d2

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed

src/Makefile.am

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,7 @@ BITCOIN_CORE_H = \
134134
support/allocators/secure.h \
135135
support/allocators/zeroafterfree.h \
136136
support/cleanse.h \
137+
support/events.h \
137138
support/lockedpool.h \
138139
sync.h \
139140
threadsafety.h \

src/support/events.h

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// Copyright (c) 2016 The Bitcoin Core developers
2+
// Distributed under the MIT software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#ifndef BITCOIN_SUPPORT_EVENTS_H
6+
#define BITCOIN_SUPPORT_EVENTS_H
7+
8+
#include <ios>
9+
10+
#include <event2/event.h>
11+
#include <event2/http.h>
12+
13+
#define MAKE_RAII(type) \
14+
/* deleter */\
15+
struct type##_deleter {\
16+
void operator()(struct type* ob) {\
17+
type##_free(ob);\
18+
}\
19+
};\
20+
/* unique ptr typedef */\
21+
typedef std::unique_ptr<struct type, type##_deleter> raii_##type
22+
23+
MAKE_RAII(event_base);
24+
MAKE_RAII(event);
25+
MAKE_RAII(evhttp);
26+
MAKE_RAII(evhttp_request);
27+
MAKE_RAII(evhttp_connection);
28+
29+
raii_event_base obtain_event_base() {
30+
auto result = raii_event_base(event_base_new());
31+
if (!result.get())
32+
throw std::runtime_error("cannot create event_base");
33+
return result;
34+
}
35+
36+
raii_event obtain_event(struct event_base* base, evutil_socket_t s, short events, event_callback_fn cb, void* arg) {
37+
return raii_event(event_new(base, s, events, cb, arg));
38+
}
39+
40+
raii_evhttp obtain_evhttp(struct event_base* base) {
41+
return raii_evhttp(evhttp_new(base));
42+
}
43+
44+
raii_evhttp_request obtain_evhttp_request(void(*cb)(struct evhttp_request *, void *), void *arg) {
45+
return raii_evhttp_request(evhttp_request_new(cb, arg));
46+
}
47+
48+
raii_evhttp_connection obtain_evhttp_connection_base(struct event_base* base, std::string host, uint16_t port) {
49+
auto result = raii_evhttp_connection(evhttp_connection_base_new(base, NULL, host.c_str(), port));
50+
if (!result.get())
51+
throw std::runtime_error("create connection failed");
52+
return result;
53+
}
54+
55+
#endif // BITCOIN_SUPPORT_EVENTS_H

0 commit comments

Comments
 (0)