xref: /minix/external/mit/lua/dist/src/lmem.h (revision 0a6a1f1d)
1 /*	$NetBSD: lmem.h,v 1.3 2015/02/02 14:03:05 lneto Exp $	*/
2 
3 /*
4 ** Id: lmem.h,v 1.43 2014/12/19 17:26:14 roberto Exp
5 ** Interface to Memory Manager
6 ** See Copyright Notice in lua.h
7 */
8 
9 #ifndef lmem_h
10 #define lmem_h
11 
12 
13 #ifndef _KERNEL
14 #include <stddef.h>
15 #endif
16 
17 #include "llimits.h"
18 #include "lua.h"
19 
20 
21 /*
22 ** This macro reallocs a vector 'b' from 'on' to 'n' elements, where
23 ** each element has size 'e'. In case of arithmetic overflow of the
24 ** product 'n'*'e', it raises an error (calling 'luaM_toobig'). Because
25 ** 'e' is always constant, it avoids the runtime division MAX_SIZET/(e).
26 **
27 ** (The macro is somewhat complex to avoid warnings:  The 'sizeof'
28 ** comparison avoids a runtime comparison when overflow cannot occur.
29 ** The compiler should be able to optimize the real test by itself, but
30 ** when it does it, it may give a warning about "comparison is always
31 ** false due to limited range of data type"; the +1 tricks the compiler,
32 ** avoiding this warning but also this optimization.)
33 */
34 #define luaM_reallocv(L,b,on,n,e) \
35   (((sizeof(n) >= sizeof(size_t) && cast(size_t, (n)) + 1 > MAX_SIZET/(e)) \
36       ? luaM_toobig(L) : cast_void(0)) , \
37    luaM_realloc_(L, (b), (on)*(e), (n)*(e)))
38 
39 /*
40 ** Arrays of chars do not need any test
41 */
42 #define luaM_reallocvchar(L,b,on,n)  \
43     cast(char *, luaM_realloc_(L, (b), (on)*sizeof(char), (n)*sizeof(char)))
44 
45 #define luaM_freemem(L, b, s)	luaM_realloc_(L, (b), (s), 0)
46 #define luaM_free(L, b)		luaM_realloc_(L, (b), sizeof(*(b)), 0)
47 #define luaM_freearray(L, b, n)   luaM_realloc_(L, (b), (n)*sizeof(*(b)), 0)
48 
49 #define luaM_malloc(L,s)	luaM_realloc_(L, NULL, 0, (s))
50 #define luaM_new(L,t)		cast(t *, luaM_malloc(L, sizeof(t)))
51 #define luaM_newvector(L,n,t) \
52 		cast(t *, luaM_reallocv(L, NULL, 0, n, sizeof(t)))
53 
54 #define luaM_newobject(L,tag,s)	luaM_realloc_(L, NULL, tag, (s))
55 
56 #define luaM_growvector(L,v,nelems,size,t,limit,e) \
57           if ((nelems)+1 > (size)) \
58             ((v)=cast(t *, luaM_growaux_(L,v,&(size),sizeof(t),limit,e)))
59 
60 #define luaM_reallocvector(L, v,oldn,n,t) \
61    ((v)=cast(t *, luaM_reallocv(L, v, oldn, n, sizeof(t))))
62 
63 LUAI_FUNC l_noret luaM_toobig (lua_State *L);
64 
65 /* not to be called directly */
66 LUAI_FUNC void *luaM_realloc_ (lua_State *L, void *block, size_t oldsize,
67                                                           size_t size);
68 LUAI_FUNC void *luaM_growaux_ (lua_State *L, void *block, int *size,
69                                size_t size_elem, int limit,
70                                const char *what);
71 
72 #endif
73 
74