Manually allocated structs

Domingo Alvarez Duarte via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Jul 27 05:34:47 PDT 2014


Hello !

I have the code bellow that I want to manually allocate to use in 
runtime code, because I declared the payload "buf[1]" the 
compiler complains about index out of bounds then I managed to do 
this "*(&tmp.buf + tmp.used++) = c;" instead of 
"tmp.buf[tmp.used++] = c;" as is done usually i "C" there is 
another easy way to achieve the same result in "D" (remember 
manual memory allocation) ?

Cheers !

--------Code

struct lua_char_buffer_st {
     size_t size, used;
     char buf[1];
};

private enum MIN_ALLOC_SIZE = 2048;
private size_t NEW_SIZE(size_t sz) {return 
(((sz/MIN_ALLOC_SIZE)+1)*MIN_ALLOC_SIZE);}

lua_char_buffer_st *lua_new_char_buffer(size_t size){
	lua_char_buffer_st *b;
	size_t n = NEW_SIZE(size);
	b = cast(lua_char_buffer_st*)malloc(lua_char_buffer_st.sizeof + 
n);
	if(b is null) return null;
	b.size = n;
	b.used = 0;
	return b;
}

int lua_char_buffer_add_char(ref LuaMatchState ms, 
lua_char_buffer_st **b, char c){
     lua_char_buffer_st *tmp = *b;
     if(tmp.used+1 >= tmp.size){
         size_t new_size = tmp.size+MIN_ALLOC_SIZE;
         tmp = cast(lua_char_buffer_st*)realloc(tmp, 
lua_char_buffer_st.sizeof + new_size);
         if(tmp is null){
             ms.error = "not enough memory when reallocating";
             return 0;
         }
         *b = tmp;
         tmp.size = new_size;
     }
     *(&tmp.buf + tmp.used++) = c;
     return 1;
}


int lua_char_buffer_add_str(ref LuaMatchState ms, 
lua_char_buffer_st **b, const(char) *str, ptrdiff_t len){
     lua_char_buffer_st *tmp = *b;
     if(len < 0) len = strlen(str);
     if(tmp.used+len >= tmp.size){
         size_t new_size = tmp.size + NEW_SIZE(len);
         tmp = cast(lua_char_buffer_st*)realloc(tmp, 
lua_char_buffer_st.sizeof + new_size);
         if(tmp is null){
             ms.error = "not enough memory when reallocating";
             return 0;
         }
         *b = tmp;
         tmp.size = new_size;
     }
     memcpy(&tmp.buf + tmp.used, str, len);
     tmp.used += len;
     return 1;
}


More information about the Digitalmars-d-learn mailing list