summaryrefslogtreecommitdiff
path: root/libc/string/cris/strncpy.c
blob: 8d074071ac22c533625cfe19714d7b7d52bca7b5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
 * Copyright (C) 2006-2007 Axis Communications AB
 *
 * Licensed under the LGPL v2.1, see the file COPYING.LIB in this tarball.
 */

#include <string.h>


char *strncpy(char *dest, const char *src, size_t count)
{
  char *ret = dest;
  unsigned long himagic = 0x80808080L;
  unsigned long lomagic = 0x01010101L;

  while (count && (unsigned long)src & (sizeof src - 1))
  {
    count--;
    if (!(*dest++ = *src++))
    {
      goto finalize;
    }
  }

  while (count >= sizeof (unsigned long))
  {
    unsigned long value = *(unsigned long*)src;
    unsigned long magic;

    if ((magic = (value - lomagic) & himagic))
    {
      if (magic & ~value)
      {
        break;
      }
    }

    *(unsigned long*)dest = value;
    dest += sizeof (unsigned long);
    src += sizeof (unsigned long);
    count -= sizeof (unsigned long);
  }

  while (count)
  {
    count--;
    if (!(*dest++ = *src++))
      break;
  }

finalize:
  if (count)
  {
    memset(dest, '\0', count);
  }

  return ret;
}
libc_hidden_def(strncpy)