Cubitect / cubiomes

C library that mimics the Minecraft biome generation.
MIT License
556 stars 98 forks source link

Fix undefined wrapping behavior in rng.h (Zig compatibility) #119

Open DuncanRuns opened 1 month ago

DuncanRuns commented 1 month ago

Takes advantage of the defined wrapping addition/subtraction behavior of unsigned integers as opposed to leaving it undefined with regular ints. I don't think the casts should cost any performance if the compiler does its job but I could be wrong since I'm a bit of a low level noob.

This is important for automatically translating the header to other languages, notably Zig where behavior is strongly defined. Most functions are translated to definitions without implementation, and linking the library provides the implementation (which can be compiled without sanitization, so cubiomes compiles and works as intended for these functions and lets things wrap if they need). But since the implementation of nextInt is included in the header, Zig translates it to a form which has the regular addition and subtraction operators, which has overflow checks leading to a panic in rare cases where overflow happens. The changes in this PR successfully "trick" Zig into using the wrapping versions of the addition and subtraction operators since that is the defined behavior of unsigned integers in C.

DuncanRuns commented 1 month ago

Before the force push, it changed the variables bits, val, and m to be a uint32_t The force pushed code now just casts directly at the operations This makes the output assembly match much closer, notably now having the same length https://gist.github.com/DuncanRuns/908f4eee46975648d58150598bab689b