2012-06-22 21:26:37 +00:00
|
|
|
/* Add two struct timespec values.
|
|
|
|
|
2018-01-01 01:19:57 +00:00
|
|
|
Copyright (C) 2011-2018 Free Software Foundation, Inc.
|
2012-06-22 21:26:37 +00:00
|
|
|
|
|
|
|
This program is free software: you can redistribute it and/or modify
|
|
|
|
it under the terms of the GNU General Public License as published by
|
|
|
|
the Free Software Foundation; either version 3 of the License, or
|
|
|
|
(at your option) any later version.
|
|
|
|
|
|
|
|
This program is distributed in the hope that it will be useful,
|
|
|
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
GNU General Public License for more details.
|
|
|
|
|
|
|
|
You should have received a copy of the GNU General Public License
|
2017-09-13 09:07:03 +00:00
|
|
|
along with this program. If not, see <https://www.gnu.org/licenses/>. */
|
2012-06-22 21:26:37 +00:00
|
|
|
|
|
|
|
/* Written by Paul Eggert. */
|
|
|
|
|
|
|
|
/* Return the sum of two timespec values A and B. On overflow, return
|
2013-09-25 03:44:34 +00:00
|
|
|
an extremal value. This assumes 0 <= tv_nsec < TIMESPEC_RESOLUTION. */
|
2012-06-22 21:26:37 +00:00
|
|
|
|
|
|
|
#include <config.h>
|
|
|
|
#include "timespec.h"
|
|
|
|
|
|
|
|
#include "intprops.h"
|
|
|
|
|
|
|
|
struct timespec
|
|
|
|
timespec_add (struct timespec a, struct timespec b)
|
|
|
|
{
|
|
|
|
time_t rs = a.tv_sec;
|
|
|
|
time_t bs = b.tv_sec;
|
|
|
|
int ns = a.tv_nsec + b.tv_nsec;
|
2013-09-19 21:40:08 +00:00
|
|
|
int nsd = ns - TIMESPEC_RESOLUTION;
|
2012-06-22 21:26:37 +00:00
|
|
|
int rns = ns;
|
2015-11-08 07:36:45 +00:00
|
|
|
time_t tmin = TYPE_MINIMUM (time_t);
|
|
|
|
time_t tmax = TYPE_MAXIMUM (time_t);
|
2012-06-22 21:26:37 +00:00
|
|
|
|
|
|
|
if (0 <= nsd)
|
|
|
|
{
|
|
|
|
rns = nsd;
|
2015-11-08 07:36:45 +00:00
|
|
|
if (bs < tmax)
|
|
|
|
bs++;
|
|
|
|
else if (rs < 0)
|
2012-06-22 21:26:37 +00:00
|
|
|
rs++;
|
2015-11-08 07:36:45 +00:00
|
|
|
else
|
|
|
|
goto high_overflow;
|
2012-06-22 21:26:37 +00:00
|
|
|
}
|
|
|
|
|
2015-11-08 07:36:45 +00:00
|
|
|
/* INT_ADD_WRAPV is not appropriate since time_t might be unsigned.
|
|
|
|
In theory time_t might be narrower than int, so plain
|
|
|
|
INT_ADD_OVERFLOW does not suffice. */
|
|
|
|
if (! INT_ADD_OVERFLOW (rs, bs) && tmin <= rs + bs && rs + bs <= tmax)
|
|
|
|
rs += bs;
|
|
|
|
else
|
2012-06-22 21:26:37 +00:00
|
|
|
{
|
|
|
|
if (rs < 0)
|
|
|
|
{
|
2015-11-08 07:36:45 +00:00
|
|
|
rs = tmin;
|
2012-06-22 21:26:37 +00:00
|
|
|
rns = 0;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
high_overflow:
|
2015-11-08 07:36:45 +00:00
|
|
|
rs = tmax;
|
2013-09-25 03:44:34 +00:00
|
|
|
rns = TIMESPEC_RESOLUTION - 1;
|
2012-06-22 21:26:37 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-19 21:40:08 +00:00
|
|
|
return make_timespec (rs, rns);
|
2012-06-22 21:26:37 +00:00
|
|
|
}
|