I have this function to fill a buffer with a repeating pattern of N bytes.
void* memsetPattern(void* buf, size_t bufSize, const void* Pattern, size_t PatternSize) {
if (buf == nullptr || Pattern == nullptr || PatternSize == 0) { return nullptr; }
if (bufSize == 0) { return buf; } // 0 Bytes to copy
if (PatternSize == 1) {
memset(buf, ((uint8_t*)Pattern)[0], bufSize);
return buf;
}
/* otherwise, if PatternSize >= 2 */
}
If the PatternSize is 1 byte, the function will instead run memset(buf, ((uint8_t*)Pattern)[0], bufSize)
, since memset runs slightly faster than my function.
If the user wanted to call memsetPattern(buf, bufSize, Pattern, 1)
, would it be possible to directly call (Pattern != nullptr && buf != nullptr) ? memset(buf, ((uint8_t*)Pattern)[0], bufSize) : nullptr
since PatternSize would be known to equal 1 byte at compile time?
I suppose one way to do it is with Macros, but it just feels wrong.
#define memsetPattern_Macro(buf, bufSize, Pattern, PatternSize)
(PatternSize == 1) ? (
(Pattern != nullptr && buf != nullptr) ? memset(buf, ((uint8_t*)Pattern)[0], bufSize) : nullptr
) : memsetPattern(buf, bufSize, Pattern, PatternSize)
Looking around, I did find if constexpr ()
, but it gives an error if I try if constexpr (PatternSize == 1) {
.
How should I go about switching the function based on parameters that are known at compile time? Would I need to change the types of arguments that are passed into the memsetPattern() function?