Skip to content
This repository has been archived by the owner on Oct 4, 2024. It is now read-only.

vector: fix support for odd-sized structures #21

Closed
wants to merge 1 commit into from
Closed

Conversation

rr-
Copy link
Contributor

@rr- rr- commented Aug 30, 2024

During implementing a fix for LostArtefacts/TRX#1463, I've discovered a problem with our design of the Vector module. Since the vector items are now implemented as void* pointers and we encourage a direct interaction with vector->items by the user, it turns out that the only effective item_size is that of a (void*) pointer.

I've changed the vector internals to use a linear byte buffer underneath and to require always passing values around through a pointer. This makes it a bit more cumbersome to use for primitive types:

VECTOR *const vec = Vector_Create(sizeof(int32_t));
-Vector_Add(vec, (void*)5);
+Vector_Add(vec, &(int32_t){5});

But the new version allows us to use the vector with structures:

typedef struct {
    int16_t a, b;
} COMPLEX;

int main(int argc, char **argv)
{
    VECTOR *v = Vector_Create(sizeof(COMPLEX));
    Vector_Add(v, &(COMPLEX){.a = 2, .b = 4});
    Vector_Add(v, &(COMPLEX){.a = 1, .b = 3});

    for (int32_t i = 0; i < v->count * v->item_size; i++) {
        printf("%02x ", (*(char**)v->priv)[i]);
    }
    printf("\n");

    COMPLEX a = *(COMPLEX*)Vector_Get(v, 0);
    COMPLEX b = *(COMPLEX*)Vector_Get(v, 1);
    printf("%d %d\n", a.a, a.b);
    printf("%d %d\n", b.a, b.b);
}

Output:

02 00 04 00 01 00 03 00
2 4
1 3

Fortunately we don't use it anywhere so there's no need to test for regressions.
I'm not sure about whether I've implemented every function correctly, though, and would appreciate additional verification – I did test them, but I'm just not confident I've covered every corner case.

@rr- rr- requested review from a team, lahm86 and walkawayy and removed request for a team August 30, 2024 08:43
Copy link
Contributor

@walkawayy walkawayy left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code looks good to me.

@rr-
Copy link
Contributor Author

rr- commented Aug 30, 2024

Merged manually in c89eb53.

@rr- rr- closed this Aug 30, 2024
@rr- rr- deleted the better-vector branch August 30, 2024 14:18
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants