release.sh changes & fixes
[minix3.git] / external / mit / lua / dist / src / lmem.c
blob5d1cfc71d86f95df0715a3c0134f467d813aee2a
1 /* $NetBSD: lmem.c,v 1.1.1.2 2012/03/15 00:08:07 alnsn Exp $ */
3 /*
4 ** $Id: lmem.c,v 1.1.1.2 2012/03/15 00:08:07 alnsn Exp $
5 ** Interface to Memory Manager
6 ** See Copyright Notice in lua.h
7 */
10 #include <stddef.h>
12 #define lmem_c
13 #define LUA_CORE
15 #include "lua.h"
17 #include "ldebug.h"
18 #include "ldo.h"
19 #include "lmem.h"
20 #include "lobject.h"
21 #include "lstate.h"
26 ** About the realloc function:
27 ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
28 ** (`osize' is the old size, `nsize' is the new size)
30 ** Lua ensures that (ptr == NULL) iff (osize == 0).
32 ** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
34 ** * frealloc(ud, p, x, 0) frees the block `p'
35 ** (in this specific case, frealloc must return NULL).
36 ** particularly, frealloc(ud, NULL, 0, 0) does nothing
37 ** (which is equivalent to free(NULL) in ANSI C)
39 ** frealloc returns NULL if it cannot create or reallocate the area
40 ** (any reallocation to an equal or smaller size cannot fail!)
45 #define MINSIZEARRAY 4
48 void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
49 int limit, const char *errormsg) {
50 void *newblock;
51 int newsize;
52 if (*size >= limit/2) { /* cannot double it? */
53 if (*size >= limit) /* cannot grow even a little? */
54 luaG_runerror(L, errormsg);
55 newsize = limit; /* still have at least one free place */
57 else {
58 newsize = (*size)*2;
59 if (newsize < MINSIZEARRAY)
60 newsize = MINSIZEARRAY; /* minimum size */
62 newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
63 *size = newsize; /* update only when everything else is OK */
64 return newblock;
68 void *luaM_toobig (lua_State *L) {
69 luaG_runerror(L, "memory allocation error: block too big");
70 return NULL; /* to avoid warnings */
76 ** generic allocation routine.
78 void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
79 global_State *g = G(L);
80 lua_assert((osize == 0) == (block == NULL));
81 block = (*g->frealloc)(g->ud, block, osize, nsize);
82 if (block == NULL && nsize > 0)
83 luaD_throw(L, LUA_ERRMEM);
84 lua_assert((nsize == 0) == (block == NULL));
85 g->totalbytes = (g->totalbytes - osize) + nsize;
86 return block;