Manually allocated structs
Domingo Alvarez Duarte via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Jul 27 08:15:49 PDT 2014
Hello again !
Anyone knows how to compile with gdc for different versions I
could not find how gdc implements it if it does ?
The proposed usage of "@property char[] buf()" although seems to
work when compiled with dmd, segfaults when compiled with gdc:
----Code to test
import std.stdio;
import core.stdc.stdlib;
//version(c_style) {
struct lua_char_buffer_st0 {
size_t size, used;
char[1] buf;
};
//}
//version(d_style) {
struct lua_char_buffer_st2 {
size_t size, used;
@property char[] buf() {
return (_buf.ptr)[0 .. size];
}
private char[0] _buf;
};
//}
//alias lua_char_buffer_st = lua_char_buffer_st0;
alias lua_char_buffer_st = lua_char_buffer_st2;
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_realloc_char_buffer(lua_char_buffer_st
*old, size_t size){
lua_char_buffer_st *b = old;
size_t n = NEW_SIZE(size);
b = cast(lua_char_buffer_st*)realloc(old,
lua_char_buffer_st.sizeof + n);
if(b is null) return null;
b.size = n;
if(old is null) b.used = 0;
return b;
}
int lua_char_buffer_add_char(lua_char_buffer_st **b, char c){
lua_char_buffer_st *tmp = *b;
if(tmp.used+1 >= tmp.size){
tmp = lua_realloc_char_buffer(tmp, tmp.used+1);
if(tmp is null){
return 0;
}
*b = tmp;
}
//printf("lua_char_buffer_add_char %p : %p : %d : %d",
&tmp.buf, tmp.buf.ptr, tmp.size, tmp.used);
//fflush(stdout);
//version(c_style)
//*(&tmp.buf + tmp.used++) = c;
//version(d_style)
tmp.buf[tmp.used++] = c;
return 1;
}
void main()
{
lua_char_buffer_st *b = lua_realloc_char_buffer(null,
MIN_ALLOC_SIZE);
lua_char_buffer_add_char(&b, 'a');
free(b);
writeln("Hello !");
}
More information about the Digitalmars-d-learn
mailing list