1
1
#include "static_string.h"
2
2
3
- const ss EMPTY_STRING = {0 , "" };
3
+ // defined this way so it has an in-memory representation that is distinct
4
+ // from NULL, allowing us to use NULL to represent a sentinel value
5
+ const ss EMPTY_STRING = {0 , "\0" };
4
6
5
7
int
6
8
ssnewlen (const char * init , size_t len , ss * to_init )
@@ -10,24 +12,19 @@ ssnewlen(const char *init, size_t len, ss *to_init)
10
12
}
11
13
12
14
if (len == 0 ) {
13
- to_init -> len = 0 ;
14
- to_init -> buf = EMPTY_STRING . buf ;
15
+ * to_init = EMPTY_STRING ;
16
+ return 0 ;
15
17
}
16
18
17
- // one extra byte for null terminator
18
- char * ret_buf = (char * )malloc (sizeof (char ) * (len + 1 ));
19
+ char * ret_buf = (char * )malloc (sizeof (char ) * len );
19
20
20
21
if (ret_buf == NULL ) {
21
22
return -1 ;
22
23
}
23
24
24
25
to_init -> len = len ;
25
26
26
- if (len > 0 ) {
27
- memcpy (ret_buf , init , len );
28
- }
29
-
30
- ret_buf [len ] = '\0' ;
27
+ memcpy (ret_buf , init , len );
31
28
32
29
to_init -> buf = ret_buf ;
33
30
@@ -37,10 +34,8 @@ ssnewlen(const char *init, size_t len, ss *to_init)
37
34
void
38
35
ssfree (ss * str )
39
36
{
40
- if (str -> buf != NULL ) {
41
- if (str -> buf != EMPTY_STRING .buf ) {
42
- free (str -> buf );
43
- }
37
+ if (str -> buf != NULL && str -> buf != EMPTY_STRING .buf ) {
38
+ free (str -> buf );
44
39
str -> buf = NULL ;
45
40
}
46
41
str -> len = 0 ;
@@ -66,18 +61,44 @@ ssnewemptylen(size_t num_bytes, ss *out)
66
61
return -2 ;
67
62
}
68
63
69
- char * buf = (char * )malloc (sizeof (char ) * (num_bytes + 1 ));
64
+ out -> len = num_bytes ;
65
+
66
+ if (num_bytes == 0 ) {
67
+ * out = EMPTY_STRING ;
68
+ return 0 ;
69
+ }
70
+
71
+ char * buf = (char * )malloc (sizeof (char ) * num_bytes );
70
72
71
73
if (buf == NULL ) {
72
74
return -1 ;
73
75
}
74
76
75
77
out -> buf = buf ;
76
- out -> len = num_bytes ;
77
78
78
79
return 0 ;
79
80
}
80
81
82
+ // same semantics as strcmp
83
+ int
84
+ sscmp (const ss * s1 , const ss * s2 )
85
+ {
86
+ size_t minlen = s1 -> len < s2 -> len ? s1 -> len : s2 -> len ;
87
+
88
+ int cmp = strncmp (s1 -> buf , s2 -> buf , minlen );
89
+
90
+ if (cmp == 0 ) {
91
+ if (s1 -> len > minlen ) {
92
+ return 1 ;
93
+ }
94
+ if (s2 -> len > minlen ) {
95
+ return -1 ;
96
+ }
97
+ }
98
+
99
+ return cmp ;
100
+ }
101
+
81
102
int
82
103
ss_isnull (const ss * in )
83
104
{
@@ -86,3 +107,13 @@ ss_isnull(const ss *in)
86
107
}
87
108
return 0 ;
88
109
}
110
+
111
+ const char *
112
+ ss_data (const ss * in , const char * default_str )
113
+ {
114
+ if (ss_isnull (in )) {
115
+ return default_str ;
116
+ }
117
+
118
+ return in -> buf ;
119
+ }
0 commit comments