ridiculousfish / libdivide

Official git repository for libdivide: optimized integer division
http://libdivide.com
Other
1.09k stars 77 forks source link

Improved error handling #38

Closed kimwalisch closed 6 years ago

kimwalisch commented 6 years ago

This pull request improves the error handling in libdivide.

Up until now we used assertions for error handling but this requires LIBDIVIDE_ASSERTIONS_ON to be defined by the user and most users don't do it. See e.g. https://github.com/ridiculousfish/libdivide/issues/23

Also, the new branchfree dividers have some tricky restrictions e.g. signed branchfree divider cannot be -1, 0, 1 and unsigned branchfree divider cannot be 0, 1.

For these reasons we need more serious error handling. I have implemented run-time checks for the dividers:

The run-time checks are not in the performance critical path i.e. they have been implemented in the divider generation functions. There shouldn't be any measurable performance impact of these run-time checks. If an error occurs an error message is printed and exit(-1) is called.

Here is an example program that shows how it works:

#include "libdivide.h"

int main()
{
    libdivide::branchfree_divider<uint64_t> div(1);
    return 0;
}

Now lets execute this program:

g++ -std=c++11 test.cpp -o test
./test
libdivide.h:1018: libdivide_u64_branchfree_gen(): Error: branchfree divider must be != 1