I have created a structure that is a actually an array that
allocates memory and growths. It is a template and it has worked
with a couple of types that I have tried with. It doesn't work
with one tho and I cannot understand why. I will list the
smallest possible code I could. Keep in mind that it is a couple
of code. For anyone that wants to read it, keep in mind that I
have to make this code work with LDC and using "-betterC".
// Filename: "test_file"
```aneluhaein```
// Filename: "my_file.d"
```d
import vec;
struct My_File {
char tok;
const char* contents;
ulong size, ln, cn, pos, identation;
ref My_File opAssign(ref const My_File s) return { return this;
}
// Copy constructor
this(ref return scope My_File rhs) {
this.tok = rhs.tok;
this.contents = rhs.contents;
this.ln = rhs.ln;
this.cn = rhs.cn;
this.pos = rhs.pos;
this.identation = rhs.identation;
}
debug {
void print() {
printf("
this.tok = %c
this.contents = \n\n`\n%s`
this.ln = %lu
this.cn = %lu
this.pos = %lu
this.identation = %lu",
this.tok,
this.contents,
this.ln,
this.cn,
this.pos,
this.identation,
);
}
}
}
```
// Filename: "vec.d"
```d
public import core.stdc.stdlib;
public import core.stdc.stdio;
public import core.sys.posix.fcntl;
public import core.sys.linux.sys.mman;
public enum DEF_VEC_REALLOC_SIZE = 3;
public enum DEF_VEC_ALLOC_SIZE = 3;
void exit_prog(int code) {
exit(0);
}
struct Vector(T) {
T* ptr; // The pointer to the data
ulong capacity; // Total amount of objects we can store
ulong length; // The amount of the objects we have stored
this(ulong capacity) { // Only used to create the vector that
will hold the files
this.length = 0;
this.capacity = capacity;
this.ptr = cast(T*)malloc(T.sizeof * capacity);
if (!this.ptr) { // Allocation error check
fprintf(stderr, "Error: Could not allocate memory for the
*%s object! Exiting...\n",
cast(char*)(T).stringof);
exit_prog(1);
}
}
void add(T element) {
if (this.capacity > this.length) {
this.ptr[this.length++] = element;
}
else {
this.capacity += DEF_VEC_REALLOC_SIZE;
realloc(this.ptr, T.sizeof * DEF_VEC_REALLOC_SIZE);
if (!this.ptr) { // Re-allocation error check
fprintf(stderr, "Error: Could not allocate more memory
for the *%s object! Exiting...",
cast(char*)(T).stringof);
exit_prog(1);
}
}
}
void inc() {
this.ptr++;
this.length--;
}
}
```
// Filename: "main.d"
```d
import core.stdc.stdlib;
import core.stdc.stdio;
import my_file;
import vec;
extern (C) void main() {
auto modules = Vector!(My_File)(DEF_VEC_ALLOC_SIZE);
const char* filename = "/tmp/test_file";
int fd = open(filename, O_RDWR);
ulong file_size = 24;
const char* contents = cast(char*)mmap(null,
file_size, PROT_READ, MAP_PRIVATE, fd, 0
);
My_File file = {
'T',
contents,
file_size,
1, 2, 3, 4
};
debug printf("\n\nBEFORE ADDING IT TO THE MODULE\n");
file.print();
modules.add(file);
debug printf("\n\n\nAFTER ADDING IT TO THE MODULE\n");
modules.ptr.print();
puts("");
exit(0);
}
```