Last active
November 12, 2020 12:30
-
-
Save hrydgard/e7cd487cbb0ef36f8ab48762f93256c3 to your computer and use it in GitHub Desktop.
truncate_cpy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// .h file | |
// Similar to strncpy but with safe zero-termination behavior | |
// and doesn't fill extra space with zeroes. | |
// Returns true if the string fit without truncation. | |
// Always performs the copy though. | |
bool truncate_cpy(char *dest, size_t destSize, const char *src); | |
template<size_t Count> | |
inline bool truncate_cpy(char(&out)[Count], const char *src) { | |
return truncate_cpy(out, Count, src); | |
} | |
// .cpp file | |
bool truncate_cpy(char *dest, size_t destSize, const char *src) { | |
assert(destSize >= 1); | |
size_t len = strlen(src); | |
if (len >= destSize - 1) { | |
memcpy(dest, src, destSize - 1); | |
dest[destSize - 1] = '\0'; | |
return false; | |
} else { | |
memcpy(dest, src, len); | |
dest[len] = '\0'; | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment