2 #include "vg_platform.h"
5 i32
vg_str_storage( vg_str
*str
)
9 vg_str_dynamic
*arr
= (vg_str_dynamic
*)str
->buffer
;
18 * Reset string. If len is -1 (dynamically allocated), buffer must be either
19 * NULL or be acquired from malloc or realloc
21 void vg_strnull( vg_str
*str
, char *buffer
, i32 len
)
25 str
->buffer
[0] = '\0';
31 vg_fatal_error( "0 length string allocation\n" );
34 void vg_strfree( vg_str
*str
)
38 vg_str_dynamic
*arr
= (vg_str_dynamic
*)str
->buffer
;
48 * Double the size of the dynamically allocated string. If unallocated, alloc of
51 static i32
vg_str_dynamic_grow( vg_str
*str
)
54 vg_str_dynamic
*hdr
= ((vg_str_dynamic
*)str
->buffer
) - 1;
55 i32 total
= (hdr
->len
+ sizeof(vg_str_dynamic
)) * 2;
56 hdr
= realloc( hdr
, total
);
57 hdr
->len
= total
- sizeof(vg_str_dynamic
);
58 str
->buffer
= (char *)(hdr
+1);
62 vg_str_dynamic
*hdr
= malloc(16);
63 hdr
->len
= 16-sizeof(vg_str_dynamic
);
64 str
->buffer
= (char *)(hdr
+1);
65 str
->buffer
[0] = '\0';
70 void vg_strcat( vg_str
*str
, const char *append
)
72 if( !append
|| (str
->i
== -1) ) return;
74 i32 max
= vg_str_storage( str
),
80 max
= vg_str_dynamic_grow( str
);
83 str
->buffer
[ max
-1 ] = '\0';
88 char c
= append
[ i
++ ];
89 str
->buffer
[ str
->i
] = c
;
98 void vg_strcatch( vg_str
*str
, char c
)
100 vg_strcat( str
, (char[]){ c
, '\0' } );
104 * FIXME: Negative numbers
106 void vg_strcati32( vg_str
*str
, i32 value
)
111 while( value
&& (i
<31) ){
112 temp
[ i
++ ] = '0' + (value
% 10);
117 for( int j
=0; j
<i
; j
++ )
118 reverse
[j
] = temp
[ i
-1-j
];
121 vg_strcat( str
, reverse
);
124 vg_strcat( str
, "0" );
127 void vg_strcati32r( vg_str
*str
, i32 value
, i32 n
, char alt
)
135 temp
[ n
-1 - (i
++) ] = '0' + (value
% 10);
140 temp
[ n
-1 - i
] = alt
;
143 vg_strcat( str
, temp
);
146 int vg_strgood( vg_str
*str
)
148 if( str
->i
== -1 ) return 0;
153 * Returns pointer to last instance of character
155 char *vg_strch( vg_str
*str
, char c
)
158 for( i32 i
=0; i
<str
->i
; i
++ ){
159 if( str
->buffer
[i
] == c
)
166 u32
vg_strncpy( const char *src
, char *dst
, u32 len
,
167 enum strncpy_behaviour behaviour
)
169 for( u32 i
=0; i
<len
; i
++ ){
172 if( !src
[i
] ) return i
;
175 if( behaviour
== k_strncpy_always_add_null
){
179 else if( behaviour
== k_strncpy_overflow_fatal
){
180 vg_fatal_error( "Strncpy dest exceeded buffer length\n" );
188 u32
vg_strdjb2( const char *str
)
192 while( (c
= *str
++) )
193 hash
= ((hash
<< 5) + hash
) + c
; /* hash * 33 + c */
198 int vg_strdjb2_eq( const char *s1
, u32 h1
, const char *s2
, u32 h2
)
201 if(!strcmp(s1
, s2
)) return 1;