3 ms·
In similar C-string trickery, consider this lovely bool-to-string function: /** @brief Construct a String equal to "true" or "false" depending on the
by azernik 6y ago
In similar C-string trickery, consider this lovely bool-to-string function:
/** @brief Construct a String equal to "true" or "false"
depending on the
value of @a x. */
inline String::String(bool x) {
// bool_data equals "false\0true\0"
assign_memo(bool_data + (-x & 6), 5 - x, 0);
}
Source: https://github.com/kohler/click/blob/6fa978f0188bd0b8a266f65cd0e79d81838b7963/include/click/string.hh#L388 https://github.com/kohler/click/blob/6fa978f0188bd0b8a266f65...
Context: This is the source code of the Click Modular Router, a system for implementing packet processing logic with a graph-like DSL. Both primitives, and certain complex logic, are implemented in C++; however, as this has to be able to run as a Linux kernel module or in userspace or as a BSD kernel module, it can't use the C++ standard library, and do has its own stdlib.
- zokier 6y ago> (-x & 6) wouldn't (x * 6) get the same result?
- azernik 6y ago* is an inherently more complicated action, and takes 3 cycles on x86 and from 3-5 cycles on ARM. & and - are stupid-simple and take 1 cycle, always. The real question is why this isn't done with ~. Possibly some weird embedded platform doesn't have an instruction for it? I doubt this string conversion code is ever on the hot path for packet processing, but Click is in general written like everything is.
- saagarjha 6y agoI don’t get why bool_data couldn’t be an array of two strings with x indexing into it…
- azernik 6y agoTwo pointer dereferences are slower than one - got to read from the top-level array, then use the pointer to read from the individual string. This way you can figure out the address of the string with about four very cheap instructions and zero memory accesses. Plus cache locality.