shithub: lu9-p9

Download patch

ref: 021d5507d7a1fdf6d1d33ebaaa05d497dfae216e
parent: 5d34be6a2478a81cb196cc889a1d9a8dc09f581a
author: kvik <kvik@a-b.xyz>
date: Thu Apr 22 19:28:34 EDT 2021

common: improve memory allocation helpers

--- a/base/common.c
+++ b/base/common.c
@@ -24,7 +24,7 @@
 
 /* Memory allocator associated with Lua state */
 static void*
-lalloc(lua_State *L, void *ptr, usize sz)
+Lallocf(lua_State *L, void *ptr, usize sz)
 {
 	void *ud;
 	
@@ -32,10 +32,12 @@
 		lua_pushliteral(L, "out of memory");
 		lua_error(L);
 	}
-	memset(ptr, 0, sz);
 	setmalloctag(ptr, getcallerpc(&L));
 	return ptr;
 }
+#define Lrealloc(L, ptr, sz) Lallocf(L, ptr, sz);
+#define Lmalloc(L, sz) Lallocf(L, nil, sz)
+#define Lfree(L, ptr) Lallocf(L, nil, 0)
 
 /* 
  * Various functions in this library require a
@@ -57,7 +59,7 @@
 
 struct Buf {
 	usize sz;
-	char *b;
+	char b[1];
 };
 
 static Buf*
@@ -64,13 +66,11 @@
 resizebuffer(lua_State *L, Buf *buf, usize sz)
 {
 	if(buf == nil){
-		buf = lalloc(L, nil, sizeof(Buf));
-		buf->b = nil;
-		buf->sz = 0;
-	}
-	if(buf->sz < sz){
-		buf->b = lalloc(L, buf->b, sz);
+		buf = Lmalloc(L, sizeof(Buf) + sz);
 		buf->sz = sz;
+	}else if(buf->sz < sz){
+		Lfree(L, buf);
+		return resizebuffer(L, nil, sz);
 	}
 	return buf;
 }
--- a/base/proc.c
+++ b/base/proc.c
@@ -152,7 +152,7 @@
 	argc = lua_gettop(L);
 	if(argc < 1)
 		luaL_argerror(L, 1, "string arguments expected");
-	argv = lalloc(L, nil, (argc+1) * sizeof(char*));
+	argv = Lmalloc(L, (argc+1) * sizeof(char*));
 	for(i = 1; i <= argc; i++)
 		argv[i-1] = luaL_checkstring(L, i);
 	argv[argc] = nil;