1 | // |
2 | // immer: immutable data structures for C++ |
3 | // Copyright (C) 2016, 2017, 2018 Juan Pedro Bolivar Puente |
4 | // |
5 | // This software is distributed under the Boost Software License, Version 1.0. |
6 | // See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt |
7 | // |
8 | |
9 | #pragma once |
10 | |
11 | #include <immer/config.hpp> |
12 | |
13 | #include <memory> |
14 | #include <cstdlib> |
15 | |
16 | namespace immer { |
17 | |
18 | /*! |
19 | * A heap that uses `std::malloc` and `std::free` to manage memory. |
20 | */ |
21 | struct malloc_heap |
22 | { |
23 | /*! |
24 | * Returns a pointer to a memory region of size `size`, if the |
25 | * allocation was successful and throws `std::bad_alloc` otherwise. |
26 | */ |
27 | template <typename... Tags> |
28 | static void* allocate(std::size_t size, Tags...) |
29 | { |
30 | auto p = std::malloc(size); |
31 | if (IMMER_UNLIKELY(!p)) |
32 | throw std::bad_alloc{}; |
33 | return p; |
34 | } |
35 | |
36 | /*! |
37 | * Releases a memory region `data` that was previously returned by |
38 | * `allocate`. One must not use nor deallocate again a memory |
39 | * region that once it has been deallocated. |
40 | */ |
41 | static void deallocate(std::size_t, void* data) |
42 | { |
43 | std::free(data); |
44 | } |
45 | }; |
46 | |
47 | } // namespace immer |
48 | |