2 ms·
How about eschewing the passing by value altogether? If someone wants to do that, they can memcpy() the array inside the function for no extra syntax. So, the
by loup-vaillant 8y ago
How about eschewing the passing by value altogether? If someone wants to do that, they can memcpy() the array inside the function for no extra syntax. So, the following would mean fat pointer:
int read(int fd, char buf[n], size_t n);
The following guarantees your array is not modified (but it's still passed by pointer).
int write(int fd, const char buf[n], size_t n);
The following emulates passing by value:
void foo(const int buf[n], size_t n) {
int tmp[n];
memcpy(buf, tmp, n);
}
Alternatively:
void foo(const int buf[n], size_t n) {
int tmp[n];
arrcpy(buf, tmp); // may or may not check bounds
}
Maybe this would render the proposition less useful, but it would already help. Here's for instance authenticated encryption from Monocypher, my crypto library:
void crypto_lock_aead(uint8_t mac[16],
uint8_t *cipher_text,
const uint8_t key[32],
const uint8_t nonce[24],
const uint8_t *ad,
size_t ad_size,
const uint8_t *plain_text,
size_t text_size);
It is not crystal clear that `text_size` is referring to the size of both the `plaintext` and the `cipher_text`. With something like your proposition, I could write this instead:
void crypto_lock_aead(uint8_t mac [16],
uint8_t cipher_text[text_size],
const uint8_t key [32],
const uint8_t nonce [24],
const uint8_t ad [ad_size],
size_t ad_size,
const uint8_t plain_text [text_size],
size_t text_size);
That way, the size of each buffer is crystal clear. Bonus: a sanitizer can check that I don't overflow my bounds (and I love sanitisers for stuff as sensitive as a crypto library).