Accessors

18, May, 2018

Do all accsessors need to have costly bound checking like this:

T get(Array *a, unsigned int index) {
    assert(a);

    if (index < a->count) {
          return a->store[index];
    }

    return NOT_A_T;
}

If you can afford for only-power-of-twos array, the above code may be:

T get(Array *a, unsigned int index) {
    assert(a);
    assert(a->mask == a->count - 1);

    return a->store[index & a->mask];
}

If you go further and limit array size to powers of 256 you may:

T get(Array *a, unsigned char index) {
    assert(a);
    assert(0x100 == a->count);

    return a->store[index];
}

or

T get(Array *a, unsigned short index) {
    assert(a);
    assert(0x10000 == a->count);

    return a->store[index];
}