1 /*
2  * Copyright (c) 2009-2016 Petri Lehtinen <petri@digip.org>
3  * Copyright (c) 2011-2012 Basile Starynkevitch <basile@starynkevitch.net>
4  *
5  * Jansson is free software; you can redistribute it and/or modify it
6  * under the terms of the MIT license. See LICENSE for details.
7  */
8 /**
9  * License: MIT
10  */
11 module jansson_d.memory;
12 
13 
14 package:
15 
16 private static import core.stdc.stdlib;
17 private static import core.stdc.string;
18 private static import jansson_d.jansson;
19 
20 /* memory function pointers */
21 //private
22 __gshared jansson_d.jansson.json_malloc_t do_malloc = &core.stdc.stdlib.malloc;
23 
24 //private
25 __gshared jansson_d.jansson.json_free_t do_free = &core.stdc.stdlib.free;
26 
27 nothrow @trusted @nogc //ToDo: @nodiscard
28 package void* jsonp_malloc(size_t size)
29 
30 	do
31 	{
32 		if (size == 0) {
33 			return null;
34 		}
35 
36 		return .do_malloc(size);
37 	}
38 
39 nothrow @trusted @nogc
40 package void jsonp_free(scope void* ptr_)
41 
42 	do
43 	{
44 		if (ptr_ == null) {
45 			return;
46 		}
47 
48 		.do_free(ptr_);
49 	}
50 
51 nothrow @trusted @nogc //ToDo: @nodiscard
52 char* jsonp_strdup(scope const char* str)
53 
54 	do
55 	{
56 		return .jsonp_strndup(str, core.stdc..string.strlen(str));
57 	}
58 
59 nothrow @trusted @nogc //ToDo: @nodiscard
60 char* jsonp_strndup(scope const char* str, size_t len)
61 
62 	do
63 	{
64 		char* new_str = cast(char*)(.jsonp_malloc(len + 1));
65 
66 		if (new_str == null) {
67 			return null;
68 		}
69 
70 		core.stdc..string.memcpy(new_str, str, len);
71 		new_str[len] = '\0';
72 
73 		return new_str;
74 	}
75 
76 ///
77 extern (C)
78 nothrow @trusted @nogc @live
79 public void json_set_alloc_funcs(jansson_d.jansson.json_malloc_t malloc_fn, jansson_d.jansson.json_free_t free_fn)
80 
81 	do
82 	{
83 		.do_malloc = malloc_fn;
84 		.do_free = free_fn;
85 	}
86 
87 ///
88 extern (C)
89 nothrow @trusted @nogc @live
90 public void json_get_alloc_funcs(jansson_d.jansson.json_malloc_t* malloc_fn, jansson_d.jansson.json_free_t* free_fn)
91 
92 	do
93 	{
94 		if (malloc_fn != null) {
95 			*malloc_fn = .do_malloc;
96 		}
97 
98 		if (free_fn != null) {
99 			*free_fn = .do_free;
100 		}
101 	}