Open Vaxeral opened 6 months ago
The overflow is intended it's part of the hashing algorithm
Right and it will work almost always. There are cases where signed integer overflow being undefined behavior can cause confusion.
int foo(int x) {
return x+1>x;
}
The optimizer will take advantage of this fact and return 1 regardless of the value x + 1
which may overflow.
But more importantly direclty importing the c library into a zig code base is affected by this issue. Because zig is very strict about violating undefined behavior the example fails in debug builds. This can easily be fixed on zig side by using the overflow operator. Just thought I'd share.
While it technically this is undefined behavior because it is not an unsigned integer, realistically this library only utilizes well-defined behavior, specifically the "wrapping" rules for shifting, addition. subtraction, and multiplication. According to the spec regarding overflow of signed integers:
C99 6.2.6.2:2:
If the sign bit is one, the value shall be modified in one of the following ways: — the corresponding value with sign bit 0 is negated (sign and magnitude); — the sign bit has the value −(2N) (two’s complement); — the sign bit has the value −(2N − 1) (one’s complement).
So this means it is well-defined behavior for any processor that uses two's complement representation, simply not well-defined behavior per the "letter of the law" of the C-standard as a whole. In the real-world, this means all processors that this library would ever be used with. It would be a challenge to even find an an architecture that doesn't use two's complement, even in the realm of micro-controllers and embedded systems it would be exotic. Suffice it to say, this "undefined behavior" can safely be ignored/suppressed.
That said, I am in the final stages of a Zig implementation that I intend to contribute, and everything works as expected. There were no undefined behavior being utilized that could not be translated, only the additional verbosity of Zig in order to explicitly convey the intent of overflow, which is standard for any C-to-Zig port.
Hi. The library seems to have undefined behavior, specifically signed integer overflow.
include/FastNoiseLite.h:484:10: runtime error: signed integer overflow: 1337 * 668265261 cannot be represented in type 'int'
Is this intended, if so what is the reason?