strncpy.c 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. * Copyright (C) 2006-2007 Axis Communications AB
  3. *
  4. * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
  5. */
  6. #include <string.h>
  7. char *strncpy(char *dest, const char *src, size_t count)
  8. {
  9. char *ret = dest;
  10. unsigned long himagic = 0x80808080L;
  11. unsigned long lomagic = 0x01010101L;
  12. while (count && (unsigned long)src & (sizeof src - 1))
  13. {
  14. count--;
  15. if (!(*dest++ = *src++))
  16. {
  17. goto finalize;
  18. }
  19. }
  20. while (count >= sizeof (unsigned long))
  21. {
  22. unsigned long value = *(unsigned long*)src;
  23. unsigned long magic;
  24. if ((magic = (value - lomagic) & himagic))
  25. {
  26. if (magic & ~value)
  27. {
  28. break;
  29. }
  30. }
  31. *(unsigned long*)dest = value;
  32. dest += sizeof (unsigned long);
  33. src += sizeof (unsigned long);
  34. count -= sizeof (unsigned long);
  35. }
  36. while (count)
  37. {
  38. count--;
  39. if (!(*dest++ = *src++))
  40. break;
  41. }
  42. finalize:
  43. if (count)
  44. {
  45. memset(dest, '\0', count);
  46. }
  47. return ret;
  48. }
  49. libc_hidden_def(strncpy)