我为C字符串编写了这个字符串复制例程.它应该表现得像strlcpy,即 - null如果size> 0则终止目标,并返回源字符串的长度.
但是,如果源指针或目标指针为空,我还希望函数失败,并以某种方式将此通知给调用者.但我想不出一个非常优雅的方式来做到这一点.现在我发送两个负值作为大小来表示源或目标指针指向null.因此我将返回类型从size_t更改为有符号整数,我对此接口不满意.什么是更好的界面?
#include <cstddef> // size_t
#include <cstdint> // 32 bit int
const std::int32_t SRC_NULL = -1;
const std::int32_t DST_NULL = -2;
std::int32_t CopyStringn (char *dest, const char *src, std::size_t size) {
const char* temp (src);
if (temp == NULL)
return SRC_NULL;
if (dest == NULL)
return DST_NULL;
while (*temp) {
if (size > 1) {
*dest++ = *temp;
--size;
}
++temp;
}
if (size)
*dest = '\0';
return static_cast<std::int32_t> (temp - src); // Length does not include null
}
Run Code Online (Sandbox Code Playgroud)