76 lines
2.1 KiB
C
76 lines
2.1 KiB
C
#include "duration.h"
|
|
#include "stdlib.h"
|
|
#include "string.h"
|
|
#include <stdio.h>
|
|
|
|
enum DurationParserState {
|
|
DURATION_PARSER_STATE_INITIAL,
|
|
DURATION_PARSER_STATE_NUMBER,
|
|
DURATION_PARSER_STATE_SECOND,
|
|
DURATION_PARSER_STATE_MINUTE,
|
|
DURATION_PARSER_STATE_HOUR,
|
|
DURATION_PARSER_STATE_EOS,
|
|
};
|
|
|
|
Duration parseDuration(const char *duration) {
|
|
enum DurationParserState state = DURATION_PARSER_STATE_INITIAL;
|
|
Duration d;
|
|
d.seconds = 0;
|
|
d.hours = 0;
|
|
d.minutes = 0;
|
|
char numBuf[32] = "0";
|
|
for (const char *c = duration; *c; c++) {
|
|
if (state == DURATION_PARSER_STATE_INITIAL) {
|
|
if (*c >= '0' && *c <= '9') {
|
|
state = DURATION_PARSER_STATE_NUMBER;
|
|
} else if (*c == 's' || *c == 'S') {
|
|
state = DURATION_PARSER_STATE_SECOND;
|
|
} else if (*c == 'm' || *c == 'M') {
|
|
state = DURATION_PARSER_STATE_MINUTE;
|
|
} else if (*c == 'h' || *c == 'H') {
|
|
state = DURATION_PARSER_STATE_HOUR;
|
|
}
|
|
}
|
|
if (state == DURATION_PARSER_STATE_NUMBER) {
|
|
const char *start = c;
|
|
while (*c >= '0' && *c <= '9') {
|
|
numBuf[c - start] = *c;
|
|
c++;
|
|
}
|
|
c--;
|
|
state = DURATION_PARSER_STATE_INITIAL;
|
|
} else if (state == DURATION_PARSER_STATE_SECOND) {
|
|
d.seconds = atoi(numBuf);
|
|
strncpy(numBuf, "0", 32);
|
|
state = DURATION_PARSER_STATE_INITIAL;
|
|
} else if (state == DURATION_PARSER_STATE_MINUTE) {
|
|
d.minutes = atoi(numBuf);
|
|
strncpy(numBuf, "0", 32);
|
|
state = DURATION_PARSER_STATE_INITIAL;
|
|
} else if (state == DURATION_PARSER_STATE_HOUR) {
|
|
d.hours = atoi(numBuf);
|
|
strncpy(numBuf, "0", 32);
|
|
state = DURATION_PARSER_STATE_INITIAL;
|
|
}
|
|
}
|
|
return d;
|
|
}
|
|
|
|
unsigned long durationToSeconds(const Duration *d) {
|
|
return d->hours * 3600 + d->minutes * 60 + d->seconds;
|
|
}
|
|
|
|
Duration secondsToDuration(unsigned long seconds) {
|
|
Duration d;
|
|
d.hours = seconds / 3600;
|
|
d.minutes = (seconds % 3600) / 60;
|
|
d.seconds = seconds % 60;
|
|
return d;
|
|
}
|
|
|
|
char* formatDuration(const Duration *d) {
|
|
char buf[32];
|
|
sprintf(buf, "%02lu:%02lu:%02lu", d->hours, d->minutes, d->seconds);
|
|
return strdup(buf);
|
|
}
|