Skip to content

Instantly share code, notes, and snippets.

@rudolfovich
Last active September 19, 2018 10:35
Show Gist options
  • Save rudolfovich/d77a1975eabc292630e6f75a99c58baf to your computer and use it in GitHub Desktop.
Save rudolfovich/d77a1975eabc292630e6f75a99c58baf to your computer and use it in GitHub Desktop.
Safe copy to array of char
#include <string>
#include <type_traits>
template<
class T,
size_t N,
typename = std::enable_if_t< (N > 0) >
>
void Copy(T (&lhs)[N], const std::basic_string<T> & rhs)
{
const std::basic_string<T>::size_type cnt = (std::min<std::basic_string<T>::size_type>)(N - 1, rhs.length());
if (cnt)
{
rhs.copy(lhs, cnt, 0);
}
lhs[cnt] = '\0';
}
template<
class T,
size_t N,
typename = std::enable_if_t< (N > 0) >
>
void Copy(T(&lhs)[N], const T * rhs)
{
//TODO: replace strlen with template StringLength<T>(s)
const std::basic_string<T>::size_type cnt = (std::min<std::basic_string<T>::size_type>)(N - 1, strlen(rhs));
if (cnt)
{
//TODO: replace strlen with template StringNCopy<T>(dst, src, cnt)
strncpy(lhs, rhs, cnt);
}
lhs[cnt] = '\0';
}
void main()
char dst[10];
Copy(dst, std::string(""));
Copy(dst, std::string("1"));
Copy(dst, std::string("12345"));
Copy(dst, std::string("123456789"));
Copy(dst, std::string("12345678901234567890"));
Copy(dst, "");
Copy(dst, "1");
Copy(dst, "12345");
Copy(dst, "123456789");
Copy(dst, "12345678901234567890");
}
//template<
// class T,
// size_t N,
// size_t M,
// typename = std::enable_if_t< (N > 0) >
// >
// void Copy(T(&lhs)[N], const T(&rhs)[M])
//{
// //TODO: replace strlen with template StringLength<T>(s)
// const std::basic_string<T>::size_type cnt = (std::min<std::basic_string<T>::size_type>)(N - 1, M);
// if (cnt)
// {
// //TODO: replace strlen with template StringNCopy<T>(dst, src, cnt)
// strncpy(lhs, rhs, cnt);
// }
// lhs[cnt] = '\0';
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment