Saturday, January 24, 2009

memcpy() / bcopy() / strncpy(): char_copy()

Well, as you've probably already noticed, I've started removing dependencies on the so-called "unsafe" string library functions from all my open-source libraries.

As part of this continuing (and somewhat life-sapping) activity, I'm moving through the STLSoft libraries. The latest release incorporates changes to the important winstl::basic_findfile_sequence class template, which is an STL extension over the Windows FindFile API.

This makes use of a new facility that's been added to the winstl::system_traits class templates: char_copy(). This (static) function is effectively a typed memcpy().


class winstl::system_traits<char>
{
. . .
public:
  char* char_copy(char* dest, char const* src, size_t n);
}

class winstl::system_traits<wchar_t>
{
. . .
public:
  wchar_t* char_copy(wchar_t* dest, wchar_t const* src, size_t n);
}


It copies exactly the number of characters specified, with no checks on the actual length of src.

The modest benefits are that it is a bit type-safe, and that you don't have to keep having to remember sizeof(char_type) * n.

I'm not totally struck on the name, and did consider borrowing other names. I liked BSD's bcopy() (to mean block copy), but it's too likely that some code somewhere #defines it to memcpy().

I'll gradually filter char_copy() throughout the rest of WinSTL, and then through UNIXSTL, as I work my way through the thankless task of getting "unsafe"-free. Ho hum.

No comments: