|
| 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 | +#include <event2/event.h> |
| 6 | +#include <map> |
| 7 | +#include <stdlib.h> |
| 8 | + |
| 9 | +#include "support/events.h" |
| 10 | + |
| 11 | +#include "test/test_bitcoin.h" |
| 12 | + |
| 13 | +#include <vector> |
| 14 | + |
| 15 | +#include <boost/test/unit_test.hpp> |
| 16 | + |
| 17 | +static std::map<void*, short> tags; |
| 18 | +static std::map<void*, uint16_t> orders; |
| 19 | +static uint16_t tagSequence = 0; |
| 20 | + |
| 21 | +static void* tag_malloc(size_t sz) { |
| 22 | + void* mem = malloc(sz); |
| 23 | + if (!mem) return mem; |
| 24 | + tags[mem]++; |
| 25 | + orders[mem] = tagSequence++; |
| 26 | + return mem; |
| 27 | +} |
| 28 | + |
| 29 | +static void tag_free(void* mem) { |
| 30 | + tags[mem]--; |
| 31 | + orders[mem] = tagSequence++; |
| 32 | + free(mem); |
| 33 | +} |
| 34 | + |
| 35 | +BOOST_FIXTURE_TEST_SUITE(raii_event_tests, BasicTestingSetup) |
| 36 | + |
| 37 | +BOOST_AUTO_TEST_CASE(raii_event_creation) |
| 38 | +{ |
| 39 | + event_set_mem_functions(tag_malloc, realloc, tag_free); |
| 40 | + |
| 41 | + void* base_ptr = NULL; |
| 42 | + { |
| 43 | + auto base = obtain_event_base(); |
| 44 | + base_ptr = (void*)base.get(); |
| 45 | + BOOST_CHECK(tags[base_ptr] == 1); |
| 46 | + } |
| 47 | + BOOST_CHECK(tags[base_ptr] == 0); |
| 48 | + |
| 49 | + void* event_ptr = NULL; |
| 50 | + { |
| 51 | + auto base = obtain_event_base(); |
| 52 | + auto event = obtain_event(base.get(), -1, 0, NULL, NULL); |
| 53 | + |
| 54 | + base_ptr = (void*)base.get(); |
| 55 | + event_ptr = (void*)event.get(); |
| 56 | + |
| 57 | + BOOST_CHECK(tags[base_ptr] == 1); |
| 58 | + BOOST_CHECK(tags[event_ptr] == 1); |
| 59 | + } |
| 60 | + BOOST_CHECK(tags[base_ptr] == 0); |
| 61 | + BOOST_CHECK(tags[event_ptr] == 0); |
| 62 | + |
| 63 | + event_set_mem_functions(malloc, realloc, free); |
| 64 | +} |
| 65 | + |
| 66 | +BOOST_AUTO_TEST_CASE(raii_event_order) |
| 67 | +{ |
| 68 | + event_set_mem_functions(tag_malloc, realloc, tag_free); |
| 69 | + |
| 70 | + void* base_ptr = NULL; |
| 71 | + void* event_ptr = NULL; |
| 72 | + { |
| 73 | + auto base = obtain_event_base(); |
| 74 | + auto event = obtain_event(base.get(), -1, 0, NULL, NULL); |
| 75 | + |
| 76 | + base_ptr = (void*)base.get(); |
| 77 | + event_ptr = (void*)event.get(); |
| 78 | + |
| 79 | + // base should have allocated before event |
| 80 | + BOOST_CHECK(orders[base_ptr] < orders[event_ptr]); |
| 81 | + } |
| 82 | + // base should be freed after event |
| 83 | + BOOST_CHECK(orders[base_ptr] > orders[event_ptr]); |
| 84 | + |
| 85 | + event_set_mem_functions(malloc, realloc, free); |
| 86 | +} |
| 87 | + |
| 88 | +BOOST_AUTO_TEST_SUITE_END() |
0 commit comments