2 #include "vg_platform.h"
7 i32
vg_str_storage( vg_str
*str
)
11 vg_str_dynamic
*arr
= (vg_str_dynamic
*)str
->buffer
;
20 * Reset string. If len is -1 (dynamically allocated), buffer must be either
21 * NULL or be acquired from malloc or realloc
23 void vg_strnull( vg_str
*str
, char *buffer
, i32 len
)
27 str
->buffer
[0] = '\0';
33 vg_fatal_error( "0 length string allocation\n" );
36 void vg_strfree( vg_str
*str
)
40 vg_str_dynamic
*arr
= (vg_str_dynamic
*)str
->buffer
;
50 * Double the size of the dynamically allocated string. If unallocated, alloc of
53 static i32
vg_str_dynamic_grow( vg_str
*str
)
56 vg_str_dynamic
*hdr
= ((vg_str_dynamic
*)str
->buffer
) - 1;
57 i32 total
= (hdr
->len
+ sizeof(vg_str_dynamic
)) * 2;
58 hdr
= realloc( hdr
, total
);
59 hdr
->len
= total
- sizeof(vg_str_dynamic
);
60 str
->buffer
= (char *)(hdr
+1);
64 vg_str_dynamic
*hdr
= malloc(16);
65 hdr
->len
= 16-sizeof(vg_str_dynamic
);
66 str
->buffer
= (char *)(hdr
+1);
67 str
->buffer
[0] = '\0';
72 void vg_strcat( vg_str
*str
, const char *append
)
74 if( !append
|| (str
->i
== -1) ) return;
76 i32 max
= vg_str_storage( str
),
82 max
= vg_str_dynamic_grow( str
);
85 str
->buffer
[ max
-1 ] = '\0';
90 char c
= append
[ i
++ ];
91 str
->buffer
[ str
->i
] = c
;
100 void vg_strcatch( vg_str
*str
, char c
)
102 vg_strcat( str
, (char[]){ c
, '\0' } );
106 * FIXME: Negative numbers
108 void vg_strcati32( vg_str
*str
, i32 value
)
113 while( value
&& (i
<31) ){
114 temp
[ i
++ ] = '0' + (value
% 10);
119 for( int j
=0; j
<i
; j
++ )
120 reverse
[j
] = temp
[ i
-1-j
];
123 vg_strcat( str
, reverse
);
126 vg_strcat( str
, "0" );
129 void vg_strcati32r( vg_str
*str
, i32 value
, i32 n
, char alt
)
137 temp
[ n
-1 - (i
++) ] = '0' + (value
% 10);
142 temp
[ n
-1 - i
] = alt
;
145 vg_strcat( str
, temp
);
148 int vg_strgood( vg_str
*str
)
150 if( str
->i
== -1 ) return 0;
155 * Returns pointer to last instance of character
157 char *vg_strch( vg_str
*str
, char c
)
160 for( i32 i
=0; i
<str
->i
; i
++ ){
161 if( str
->buffer
[i
] == c
)
168 u32
vg_strncpy( const char *src
, char *dst
, u32 len
,
169 enum strncpy_behaviour behaviour
)
171 for( u32 i
=0; i
<len
; i
++ ){
174 if( !src
[i
] ) return i
;
177 if( behaviour
== k_strncpy_always_add_null
){
181 else if( behaviour
== k_strncpy_overflow_fatal
){
182 vg_fatal_error( "Strncpy dest exceeded buffer length\n" );
190 static void _vg_strcatf_va( vg_str
*str
, const char *fmt
, va_list args
)
193 vsnprintf( buffer
, vg_list_size(buffer
), fmt
, args
);
194 vg_strcat( str
, buffer
);
197 void vg_strcatf( vg_str
*str
, const char *fmt
, ... )
200 va_start( args
, fmt
);
201 _vg_strcatf_va( str
, fmt
, args
);
205 u32
vg_strdjb2( const char *str
)
209 while( (c
= *str
++) )
210 hash
= ((hash
<< 5) + hash
) + c
; /* hash * 33 + c */
215 int vg_strdjb2_eq( const char *s1
, u32 h1
, const char *s2
, u32 h2
)
218 if(!strcmp(s1
, s2
)) return 1;