Botan: src/engine/gnump/gmp_mem.cpp Source File

Botan 1.10.17

gmp_mem.cpp
Go to the documentation of this file.
1 /*
2 * GNU MP Memory Handlers
3 * (C) 1999-2010 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7
8 #include <botan/internal/gnump_engine.h>
9 #include <cstring>
10 #include <gmp.h>
11
12 namespace Botan {
13
14 namespace {
15
16 /*
17 * Allocator used by GNU MP
18 */
19 Allocator* gmp_alloc = 0;
20 size_t gmp_alloc_refcnt = 0;
21
22 /*
23 * Allocation Function for GNU MP
24 */
25 void* gmp_malloc(size_t n)
26 {
27 return gmp_alloc->allocate(n);
28 }
29
30 /*
31 * Reallocation Function for GNU MP
32 */
33 void* gmp_realloc(void* ptr, size_t old_n, size_t new_n)
34 {
35 void* new_buf = gmp_alloc->allocate(new_n);
36 std::memcpy(new_buf, ptr, std::min(old_n, new_n));
37 gmp_alloc->deallocate(ptr, old_n);
38 return new_buf;
39 }
40
41 /*
42 * Deallocation Function for GNU MP
43 */
44 void gmp_free(void* ptr, size_t n)
45 {
46 gmp_alloc->deallocate(ptr, n);
47 }
48
49 }
50
51 /*
52 * GMP_Engine Constructor
53 */
54 GMP_Engine::GMP_Engine()
55 {
56 if(gmp_alloc == 0)
57 {
58 gmp_alloc = Allocator::get(true);
59 mp_set_memory_functions(gmp_malloc, gmp_realloc, gmp_free);
60 }
61
62 ++gmp_alloc_refcnt;
63 }
64
65 GMP_Engine::~GMP_Engine()
66 {
67 --gmp_alloc_refcnt;
68
69 if(gmp_alloc_refcnt == 0)
70 {
71 mp_set_memory_functions(NULL, NULL, NULL);
72 gmp_alloc = 0;
73 }
74 }
75
76 }
Botan::GMP_Engine::GMP_Engine
GMP_Engine()
Definition: gmp_mem.cpp:54
Botan::Allocator::get
static Allocator * get(bool locking)
Definition: defalloc.cpp:90
Botan
Definition: algo_base.h:14
Botan::GMP_Engine::~GMP_Engine
~GMP_Engine()
Definition: gmp_mem.cpp:65
Botan::CT::min
T min(T a, T b)
Definition: ct_utils.h:127