1/*	$NetBSD$	*/
2
3/*
4** Id: lmem.c,v 1.70.1.1 2007/12/27 13:02:25 roberto Exp
5** Interface to Memory Manager
6** See Copyright Notice in lua.h
7*/
8
9
10#include <stddef.h>
11
12#define lmem_c
13#define LUA_CORE
14
15#include "lua.h"
16
17#include "ldebug.h"
18#include "ldo.h"
19#include "lmem.h"
20#include "lobject.h"
21#include "lstate.h"
22
23
24
25/*
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)
29**
30** Lua ensures that (ptr == NULL) iff (osize == 0).
31**
32** * frealloc(ud, NULL, 0, x) creates a new block of size `x'
33**
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)
38**
39** frealloc returns NULL if it cannot create or reallocate the area
40** (any reallocation to an equal or smaller size cannot fail!)
41*/
42
43
44
45#define MINSIZEARRAY	4
46
47
48void *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 */
56  }
57  else {
58    newsize = (*size)*2;
59    if (newsize < MINSIZEARRAY)
60      newsize = MINSIZEARRAY;  /* minimum size */
61  }
62  newblock = luaM_reallocv(L, block, *size, newsize, size_elems);
63  *size = newsize;  /* update only when everything else is OK */
64  return newblock;
65}
66
67
68void *luaM_toobig (lua_State *L) {
69  luaG_runerror(L, "memory allocation error: block too big");
70  return NULL;  /* to avoid warnings */
71}
72
73
74
75/*
76** generic allocation routine.
77*/
78void *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;
87}
88
89