lmem.h 2.4 KB

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