-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.c
More file actions
389 lines (359 loc) · 12.9 KB
/
Copy path1.c
File metadata and controls
389 lines (359 loc) · 12.9 KB
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
// robust_time_parser.c
// Compile: gcc -std=c11 -O2 -Wall robust_time_parser.c -o robust_time_parser
// Usage: run and try inputs (examples are in main).
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <limits.h>
#include <math.h>
typedef struct {
long long total_millis; // signed total milliseconds (can be negative)
int hours;
int minutes;
int seconds;
int millis; // 0..999
} time_parse_result;
// Trim helpers
static void trim(char *s) {
// trim both ends in place
char *p = s;
while (*p && isspace((unsigned char)*p)) p++;
if (p != s) memmove(s, p, strlen(p)+1);
size_t len = strlen(s);
while (len && isspace((unsigned char)s[len-1])) s[--len] = '\0';
}
// lower-case in place
static void to_lower_inplace(char *s) {
for (char *p = s; *p; ++p) *p = (char)tolower((unsigned char)*p);
}
// map unit token to multiplier in milliseconds
// returns multiplier (ms) and sets matched=true if valid unit found
static long long unit_to_multiplier_ms(const char *unit, bool *matched) {
*matched = false;
if (!unit || !*unit) return 0;
// recognize prefixes
if (unit[0]=='h') {
*matched = true;
return 3600LL * 1000LL;
}
if (unit[0]=='m') {
*matched = true;
return 60LL * 1000LL;
}
if (unit[0]=='s') {
*matched = true;
return 1000LL;
}
// accomodate words like "hour", "min", "sec", "hrs", "mins", "secs", "seconds", etc.
if (strncmp(unit, "hour", 4)==0 || strncmp(unit, "hr", 2)==0) {
*matched = true;
return 3600LL * 1000LL;
}
if (strncmp(unit, "min", 3)==0) {
*matched = true;
return 60LL * 1000LL;
}
if (strncmp(unit, "sec", 3)==0) {
*matched = true;
return 1000LL;
}
// none matched
return 0;
}
static bool safe_add_millis(long long *acc, long long add) {
if (add > 0 && *acc > LLONG_MAX - add) return false;
if (add < 0 && *acc < LLONG_MIN - add) return false;
*acc += add;
return true;
}
// Helper: parse colon-separated forms
// Accepts "H:M:S(.frac)" or "M:S(.frac)" or "S(.frac)". Fractional part only allowed in last component.
static bool parse_colon_format(const char *s_in, long long *out_millis) {
char buf[256];
strncpy(buf, s_in, sizeof(buf)-1);
buf[sizeof(buf)-1] = '\0';
trim(buf);
to_lower_inplace(buf);
// Tokenize by ':'
int parts_idx = 0;
char *parts[4] = {0};
char *p = buf;
char *tok;
char *tok = strtok(p, ":");
while (tok && parts_idx < 4) {
parts[parts_idx++] = tok;
tok = strtok(NULL, ":");
}
if (parts_idx == 0) return false;
// only allow up to 3 parts
if (parts_idx > 3) return false;
// parse each part; last part may have fractional seconds
long long total_ms = 0;
for (int i = 0; i < parts_idx; ++i) {
char *part = parts[i];
trim(part);
if (*part == '\0') return false;
// last part: allow decimal
if (i == parts_idx - 1) {
// parse double
char *endptr = NULL;
double val = strtod(part, &endptr);
if (endptr == part) return false; // no number
// if there's trailing non-space, fail
while (*endptr) {
if (!isspace((unsigned char)*endptr)) return false;
endptr++;
}
long long add_ms = (long long) llround(val * 1000.0);
// multiplier depends on position: if 3 parts -> seconds, if 2 parts -> seconds, if 1 part -> seconds
// multiplier for this component:
if (parts_idx == 3) {
// parts: H : M : S
// this is seconds
if (!safe_add_millis(&total_ms, add_ms)) return false;
} else if (parts_idx == 2) {
// parts: M : S
if (!safe_add_millis(&total_ms, add_ms)) return false;
} else {
// single value, seconds
if (!safe_add_millis(&total_ms, add_ms)) return false;
}
} else {
// integer component (hours or minutes)
char *endptr = NULL;
long long val = strtoll(part, &endptr, 10);
if (endptr == part) return false;
while (*endptr) {
if (!isspace((unsigned char)*endptr)) return false;
endptr++;
}
// position: if parts_idx==3: i==0 -> hours, i==1 -> minutes
if (parts_idx == 3) {
if (i == 0) {
if (!safe_add_millis(&total_ms, val * 3600LL * 1000LL)) return false;
} else if (i == 1) {
if (!safe_add_millis(&total_ms, val * 60LL * 1000LL)) return false;
}
} else if (parts_idx == 2) {
// i==0 -> minutes
if (i == 0) {
if (!safe_add_millis(&total_ms, val * 60LL * 1000LL)) return false;
}
} else {
// shouldn't get here
}
}
}
*out_millis = total_ms;
return true;
}
// Main parser
// returns true on success, fills result
bool parse_timestring_to_millis(const char *input, time_parse_result *res) {
if (!input || !res) return false;
char buf[1024];
strncpy(buf, input, sizeof(buf)-1);
buf[sizeof(buf)-1] = '\0';
trim(buf);
if (buf[0] == '\0') return false;
// capture sign
bool negative = false;
if (buf[0] == '+') {
memmove(buf, buf+1, strlen(buf));
trim(buf);
} else if (buf[0] == '-') {
negative = true;
memmove(buf, buf+1, strlen(buf));
trim(buf);
}
// if colon present -> parse colon format
long long total_ms = 0;
if (strchr(buf, ':')) {
if (!parse_colon_format(buf, &total_ms)) return false;
if (negative) total_ms = -total_ms;
// Normalize into fields
long long abs_ms = llabs(total_ms);
long long secs = abs_ms / 1000LL;
int millis = (int)(abs_ms % 1000LL);
int hours = (int)(secs / 3600LL);
int minutes = (int)((secs % 3600LL) / 60LL);
int seconds = (int)(secs % 60LL);
res->total_millis = total_ms;
res->hours = hours;
res->minutes = minutes;
res->seconds = seconds;
res->millis = millis;
return true;
}
// Otherwise: token-scan: find numbers (possibly float) and the immediate following letters as unit (if any)
char *s = buf;
to_lower_inplace(s);
// We'll collect tokens into arrays:
typedef struct {
double value; // numeric value (may be fractional)
char unit[32]; // unit letters if present (lowercase), empty if none
bool has_unit;
} token_t;
token_t tokens[64];
int tok_count = 0;
while (*s) {
// skip non-digit/non-dot/non-plus/minus (note minus handled earlier)
while (*s && !isdigit((unsigned char)*s) && *s != '.' && *s!='+' && *s!='-') s++;
if (!*s) break;
// parse number (double)
char *endptr = NULL;
double val = strtod(s, &endptr);
if (endptr == s) {
// no number? skip one char to avoid infinite loop
s++;
continue;
}
s = endptr;
// skip spaces
while (*s && isspace((unsigned char)*s)) s++;
// capture unit letters (alphabetic), up to punctuation/space
char unitbuf[32] = {0};
int ui = 0;
while (*s && isalpha((unsigned char)*s) && ui < (int)sizeof(unitbuf)-1) {
unitbuf[ui++] = *s;
s++;
}
unitbuf[ui] = '\0';
// trim possible plural punctuation like '.' or ',' after unit
// skip trailing punctuation/spaces for next token
while (*s && !isdigit((unsigned char)*s) && *s != '.' && *s!='+' && *s!='-') s++;
if (tok_count >= (int)(sizeof(tokens)/sizeof(tokens[0]))) return false;
tokens[tok_count].value = val;
if (ui > 0) {
tokens[tok_count].has_unit = true;
strncpy(tokens[tok_count].unit, unitbuf, sizeof(tokens[tok_count].unit)-1);
} else {
tokens[tok_count].has_unit = false;
tokens[tok_count].unit[0] = '\0';
}
tok_count++;
}
if (tok_count == 0) return false;
// Now convert tokens to milliseconds
// If tokens have explicit units, use them.
// For tokens without units, we'll assign right->left to s,m,h for ambiguous tokens.
long long accum_ms = 0;
// First pass: explicit unit tokens
bool used_index[64] = {0};
for (int i = 0; i < tok_count; ++i) {
if (!tokens[i].has_unit) continue;
bool matched;
long long mult = unit_to_multiplier_ms(tokens[i].unit, &matched);
if (!matched) {
// try partial match: maybe user wrote "hours" or "mins" etc - function covers startswith check
// if still not matched, treat as error
return false;
}
// convert value*mult to ms (watch for overflow)
double prod = tokens[i].value * (double)mult;
if (!isfinite(prod)) return false;
// round to nearest ms
long long add_ms = (long long) llround(prod);
if (!safe_add_millis(&accum_ms, add_ms)) return false;
used_index[i] = true;
}
// Second pass: unitless tokens — assign right->left to seconds, minutes, hours
int slot = 0; // 0 -> seconds, 1 -> minutes, 2 -> hours (we'll fill starting from seconds)
// We'll count how many unitless tokens and assign from rightmost token to leftmost token
int unitless_count = 0;
for (int i = 0; i < tok_count; ++i) if (!used_index[i]) unitless_count++;
if (unitless_count > 0) {
// collect indexes of unitless tokens
int idxs[64]; int idxc = 0;
for (int i = 0; i < tok_count; ++i) if (!used_index[i]) idxs[idxc++] = i;
// assign from right to left
for (int j = idxc - 1; j >= 0; --j) {
int i = idxs[j];
long long add_ms = 0;
if (slot == 0) { // seconds
add_ms = (long long) llround(tokens[i].value * 1000.0);
} else if (slot == 1) { // minutes
add_ms = (long long) llround(tokens[i].value * 60.0 * 1000.0);
} else if (slot == 2) { // hours
add_ms = (long long) llround(tokens[i].value * 3600.0 * 1000.0);
} else {
// more numbers than h/m/s -> treat additional left numbers as extra hours (carry on)
add_ms = (long long) llround(tokens[i].value * 3600.0 * 1000.0);
}
if (!safe_add_millis(&accum_ms, add_ms)) return false;
slot++;
}
}
if (negative) accum_ms = -accum_ms;
// Normalize into fields (hours/min/sec/millis)
long long abs_ms = llabs(accum_ms);
long long total_seconds = abs_ms / 1000LL;
int millis = (int)(abs_ms % 1000LL);
int hours = (int)(total_seconds / 3600LL);
int minutes = (int)((total_seconds % 3600LL) / 60LL);
int seconds = (int)(total_seconds % 60LL);
res->total_millis = accum_ms;
res->hours = hours;
res->minutes = minutes;
res->seconds = seconds;
res->millis = millis;
return true;
}
// --- Example test harness ---
int main(void) {
const char *tests[] = {
"12:34:56",
"3:21",
"45",
"1hr 3min 23sec",
"1h30m",
"1h 30",
"90s",
"1 hour, 30 minutes",
"1:02:03.5",
"2.5h",
"1.25min",
"1 2 3",
"3 20",
"-1:00:00",
" 5hours 90sec ",
"invalid",
"1hr 75min 120s",
"1000000000000s", // test big value (may overflow)
NULL
};
for (int i = 0; tests[i]; ++i) {
time_parse_result r;
bool ok = parse_timestring_to_millis(tests[i], &r);
if (!ok) {
printf("Input: \"%s\" -> parse error or overflow\n", tests[i]);
} else {
// show normalized breakdown and total seconds
long long total_s = r.total_millis / 1000LL;
long long sign = (r.total_millis < 0) ? -1 : 1;
printf("Input: \"%s\"\n -> normalized: %s%02d:%02d:%02d.%03d (total millis: %lld)\n",
tests[i],
(r.total_millis < 0) ? "-" : "",
r.hours, r.minutes, r.seconds, r.millis, r.total_millis);
}
}
// interactive demo:
printf("\nEnter time strings (empty line to quit):\n");
char line[512];
while (1) {
if (!fgets(line, sizeof(line), stdin)) break;
trim(line);
if (line[0] == '\0') break;
time_parse_result r;
if (!parse_timestring_to_millis(line, &r)) {
printf("Parse error\n");
} else {
printf("Parsed: %s%02d:%02d:%02d.%03d (total millis: %lld)\n",
(r.total_millis < 0) ? "-" : "",
r.hours, r.minutes, r.seconds, r.millis, r.total_millis);
}
}
return 0;
}