3 ms·
In my view asserts are just a way of defining the contract of an interface that cannot be specified to the compiler/runtime any other way. They are a workaroun
by rkeene2 8y ago
In my view asserts are just a way of defining the contract of an interface that cannot be specified to the compiler/runtime any other way. They are a workaround of limitations of those systems, or rather the extend a system with infinite flexibility.
For example the NaCl "randombytes" function has the prototype:
void randombytes(unsigned char *buffer, unsigned long long length);
It has no way to report an error -- its contract is that it must fill the buffer with high quality random bytes before returning.
And the OpenBSD function "arc4random_buf" has the prototype:
void arc4random_buf(void *buf, size_t nbytes);
So we have a potential type difference between the two interfaces for the amount of data that we can generate.
If you wanted to back randombytes() by arc4random_buf() you have several options:
1. Handle the case within randombytes() where the (unsigned long long) value exceeds the maximum value of (size_t) by making repeated calls to arc4random_buf();
2. Assert, at compile time, that (size_t)'s range falls within (unsigned long long) and there can be no problem (since arc4random_buf() similarly cannot fail);
3. Redefine the contract of randombytes() such that specifying a buffer length that exceeds (size_t)'s maximum value is invalid -- this is really the same as #2 but instead of failing to compile if (SIZE_MAX < ULLONG_MAX) the program will compile and run fine as long as the contract is not violated; The assert in this case is a guard against the violation that should never occur and helps to enforce the contract during development
With regards to production use of assert, catching a contract violation there means a lot of things have gone wrong. How likely things are to go wrong and how much damage they do when they do go wrong can vary from contract to contract. Various asserts may be used based on the such things, from compile-time to run-time debug to run-time production to an inline debugging framework. There are trade-offs and no answer for all cases.