PatchworkOS  19e446b
A non-POSIX operating system.
Loading...
Searching...
No Matches
strncpy.c
Go to the documentation of this file.
1#include <string.h>
2
3char* strncpy(char* _RESTRICT s1, const char* _RESTRICT s2, size_t n)
4{
5 char* rc = s1;
6
7 while (n && (*s1++ = *s2++))
8 {
9 /* Cannot do "n--" in the conditional as size_t is unsigned and we have
10 to check it again for >0 in the next loop below, so we must not risk
11 underflow.
12 */
13 --n;
14 }
15
16 /* Checking against 1 as we missed the last --n in the loop above. */
17 while (n-- > 1)
18 {
19 *s1++ = '\0';
20 }
21
22 return rc;
23}
24
25#ifdef _KERNEL_
26#ifdef _TESTING_
27
28#include <kernel/log/log.h>
29#include <kernel/sched/clock.h>
30#include <kernel/utils/test.h>
31
32static uint64_t _test_strncpy_iter(void)
33{
34 char s[] = "xxxxxxx";
35 TEST_ASSERT(strncpy(s, "", 1) == s);
36 TEST_ASSERT(s[0] == '\0');
37 TEST_ASSERT(s[1] == 'x');
38 TEST_ASSERT(strncpy(s, "abcde", 6) == s);
39 TEST_ASSERT(s[0] == 'a');
40 TEST_ASSERT(s[4] == 'e');
41 TEST_ASSERT(s[5] == '\0');
42 TEST_ASSERT(s[6] == 'x');
43 TEST_ASSERT(strncpy(s, "abcde", 7) == s);
44 TEST_ASSERT(s[6] == '\0');
45 TEST_ASSERT(strncpy(s, "xxxx", 3) == s);
46 TEST_ASSERT(s[0] == 'x');
47 TEST_ASSERT(s[2] == 'x');
48 TEST_ASSERT(s[3] == 'd');
49
50 char s2[1024];
51 memset(s2, 'x', sizeof(s2));
52 char src[512];
53 memset(src, 'a', sizeof(src));
54 src[511] = '\0';
55
56 TEST_ASSERT(strncpy(s2, src, 1024) == s2);
57 TEST_ASSERT(s2[0] == 'a');
58 TEST_ASSERT(s2[510] == 'a');
59 TEST_ASSERT(s2[511] == '\0');
60 TEST_ASSERT(s2[512] == '\0');
61 TEST_ASSERT(s2[1023] == '\0');
62
63 return 0;
64}
65
67{
68 for (int k = 0; k < 1; ++k)
69 {
70 TEST_ASSERT(_test_strncpy_iter() != ERR);
71 }
72
73 return 0;
74}
75
76#endif
77#endif
#define _RESTRICT
Definition config.h:17
#define TEST_DEFINE(_name)
Define a test function to be run by TEST_ALL().
Definition test.h:71
#define TEST_ASSERT(cond)
Assert a condition in a test.
Definition test.h:82
#define ERR
Integer error value.
Definition ERR.h:17
__UINT64_TYPE__ uint64_t
Definition stdint.h:17
_PUBLIC void * memset(void *s, int c, size_t n)
Definition memset.c:4
char * strncpy(char *_RESTRICT s1, const char *_RESTRICT s2, size_t n)
Definition strncpy.c:3