[Vala] Some thoughts about multidimensional arrays



Hi,

I wrote some code using multidimensional arrays yesterday and realized
it is not .... perfect, especially if you use strings.

Every array uses an additional _length and and _size gint. size is the
allocated size, length the actual use fields. Because every array uses
such data, why not pack them into a struct? Let's call it
ArrayDim[ension]:

typedef ArrayDim struct ArrayDim;
struct ArrayDim {
    gint length;
    gint size;
}

This is enugh for 1 dimensional arrays, but what about multidimensional
ones? I suggest to add an addional field for the next dimension so you
can chain up to arbitary array sizes. :

typedef MultiArrayDim struct MultiArrayDim;
struct MultiArrayDim {
    ArrayDim dim;
    ArrayDim[] next;
}

In the last dimenstion you'll only need a normal ArrayDim, else you have
to use a MultiArrayDim to have the metadata for the next dimension.

Last but not least an short example:

vala code:
//1
int[][] foo = null;
//2
foo = new int[][2];
//3
foo[0] = new int[2];
//4
foo[1] = new int[6];

C code:
//1
gint** foo = NULL;
MultiArrayDim foo_meta = { 0, 0, NULL };
//2
foo = g_new0( gint*, 2 + 1 );
foo_meta.size = 2;
foo_meta.next = g_new0( ArrayDim, 2 );
//3
foo[0] = g_new0( gint, 2 + 1 );
foo_meta.next[0].size = 2 + 1;
//4
foo[1] = g_new0( gint, 6 + 1 );
foo_meta.next[1].size = 6 + 1;

this even makes it possible to check the array ranges on accessing the
elements and maybe resizing.

Comments welcome.

Regards,
        Frederik

-- 
IRC: playya @ Freenode, Gimpnet
xmpp: playya draugr de

Attachment: signature.asc
Description: Digital signature



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]