summaryrefslogtreecommitdiff
path: root/tests/test_memory.cpp
blob: 8f2d41b593f683772d14374cf883a002330e64d6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include "common.hpp"

namespace
{
	char buffer[8];
	int allocate_count = 0;
	int deallocate_count = 0;

	void* allocate(size_t size)
	{
		CHECK(size == 8);
		++allocate_count;
		return buffer;
	}

	void deallocate(void* ptr)
	{
		CHECK(ptr == buffer);
		++deallocate_count;
	}
}

TEST(custom_memory_management)
{
	// remember old functions
	allocation_function old_allocate = get_memory_allocation_function();
	deallocation_function old_deallocate = get_memory_deallocation_function();

	// replace functions
	set_memory_management_functions(allocate, deallocate);

	try
	{
		{
			// parse document
			xml_document doc;
			CHECK(doc.load("<node/>"));
	
			CHECK(allocate_count == 1);
			CHECK(deallocate_count == 0);
			CHECK_STRING(buffer, "<node\0>");

			// modify document
			doc.child("node").set_name("foobars");

			CHECK(allocate_count == 2);
			CHECK(deallocate_count == 0);
			CHECK_STRING(buffer, "foobars");
		}

		CHECK(allocate_count == 2);
		CHECK(deallocate_count == 2);
		CHECK_STRING(buffer, "foobars");

		// restore old functions
		set_memory_management_functions(old_allocate, old_deallocate);
	}
	catch (const char* error)
	{
		// restore old functions
		set_memory_management_functions(old_allocate, old_deallocate);

		// rethrow
		throw error;
	}
}