-
Notifications
You must be signed in to change notification settings - Fork 1
/
utilities.c
556 lines (463 loc) · 11.4 KB
/
utilities.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
// utilities.c-- miscellaneous utility functions.
#include <stdlib.h>
#define true 1
#define false 0
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <limits.h>
#include <inttypes.h>
#include <math.h>
#include <float.h>
#include "utilities.h"
//----------
//
// copy_string--
// Create (in the heap) a copy of a string or a prefix of a string.
//
//----------
//
// Arguments:
// const char* s: The string to copy.
// int n: (copy_prefix only) the number of characters to copy.
//
// Returns:
// A pointer to new string; failures result in program termination.
//
//----------
char* copy_string
(const char* s)
{
char* ss;
if (s == NULL) return NULL;
ss = malloc (strlen(s) + 1);
if (ss == NULL)
{
fprintf (stderr, "failed to allocate %lld bytes to copy \"%s\"\n",
(long long) (strlen(s)+1), s);
exit (EXIT_FAILURE);
}
return strcpy (/*to*/ ss, /*from*/ s);
}
//----------
//
// strcmp_prefix--
// Determine if a string contains another as a prefix.
//
//----------
//
// Arguments:
// const char* str1: The string.
// const char* str2: The prefix string.
//
// Returns:
// The same as strcmp(prefix1,str2) would, where prefix1 is str1 truncated
// to be no longer than str2.
//
//----------
int strcmp_prefix
(const char* str1,
const char* str2)
{
return strncmp (str1, str2, strlen(str2));
}
//----------
//
// strcmp_suffix, strncmp_suffix--
// Determine if a string contains another as a suffix.
//
//----------
//
// Arguments:
// const char* str1: The string.
// const char* str2: The suffix string.
// size_t n: (strncmp_suffix only) The max length of str1.
//
// Returns:
// The same as strcmp(suffix1,str2) or strncmp(suffix1,str2,n) would, where
// suffix1 is the last N characters of str1, and N is the length of str2. If
// str2 is longer than str1, it cannot be a suffix (in this case we compare to
// the entirety of str1).
//
//----------
int strcmp_suffix
(const char* str1,
const char* str2)
{
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
if (len2 <= len1) return strcmp (str1+len1-len2, str2);
else return strcmp (str1, str2);
}
int strncmp_suffix
(const char* str1,
const char* str2,
size_t n)
{
size_t len1 = strlen(str1);
size_t len2 = strlen(str2);
if (len1 > n) len1 = n;
if (len2 <= len1) return strcmp (str1+len1-len2, str2);
else return strcmp (str1, str2);
}
//----------
//
// string_to_int, string_to_u32--
// Parse a string for the integer value it contains.
//
//----------
//
// Arguments:
// const char* s: The string to parse.
//
// Returns:
// The integer value of the string. Note that the string *must not* contain
// anything other than a valid integer-- failures result in program
// termination.
//
//----------
int string_to_int
(const char* s)
{
char* ss;
int v;
char extra;
// skip to first non-blank
ss = (char*) s;
while ((*ss == ' ') || (*ss == '\t') || (*ss == '\n'))
ss++;
if (*ss == 0) goto empty_string;
// convert to number
if (sscanf (ss, "%d%c", &v, &extra) != 1) goto not_an_integer;
// make sure signs match
if ((v < 0) && (*ss != '-')) goto out_of_range;
if ((v > 0) && (*ss == '-')) goto out_of_range;
return v;
//////////
// failure exits
//////////
empty_string:
fprintf (stderr, "an empty string is not an integer\n");
exit (EXIT_FAILURE);
not_an_integer:
fprintf (stderr, "\"%s\" is not an integer\n", s);
exit (EXIT_FAILURE);
out_of_range:
fprintf (stderr, "\"%s\" is outside the range of a signed integer\n", s);
exit (EXIT_FAILURE);
return 0;
}
int string_to_u32
(const char* s)
{
char* ss;
u32 v;
char extra;
// skip to first non-blank
ss = (char*) s;
while ((*ss == ' ') || (*ss == '\t') || (*ss == '\n'))
ss++;
if (*ss == 0) goto empty_string;
// convert to number
if (*ss == '-') goto not_an_integer;
if (sscanf (ss, "%u%c", &v, &extra) != 1) goto not_an_integer;
return v;
//////////
// failure exits
//////////
empty_string:
fprintf (stderr, "an empty string is not an unsigned integer\n");
exit (EXIT_FAILURE);
not_an_integer:
fprintf (stderr, "\"%s\" is not an unsigned integer\n", s);
exit (EXIT_FAILURE);
return 0;
}
//----------
//
// string_to_unitized_int, string_to_unitized_int64--
// Parse a string for the integer value it contains, allowing K, M, and G
// suffixes.
//
//----------
//
// Arguments:
// const char* s: The string to parse.
// int byThousands: true => K means one thousand
// false => K means 1,024.
//
// Returns:
// The integer value of the string. Note that the string *must not* contain
// anything (except for an opptional suffix) other than a valid integer--
// failures result in fatality.
//
//----------
int string_to_unitized_int
(const char* s,
int byThousands)
{
char ss[20];
int len = strlen (s);
char* parseMe;
int v;
float vf;
char extra;
int mult;
int isFloat;
mult = 1;
if (len >= (int) sizeof (ss))
parseMe = (char*) s;
else
{
parseMe = ss;
strcpy (ss, s);
if (len > 0)
{
switch (ss[len-1])
{
case 'K': case 'k':
mult = (byThousands)? 1000 : 1024;
break;
case 'M': case 'm':
mult = (byThousands)? 1000000 : 1024L * 1024L;
break;
case 'G': case 'g':
mult = (byThousands)? 1000000000 : 1024L * 1024L * 1024L;
break;
}
if (mult != 1)
ss[len-1] = 0;
}
}
isFloat = false;
if (sscanf (parseMe, "%d%c", &v, &extra) != 1)
{
if (sscanf (parseMe, "%f%c", &vf, &extra) != 1) goto bad;
isFloat = true;
}
if (isFloat)
{
if ((vf > 0) && ( vf*mult > INT_MAX)) goto overflow;
if ((vf < 0) && (-vf*mult > INT_MAX)) goto overflow;
v = (vf * mult) + .5;
}
else if (mult != 1)
{
if ((v > 0) && ( v > INT_MAX / mult)) goto overflow;
if ((v < 0) && (-v > INT_MAX / mult)) goto overflow;
v *= mult;
}
return v;
bad:
fprintf (stderr, "\"%s\" is not an integer\n", s);
exit (EXIT_FAILURE);
overflow:
fprintf (stderr, "\"%s\" is out of range for an integer\n", s);
exit (EXIT_FAILURE);
return 0;
}
//----------
//
// string_to_double, try_string_to_double--
// Parse a string for the double floating point value it contains.
//
//----------
//
// Arguments:
// const char* s: The string to parse.
// double* v: (try_string_to_double only) Place to return the value.
//
// Returns:
// (string_to_double) The value of the string. Note that the string *must
// not* contain anything other than a valid number-- failures result in
// fatality.
//
// (try_string_to_double) true if the string was successfully parse; false
// if not.
//
//----------
// string_to_double--
double string_to_double
(const char* s)
{
char* ss;
double v;
char extra;
// skip to first non-blank
ss = (char*) s;
while ((*ss == ' ') || (*ss == '\t') || (*ss == '\n'))
ss++;
if (*ss == 0) goto empty_string;
// check for named constants
if (strcmp (s, "inf") == 0) return DBL_MAX;
if (strcmp (s, "+inf") == 0) return DBL_MAX;
if (strcmp (s, "-inf") == 0) return -DBL_MAX;
if (strcmp (s, "1/inf") == 0) return DBL_MIN;
if (strcmp (s, "+1/inf") == 0) return DBL_MIN;
if (strcmp (s, "-1/inf") == 0) return -DBL_MIN;
// convert to number
if (sscanf (s, "%lf%c", &v, &extra) != 1) goto not_a_number;
return v;
empty_string:
fprintf (stderr, "an empty string is not a number\n");
exit (EXIT_FAILURE);
not_a_number:
fprintf (stderr, "\"%s\" is not a number\n", s);
exit (EXIT_FAILURE);
}
// try_string_to_double--
int try_string_to_double
(const char* s,
double* _v)
{
char* ss;
double v;
char extra;
// skip to first non-blank
ss = (char*) s;
while ((*ss == ' ') || (*ss == '\t') || (*ss == '\n'))
ss++;
if (*ss == 0) return false;
// check for named constants
if (strcmp (s, "inf") == 0) { v = DBL_MAX; goto success; }
if (strcmp (s, "+inf") == 0) { v = DBL_MAX; goto success; }
if (strcmp (s, "-inf") == 0) { v = -DBL_MAX; goto success; }
if (strcmp (s, "1/inf") == 0) { v = DBL_MIN; goto success; }
if (strcmp (s, "+1/inf") == 0) { v = DBL_MIN; goto success; }
if (strcmp (s, "-1/inf") == 0) { v = -DBL_MIN; goto success; }
// convert to number
if (sscanf (s, "%lf%c", &v, &extra) != 1) return false;
success:
if (_v != NULL) *(_v) = v;
return true;
}
//----------
//
// skip_whitespace--
// Skip characters until we get something that ain't whitespace.
// skip_darkspace--
// Skip characters until we get something that ain't darkspace.
//
//----------
//
// Arguments:
// char* s: The string to read.
//
// Returns:
// Pointer to the first character at or beyond s that meets the stopping
// criteria. Note that we never scan beyond the end of the string.
//
//----------
char* skip_whitespace (char* s)
{ while ((*s != 0) && (isspace (*s))) s++; return s; }
char* skip_darkspace (char* s)
{ while ((*s != 0) && (!isspace (*s))) s++; return s; }
//----------
//
// duration_to_string--
// Convert a time (duration) to a string.
//
//----------
//
// Arguments:
// float seconds: The duration to convert.
//
// Returns:
// a pointer to a string representation of the duration; note that the
// buffer holding this string is private to this function.
//
//----------
char* duration_to_string
(float seconds)
{
static char buffer[1000];
int hours, minutes;
if (seconds < 60)
sprintf (buffer, "%.3fs", seconds);
else if (seconds < 3600)
{
minutes = seconds / 60;
seconds -= 60 * minutes;
sprintf (buffer, "%dm%06.3fs", minutes, seconds);
}
else
{
minutes = seconds / 60;
seconds -= 60 * minutes;
hours = minutes / 60;
minutes -= 60 * hours;
sprintf (buffer, "%dh%02dm%06.3fs", hours, minutes, seconds);
}
return buffer;
}
//----------
//
// ucommatize--
// Convert an integer to a string, including commas.
//
//----------
//
// Arguments:
// const u64 v: The number to convert. Note that the actual supported
// range is 63 bits (because, internally, we convert to signed
// int).
//
// Returns:
// A string representing that number, including commas. (see note 1)
//
//----------
//
// notes:
//
// (1) The memory containing the returned string belongs to this routine, as
// static memory. There are only five such memory blocks, and they are
// used on alternate calls. So when you make more than five calls, the
// results of previous calls are clobbered.
//
//----------
char* ucommatize
(const u64 v)
{
static char s1[52];// (big enough for 128-bit decimal value with commas,
static char s2[52];// .. the biggest being
static char s3[52];// .. 340,282,366,920,938,463,463,374,607,431,768,211,455)
static char s4[52];
static char s5[52];
static char* s = s5;
int len, commas;
char* src, *dst;
if (s == s1) s = s2; // (ping pong)
else if (s == s2) s = s3;
else if (s == s3) s = s4;
else if (s == s4) s = s5;
else s = s1;
sprintf (s, "%jd", (intmax_t) v); // $$$ this could overflow the buffer
// $$$ .. if int_max_t > 128 bits
len = strlen (s);
commas = (len-1) / 3;
if (commas != 0)
{
src = s + len - 1;
dst = s + len + commas; *(dst--) = 0;
while (dst > src)
{
*(dst--) = *(src--);
*(dst--) = *(src--);
*(dst--) = *(src--);
*(dst--) = ',';
}
}
return s;
}
void safe_strncpy
(char *dest, const char *src, size_t n)
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wstringop-truncation"
strncpy(dest, src, n);
#pragma GCC diagnostic pop
if (n > 0)
{
dest[n-1] = '\0'; // Ensure null-termination
}
}