#include <ctype.h>
#include <stdio.h>
#include <string.h>
#include <isc/buffer.h>
#include <isc/region.h>
#include <isc/util.h>
#include <dns/ttl.h>
#define RETERR(x) do { \
isc_result_t _r = (x); \
if (_r != ISC_R_SUCCESS) \
return (_r); \
} while (0)
static isc_result_t
ttlfmt(unsigned int t, const char *s, int verbose,
int space, isc_buffer_t *target)
{
char tmp[60];
unsigned int len;
isc_region_t region;
if (verbose)
len = snprintf(tmp, sizeof(tmp), "%s%u %s%s",
space ? " " : "",
t, s,
t == 1 ? "" : "s");
else
len = snprintf(tmp, sizeof(tmp), "%u%c", t, s[0]);
INSIST(len + 1 <= sizeof(tmp));
isc_buffer_availableregion(target, ®ion);
if (len > region.length)
return (ISC_R_NOSPACE);
memmove(region.base, tmp, len);
isc_buffer_add(target, len);
return (ISC_R_SUCCESS);
}
isc_result_t
dns_ttl_totext(uint32_t src, int verbose, isc_buffer_t *target) {
unsigned secs, mins, hours, days, weeks, x;
secs = src % 60; src /= 60;
mins = src % 60; src /= 60;
hours = src % 24; src /= 24;
days = src % 7; src /= 7;
weeks = src; src = 0;
POST(src);
x = 0;
if (weeks != 0) {
RETERR(ttlfmt(weeks, "week", verbose, (x > 0), target));
x++;
}
if (days != 0) {
RETERR(ttlfmt(days, "day", verbose, (x > 0), target));
x++;
}
if (hours != 0) {
RETERR(ttlfmt(hours, "hour", verbose, (x > 0), target));
x++;
}
if (mins != 0) {
RETERR(ttlfmt(mins, "minute", verbose, (x > 0), target));
x++;
}
if (secs != 0 ||
(weeks == 0 && days == 0 && hours == 0 && mins == 0)) {
RETERR(ttlfmt(secs, "second", verbose, (x > 0), target));
x++;
}
INSIST (x > 0);
if (x == 1 && !verbose) {
isc_region_t region;
isc_buffer_usedregion(target, ®ion);
region.base[region.length - 1] =
toupper(region.base[region.length - 1]);
}
return (ISC_R_SUCCESS);
}