3 ms·
Something like this? https://godbolt.org/z/6nod5e https://godbolt.org/z/6nod5e. It even produces almost identical assembly. The equivalent to checked_mul is __
by lorenzhs 6y ago
Something like this? https://godbolt.org/z/6nod5e https://godbolt.org/z/6nod5e. It even produces almost identical assembly.
The equivalent to checked_mul is __builtin_mul_overflow, which is a compiler builtin:
https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.... Similarly, saturating_sub seems like it can be implemented with __builtin_sub_overflow.
- Measter 6y agoWould those work on any compiler, or are they compiler-specific? If those are non-standard compiler-specific extensions, not even a library, is it truly a part of C++? While I'll grant that Rust only has one fully functional compiler at this time, those functions have been part of Rust's corelib since 1.0. Any Rust compiler would have to support them.
- lorenzhs 6y agoThey're not part of the standard, but gcc, clang, and icc (Intel) support them. Alternatively, you could emit the correct instructions in an asm block on supported architectures (x86: 'jo'/'jno' for jumps, 'cmovo'/'cmovno' for conditional moves [1]) or reimplement the operations in software [2] [1] https://www.felixcloutier.com/x86/jcc https://www.felixcloutier.com/x86/jcc and https://www.felixcloutier.com/x86/cmovcc https://www.felixcloutier.com/x86/cmovcc [2] https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensure+that+operations+on+signed+integers+do+not+result+in+overflow https://wiki.sei.cmu.edu/confluence/display/c/INT32-C.+Ensur....