11#include "static_string.h"
22
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" };
46
57int
68ssnewlen (const char * init , size_t len , ss * to_init )
@@ -10,24 +12,19 @@ ssnewlen(const char *init, size_t len, ss *to_init)
1012 }
1113
1214 if (len == 0 ) {
13- to_init -> len = 0 ;
14- to_init -> buf = EMPTY_STRING . buf ;
15+ * to_init = EMPTY_STRING ;
16+ return 0 ;
1517 }
1618
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 );
1920
2021 if (ret_buf == NULL ) {
2122 return -1 ;
2223 }
2324
2425 to_init -> len = len ;
2526
26- if (len > 0 ) {
27- memcpy (ret_buf , init , len );
28- }
29-
30- ret_buf [len ] = '\0' ;
27+ memcpy (ret_buf , init , len );
3128
3229 to_init -> buf = ret_buf ;
3330
@@ -37,10 +34,8 @@ ssnewlen(const char *init, size_t len, ss *to_init)
3734void
3835ssfree (ss * str )
3936{
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 );
4439 str -> buf = NULL ;
4540 }
4641 str -> len = 0 ;
@@ -66,18 +61,44 @@ ssnewemptylen(size_t num_bytes, ss *out)
6661 return -2 ;
6762 }
6863
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 );
7072
7173 if (buf == NULL ) {
7274 return -1 ;
7375 }
7476
7577 out -> buf = buf ;
76- out -> len = num_bytes ;
7778
7879 return 0 ;
7980}
8081
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+
81102int
82103ss_isnull (const ss * in )
83104{
@@ -86,3 +107,13 @@ ss_isnull(const ss *in)
86107 }
87108 return 0 ;
88109}
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