blob: ca58fb1c2725acc2484eeeb0ad8fc08e1dd79135 (
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
|
/* SPDX-License-Identifier: MIT
* Copyright (c) 2026 Leah Rowe <leah@libreboot.org>
*
* String functions
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <unistd.h>
#include "../include/common.h"
/* scmp() - strict string comparison
*
* strict string comparison
* similar to strncmp, but null and
* unterminated inputs do not produce
* a return value; on error, errno is
* set and -1 is returned.
*
* the real return value is stored in
* the 4th argument by pointer.
*
* the value at rval pointer is set,
* only upon success. callers should
* check the return value accordingly.
*/
int
scmp(const char *a,
const char *b,
size_t maxlen,
int *rval)
{
size_t ch;
unsigned char ac;
unsigned char bc;
if (a == NULL ||
b == NULL ||
rval == NULL) {
errno = EFAULT;
return -1;
}
for (ch = 0; ch < maxlen; ch++) {
ac = (unsigned char)a[ch];
bc = (unsigned char)b[ch];
if (ac != bc) {
*rval = ac - bc;
return 0;
}
if (ac == '\0') {
*rval = 0;
return 0;
}
}
/* block unterminated strings */
errno = EFAULT;
return -1;
}
/* slen() - strict strict length
*
* strict string length calculation
* similar to strnlen, but null and
* unterminated inputs do not produce
* a return value; on error, errno is
* set and -1 is returned.
*
* the real return value is stored in
* the 3rd argument by pointer.
*
* the value at rval pointer is set,
* only upon success. callers should
* check the return value accordingly.
*/
int
slen(const char *s,
size_t maxlen,
size_t *rval)
{
size_t ch;
if (s == NULL ||
rval == NULL) {
errno = EFAULT;
return -1;
}
for (ch = 0;
ch < maxlen && s[ch] != '\0';
ch++);
if (ch == maxlen) {
/* unterminated */
errno = EFAULT;
return -1;
}
*rval = ch;
return 0;
}
|