StringCopy.h 909 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Scintilla source code edit control
  2. /** @file StringCopy.h
  3. ** Safe string copy function which always NUL terminates.
  4. ** ELEMENTS macro for determining array sizes.
  5. **/
  6. // Copyright 2013 by Neil Hodgson <neilh@scintilla.org>
  7. // The License.txt file describes the conditions under which this software may be distributed.
  8. #ifndef STRINGCOPY_H
  9. #define STRINGCOPY_H
  10. #ifdef SCI_NAMESPACE
  11. namespace Scintilla {
  12. #endif
  13. // Safer version of string copy functions like strcpy, wcsncpy, etc.
  14. // Instantiate over fixed length strings of both char and wchar_t.
  15. // May truncate if source doesn't fit into dest with room for NUL.
  16. template <typename T, size_t count>
  17. void StringCopy(T (&dest)[count], const T* source) {
  18. for (size_t i=0; i<count; i++) {
  19. dest[i] = source[i];
  20. if (!source[i])
  21. break;
  22. }
  23. dest[count-1] = 0;
  24. }
  25. #define ELEMENTS(a) (sizeof(a) / sizeof(a[0]))
  26. #ifdef SCI_NAMESPACE
  27. }
  28. #endif
  29. #endif