-
Notifications
You must be signed in to change notification settings - Fork 0
/
types_string.c
103 lines (83 loc) · 1.96 KB
/
types_string.c
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
/********************************************
memory.c
copyright 1991,1992,2014-2016 Michael D. Brennan
This is a source file for mawk, an implementation of
the AWK programming language.
Mawk is distributed without warranty under the terms of
the GNU General Public License, version 3, 2007.
If you import elements of this code into another product,
you agree to not name that product mawk.
********************************************/
/* types_string.c */
#include "mawk.h"
#include "types_string.h"
STRING null_str = { 0, 1, "" };
STRING * const the_empty_str = &null_str;
static STRING *
xnew_STRING(const size_t len )
{
STRING * sval = (STRING *)zmalloc( STRING_SIZE( len ) );
sval->len = len;
sval->ref_cnt = 1;
sval->str[len] = 0;
return sval;
}
/* allocate space for a STRING */
STRING *
new_STRING0( const size_t len )
{
if ( len == 0 ) {
return STRING_dup( the_empty_str );
}
else {
return xnew_STRING( len );
}
}
/* memcpy into a STRING */
STRING *
new_STRING2( const char * s, const size_t len )
{
if ( len == 0 ) {
return STRING_dup( the_empty_str );
}
else {
STRING * ret = xnew_STRING( len );
memcpy( ret->str, s, len );
return ret;
}
}
/* convert char* to STRING* */
STRING *
new_STRING( const char * s )
{
size_t len = strlen( s );
return new_STRING2( s, len );
}
/* compare two strings in manner of strcmp */
int
STRING_cmp( const STRING * s1, const STRING * s2 )
{
int ret;
size_t len1 = s1->len;
size_t len2 = s2->len;
size_t len = len1 <= len2 ? len1 : len2;
ret = memcmp( s1->str, s2->str, len );
if ( ret == 0 ) {
if ( len1 > len ) {
ret = 1;
}
else if ( len2 > len ) {
ret = -1;
}
}
return ret;
}
#ifdef DEBUG
void
DB_free_STRING( STRING * sval )
{
if ( --sval->ref_cnt == 0 ) {
zfree( sval, STRING_SIZE( sval->len ) );
}
}
#endif