Blame gnulib-tests/dtotimespec.c

Packit Service fdd496
/* Convert double to timespec.
Packit Service fdd496
Packit Service fdd496
   Copyright (C) 2011-2017 Free Software Foundation, Inc.
Packit Service fdd496
Packit Service fdd496
   This program is free software: you can redistribute it and/or modify
Packit Service fdd496
   it under the terms of the GNU General Public License as published by
Packit Service fdd496
   the Free Software Foundation; either version 3 of the License, or
Packit Service fdd496
   (at your option) any later version.
Packit Service fdd496
Packit Service fdd496
   This program is distributed in the hope that it will be useful,
Packit Service fdd496
   but WITHOUT ANY WARRANTY; without even the implied warranty of
Packit Service fdd496
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
Packit Service fdd496
   GNU General Public License for more details.
Packit Service fdd496
Packit Service fdd496
   You should have received a copy of the GNU General Public License
Packit Service fdd496
   along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
Packit Service fdd496
Packit Service fdd496
/* written by Paul Eggert */
Packit Service fdd496
Packit Service fdd496
/* Convert the double value SEC to a struct timespec.  Round toward
Packit Service fdd496
   positive infinity.  On overflow, return an extremal value.  */
Packit Service fdd496
Packit Service fdd496
#include <config.h>
Packit Service fdd496
Packit Service fdd496
#include "timespec.h"
Packit Service fdd496
Packit Service fdd496
#include "intprops.h"
Packit Service fdd496
Packit Service fdd496
struct timespec
Packit Service fdd496
dtotimespec (double sec)
Packit Service fdd496
{
Packit Service fdd496
  if (! (TYPE_MINIMUM (time_t) < sec))
Packit Service fdd496
    return make_timespec (TYPE_MINIMUM (time_t), 0);
Packit Service fdd496
  else if (! (sec < 1.0 + TYPE_MAXIMUM (time_t)))
Packit Service fdd496
    return make_timespec (TYPE_MAXIMUM (time_t), TIMESPEC_RESOLUTION - 1);
Packit Service fdd496
  else
Packit Service fdd496
    {
Packit Service fdd496
      time_t s = sec;
Packit Service fdd496
      double frac = TIMESPEC_RESOLUTION * (sec - s);
Packit Service fdd496
      long ns = frac;
Packit Service fdd496
      ns += ns < frac;
Packit Service fdd496
      s += ns / TIMESPEC_RESOLUTION;
Packit Service fdd496
      ns %= TIMESPEC_RESOLUTION;
Packit Service fdd496
Packit Service fdd496
      if (ns < 0)
Packit Service fdd496
        {
Packit Service fdd496
          s--;
Packit Service fdd496
          ns += TIMESPEC_RESOLUTION;
Packit Service fdd496
        }
Packit Service fdd496
Packit Service fdd496
      return make_timespec (s, ns);
Packit Service fdd496
    }
Packit Service fdd496
}