#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "commp_util.h"
int
commp_skip_white_space(const char **begin, const char *end)
{
while (*begin < end) {
if (!isspace(**begin))
return (0);
(*begin)++;
}
return (1);
}
int
commp_find_token(const char **begin, const char **current, const char *end,
char token, boolean_t last)
{
*current = *begin;
while (*current < end) {
if (!last && (**current == token))
break;
else if (isspace(**current))
return (1);
(*current)++;
}
if (*current == *begin)
return (1);
else
return (0);
}
int
commp_atoi(const char *begin, const char *end, int *num)
{
boolean_t num_found = B_FALSE;
*num = 0;
while (begin < end) {
if (isdigit(*begin)) {
*num = (*num * 10) + (*begin - '0');
num_found = B_TRUE;
begin++;
} else {
break;
}
}
if (!num_found || (begin != end))
return (EINVAL);
return (0);
}
int
commp_strtoull(const char *begin, const char *end, uint64_t *num)
{
boolean_t num_found = B_FALSE;
*num = 0;
while (begin < end) {
if (isdigit(*begin)) {
*num = (*num * 10) + (*begin - '0');
num_found = B_TRUE;
begin++;
} else {
break;
}
}
if (!num_found || (begin != end))
return (EINVAL);
return (0);
}
int
commp_strtoub(const char *begin, const char *end, uint8_t *num)
{
boolean_t num_found = B_FALSE;
*num = 0;
while (begin < end) {
if (isdigit(*begin)) {
*num = (*num * 10) + (*begin - '0');
num_found = B_TRUE;
begin++;
} else {
break;
}
}
if (!num_found || (begin != end))
return (EINVAL);
return (0);
}
int
commp_atoui(const char *begin, const char *end, uint_t *num)
{
boolean_t num_found = B_FALSE;
*num = 0;
while (begin < end) {
if (isdigit(*begin)) {
*num = (*num * 10) + (*begin - '0');
num_found = B_TRUE;
begin++;
} else {
break;
}
}
if (!num_found || (begin != end))
return (EINVAL);
return (0);
}
int
commp_add_str(char **dest, const char *src, int len)
{
if (len == 0)
return (EINVAL);
(*dest) = calloc(1, len + 1);
if (*dest == NULL)
return (ENOMEM);
(void) strncpy(*dest, src, len);
return (0);
}
int
commp_time_to_secs(const char *begin, const char *end, uint64_t *num)
{
uint_t factor = 0;
if (!isdigit(*(end - 1))) {
switch (*(end - 1)) {
case 'd':
factor = COMMP_SECS_IN_DAY;
break;
case 'h':
factor = COMMP_SECS_IN_HOUR;
break;
case 'm':
factor = COMMP_SECS_IN_MIN;
break;
case 's':
factor = 1;
break;
default:
return (EINVAL);
}
--end;
}
if (commp_strtoull(begin, end, num) != 0)
return (EINVAL);
if (factor != 0)
(*num) = (*num) * factor;
return (0);
}