timefns.c 64.9 KB
Newer Older
1 2
/* Timestamp functions for Emacs

Paul Eggert's avatar
Paul Eggert committed
3
Copyright (C) 1985-1987, 1989, 1993-2020 Free Software Foundation, Inc.
4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

This file is part of GNU Emacs.

GNU Emacs 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.

GNU Emacs 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
along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.  */

#include <config.h>

#include "systime.h"

#include "blockinput.h"
25
#include "bignum.h"
26 27
#include "coding.h"
#include "lisp.h"
Daniel Colascione's avatar
Daniel Colascione committed
28
#include "pdumper.h"
29 30 31 32

#include <strftime.h>

#include <errno.h>
33
#include <limits.h>
34 35 36 37 38 39 40 41 42 43 44 45 46 47
#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#ifdef HAVE_TIMEZONE_T
# include <sys/param.h>
# if defined __NetBSD_Version__ && __NetBSD_Version__ < 700000000
#  define HAVE_TZALLOC_BUG true
# endif
#endif
#ifndef HAVE_TZALLOC_BUG
# define HAVE_TZALLOC_BUG false
#endif

Paul Eggert's avatar
Paul Eggert committed
48
enum { TM_YEAR_BASE = 1900 };
49 50 51 52 53 54 55 56 57 58 59 60

#ifndef HAVE_TM_GMTOFF
# define HAVE_TM_GMTOFF false
#endif

#ifndef TIME_T_MIN
# define TIME_T_MIN TYPE_MINIMUM (time_t)
#endif
#ifndef TIME_T_MAX
# define TIME_T_MAX TYPE_MAXIMUM (time_t)
#endif

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
/* Compile with -DFASTER_TIMEFNS=0 to disable common optimizations and
   allow easier testing of some slow-path code.  */
#ifndef FASTER_TIMEFNS
# define FASTER_TIMEFNS 1
#endif

/* Whether to warn about Lisp timestamps (TICKS . HZ) that may be
   instances of obsolete-format timestamps (HI . LO) where HI is
   the high-order bits and LO the low-order 16 bits.  Currently this
   is true, but it should change to false in a future version of
   Emacs.  Compile with -DWARN_OBSOLETE_TIMESTAMPS=0 to see what the
   future will be like.  */
#ifndef WARN_OBSOLETE_TIMESTAMPS
enum { WARN_OBSOLETE_TIMESTAMPS = true };
#endif

/* Although current-time etc. generate list-format timestamps
   (HI LO US PS), the plan is to change these functions to generate
   frequency-based timestamps (TICKS . HZ) in a future release.
   To try this now, compile with -DCURRENT_TIME_LIST=0.  */
#ifndef CURRENT_TIME_LIST
enum { CURRENT_TIME_LIST = true };
#endif

#if FIXNUM_OVERFLOW_P (1000000000)
static Lisp_Object timespec_hz;
#else
# define timespec_hz make_fixnum (TIMESPEC_HZ)
#endif

#define TRILLION 1000000000000
#if FIXNUM_OVERFLOW_P (TRILLION)
static Lisp_Object trillion;
94
# define ztrillion (*xbignum_val (trillion))
95 96 97 98 99 100 101
#else
# define trillion make_fixnum (TRILLION)
# if ULONG_MAX < TRILLION || !FASTER_TIMEFNS
mpz_t ztrillion;
# endif
#endif

102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
/* True if the nonzero Lisp integer HZ divides evenly into a trillion.  */
static bool
trillion_factor (Lisp_Object hz)
{
  if (FASTER_TIMEFNS)
    {
      if (FIXNUMP (hz))
	return TRILLION % XFIXNUM (hz) == 0;
      if (!FIXNUM_OVERFLOW_P (TRILLION))
	return false;
    }
  verify (TRILLION <= INTMAX_MAX);
  intmax_t ihz;
  return integer_to_intmax (hz, &ihz) && TRILLION % ihz == 0;
}

118 119 120 121 122 123 124 125 126 127 128 129 130 131
/* Return a struct timeval that is roughly equivalent to T.
   Use the least timeval not less than T.
   Return an extremal value if the result would overflow.  */
struct timeval
make_timeval (struct timespec t)
{
  struct timeval tv;
  tv.tv_sec = t.tv_sec;
  tv.tv_usec = t.tv_nsec / 1000;

  if (t.tv_nsec % 1000 != 0)
    {
      if (tv.tv_usec < 999999)
	tv.tv_usec++;
132
      else if (tv.tv_sec < TIME_T_MAX)
133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
	{
	  tv.tv_sec++;
	  tv.tv_usec = 0;
	}
    }

  return tv;
}

/* Yield A's UTC offset, or an unspecified value if unknown.  */
static long int
tm_gmtoff (struct tm *a)
{
#if HAVE_TM_GMTOFF
  return a->tm_gmtoff;
#else
  return 0;
#endif
}

/* Yield A - B, measured in seconds.
   This function is copied from the GNU C Library.  */
static int
tm_diff (struct tm *a, struct tm *b)
{
  /* Compute intervening leap days correctly even if year is negative.
     Take care to avoid int overflow in leap day calculations,
     but it's OK to assume that A and B are close to each other.  */
  int a4 = (a->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (a->tm_year & 3);
  int b4 = (b->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (b->tm_year & 3);
  int a100 = a4 / 25 - (a4 % 25 < 0);
  int b100 = b4 / 25 - (b4 % 25 < 0);
  int a400 = a100 >> 2;
  int b400 = b100 >> 2;
  int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
  int years = a->tm_year - b->tm_year;
  int days = (365 * years + intervening_leap_days
	      + (a->tm_yday - b->tm_yday));
  return (60 * (60 * (24 * days + (a->tm_hour - b->tm_hour))
		+ (a->tm_min - b->tm_min))
	  + (a->tm_sec - b->tm_sec));
}

enum { tzeqlen = sizeof "TZ=" - 1 };

/* Time zones equivalent to current local time and to UTC, respectively.  */
static timezone_t local_tz;
static timezone_t const utc_tz = 0;

static struct tm *
emacs_localtime_rz (timezone_t tz, time_t const *t, struct tm *tm)
{
  tm = localtime_rz (tz, t, tm);
  if (!tm && errno == ENOMEM)
    memory_full (SIZE_MAX);
  return tm;
}

191
static AVOID
192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
invalid_time_zone_specification (Lisp_Object zone)
{
  xsignal2 (Qerror, build_string ("Invalid time zone specification"), zone);
}

/* Free a timezone, except do not free the time zone for local time.
   Freeing utc_tz is also a no-op.  */
static void
xtzfree (timezone_t tz)
{
  if (tz != local_tz)
    tzfree (tz);
}

/* Convert the Lisp time zone rule ZONE to a timezone_t object.
   The returned value either is 0, or is LOCAL_TZ, or is newly allocated.
   If SETTZ, set Emacs local time to the time zone rule; otherwise,
   the caller should eventually pass the returned value to xtzfree.  */
static timezone_t
tzlookup (Lisp_Object zone, bool settz)
{
  static char const tzbuf_format[] = "<%+.*"pI"d>%s%"pI"d:%02d:%02d";
  char const *trailing_tzbuf_format = tzbuf_format + sizeof "<%+.*"pI"d" - 1;
  char tzbuf[sizeof tzbuf_format + 2 * INT_STRLEN_BOUND (EMACS_INT)];
  char const *zone_string;
  timezone_t new_tz;

  if (NILP (zone))
    return local_tz;
  else if (EQ (zone, Qt) || EQ (zone, make_fixnum (0)))
    {
      zone_string = "UTC0";
      new_tz = utc_tz;
    }
  else
    {
      bool plain_integer = FIXNUMP (zone);

      if (EQ (zone, Qwall))
	zone_string = 0;
      else if (STRINGP (zone))
	zone_string = SSDATA (ENCODE_SYSTEM (zone));
      else if (plain_integer || (CONSP (zone) && FIXNUMP (XCAR (zone))
				 && CONSP (XCDR (zone))))
	{
	  Lisp_Object abbr UNINIT;
	  if (!plain_integer)
	    {
	      abbr = XCAR (XCDR (zone));
	      zone = XCAR (zone);
	    }

	  EMACS_INT abszone = eabs (XFIXNUM (zone)), hour = abszone / (60 * 60);
	  int hour_remainder = abszone % (60 * 60);
	  int min = hour_remainder / 60, sec = hour_remainder % 60;

	  if (plain_integer)
	    {
	      int prec = 2;
	      EMACS_INT numzone = hour;
	      if (hour_remainder != 0)
		{
		  prec += 2, numzone = 100 * numzone + min;
		  if (sec != 0)
		    prec += 2, numzone = 100 * numzone + sec;
		}
	      sprintf (tzbuf, tzbuf_format, prec,
		       XFIXNUM (zone) < 0 ? -numzone : numzone,
		       &"-"[XFIXNUM (zone) < 0], hour, min, sec);
	      zone_string = tzbuf;
	    }
	  else
	    {
	      AUTO_STRING (leading, "<");
	      AUTO_STRING_WITH_LEN (trailing, tzbuf,
				    sprintf (tzbuf, trailing_tzbuf_format,
					     &"-"[XFIXNUM (zone) < 0],
					     hour, min, sec));
	      zone_string = SSDATA (concat3 (leading, ENCODE_SYSTEM (abbr),
					     trailing));
	    }
	}
      else
	invalid_time_zone_specification (zone);

      new_tz = tzalloc (zone_string);

      if (HAVE_TZALLOC_BUG && !new_tz && errno != ENOMEM && plain_integer
	  && XFIXNUM (zone) % (60 * 60) == 0)
	{
	  /* tzalloc mishandles POSIX strings; fall back on tzdb if
	     possible (Bug#30738).  */
	  sprintf (tzbuf, "Etc/GMT%+"pI"d", - (XFIXNUM (zone) / (60 * 60)));
	  new_tz = tzalloc (zone_string);
	}

      if (!new_tz)
	{
	  if (errno == ENOMEM)
	    memory_full (SIZE_MAX);
	  invalid_time_zone_specification (zone);
	}
    }

  if (settz)
    {
      block_input ();
      emacs_setenv_TZ (zone_string);
      tzset ();
      timezone_t old_tz = local_tz;
      local_tz = new_tz;
      tzfree (old_tz);
      unblock_input ();
    }

  return new_tz;
}

void
Daniel Colascione's avatar
Daniel Colascione committed
311
init_timefns (void)
312
{
313
#ifdef HAVE_UNEXEC
314 315 316 317 318 319
  /* A valid but unlikely setting for the TZ environment variable.
     It is OK (though a bit slower) if the user chooses this value.  */
  static char dump_tz_string[] = "TZ=UtC0";

  /* When just dumping out, set the time zone to a known unlikely value
     and skip the rest of this function.  */
Daniel Colascione's avatar
Daniel Colascione committed
320
  if (will_dump_with_unexec_p ())
321 322 323 324 325 326 327 328 329
    {
      xputenv (dump_tz_string);
      tzset ();
      return;
    }
#endif

  char *tz = getenv ("TZ");

330
#ifdef HAVE_UNEXEC
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
  /* If the execution TZ happens to be the same as the dump TZ,
     change it to some other value and then change it back,
     to force the underlying implementation to reload the TZ info.
     This is needed on implementations that load TZ info from files,
     since the TZ file contents may differ between dump and execution.  */
  if (tz && strcmp (tz, &dump_tz_string[tzeqlen]) == 0)
    {
      ++*tz;
      tzset ();
      --*tz;
    }
#endif

  /* Set the time zone rule now, so that the call to putenv is done
     before multiple threads are active.  */
  tzlookup (tz ? build_string (tz) : Qwall, true);
}

/* Report that a time value is out of range for Emacs.  */
void
time_overflow (void)
{
  error ("Specified time is not representable");
}

356
static AVOID
Paul Eggert's avatar
Paul Eggert committed
357
time_error (int err)
358
{
Paul Eggert's avatar
Paul Eggert committed
359 360 361 362 363 364
  switch (err)
    {
    case ENOMEM: memory_full (SIZE_MAX);
    case EOVERFLOW: time_overflow ();
    default: error ("Invalid time specification");
    }
365 366
}

367
static AVOID
368
invalid_hz (Lisp_Object hz)
369
{
370
  xsignal2 (Qerror, build_string ("Invalid time frequency"), hz);
371 372 373
}

/* Return the upper part of the time T (everything but the bottom 16 bits).  */
374
static Lisp_Object
375 376
hi_time (time_t t)
{
377
  return INT_TO_INTEGER (t >> LO_TIME_BITS);
378 379 380
}

/* Return the bottom bits of the time T.  */
381
static Lisp_Object
382 383
lo_time (time_t t)
{
384
  return make_fixnum (t & ((1 << LO_TIME_BITS) - 1));
385 386
}

387 388 389 390 391 392 393 394 395
/* When converting a double to a fraction TICKS / HZ, HZ is equal to
   FLT_RADIX * P where 0 <= P < FLT_RADIX_POWER_SIZE.  The tiniest
   nonzero double uses the maximum P.  */
enum { flt_radix_power_size = DBL_MANT_DIG - DBL_MIN_EXP + 1 };

/* A integer vector of size flt_radix_power_size.  The Pth entry
   equals FLT_RADIX**P.  */
static Lisp_Object flt_radix_power;

396
/* Convert T into an Emacs time *RESULT, truncating toward minus infinity.
Paul Eggert's avatar
Paul Eggert committed
397 398
   Return zero if successful, an error number otherwise.  */
static int
399 400
decode_float_time (double t, struct lisp_time *result)
{
401 402 403 404 405 406 407 408
  Lisp_Object ticks, hz;
  if (t == 0)
    {
      ticks = make_fixnum (0);
      hz = make_fixnum (1);
    }
  else
    {
Paul Eggert's avatar
Paul Eggert committed
409 410 411
      int scale = double_integer_scale (t);

      if (scale < 0)
412 413 414 415 416 417 418 419 420
	{
	 /* T is finite but so large that HZ would be less than 1 if
	    T's precision were represented exactly.  SCALE must be
	    nonnegative, as the (TICKS . HZ) representation requires
	    HZ to be at least 1.  So use SCALE = 0, which converts T to
	    (T . 1), which is the exact numeric value with too-large HZ,
	    which is typically better than signaling overflow.  */
	  scale = 0;
	}
Paul Eggert's avatar
Paul Eggert committed
421 422
      else if (flt_radix_power_size <= scale)
	return isnan (t) ? EDOM : EOVERFLOW;
423

Paul Eggert's avatar
Paul Eggert committed
424 425 426
      /* Compute TICKS, HZ such that TICKS / HZ exactly equals T, where HZ is
	 T's frequency or 1, whichever is greater.  Here, “frequency” means
	 1/precision.  Cache HZ values in flt_radix_power.  */
427 428 429 430 431 432 433 434 435 436 437 438 439
      double scaled = scalbn (t, scale);
      eassert (trunc (scaled) == scaled);
      ticks = double_to_integer (scaled);
      hz = AREF (flt_radix_power, scale);
      if (NILP (hz))
	{
	  mpz_ui_pow_ui (mpz[0], FLT_RADIX, scale);
	  hz = make_integer_mpz ();
	  ASET (flt_radix_power, scale, hz);
	}
    }
  result->ticks = ticks;
  result->hz = hz;
Paul Eggert's avatar
Paul Eggert committed
440
  return 0;
441 442 443 444 445 446 447
}

/* Make a 4-element timestamp (HI LO US PS) from TICKS and HZ.
   Drop any excess precision.  */
static Lisp_Object
ticks_hz_list4 (Lisp_Object ticks, Lisp_Object hz)
{
Paul Eggert's avatar
Paul Eggert committed
448
  /* mpz[0] = floor ((ticks * trillion) / hz).  */
449
  mpz_t const *zticks = bignum_integer (&mpz[0], ticks);
450 451 452 453 454 455
#if FASTER_TIMEFNS && TRILLION <= ULONG_MAX
  mpz_mul_ui (mpz[0], *zticks, TRILLION);
#else
  mpz_mul (mpz[0], *zticks, ztrillion);
#endif
  mpz_fdiv_q (mpz[0], mpz[0], *bignum_integer (&mpz[1], hz));
Paul Eggert's avatar
Paul Eggert committed
456 457 458

  /* mpz[0] = floor (mpz[0] / trillion), with US = the high six digits of the
     12-digit remainder, and PS = the low six digits.  */
459 460 461 462 463 464 465 466 467
#if FASTER_TIMEFNS && TRILLION <= ULONG_MAX
  unsigned long int fullps = mpz_fdiv_q_ui (mpz[0], mpz[0], TRILLION);
  int us = fullps / 1000000;
  int ps = fullps % 1000000;
#else
  mpz_fdiv_qr (mpz[0], mpz[1], mpz[0], ztrillion);
  int ps = mpz_fdiv_q_ui (mpz[1], mpz[1], 1000000);
  int us = mpz_get_ui (mpz[1]);
#endif
Paul Eggert's avatar
Paul Eggert committed
468 469

  /* mpz[0] = floor (mpz[0] / 1 << LO_TIME_BITS), with lo = remainder.  */
470 471 472 473 474
  unsigned long ulo = mpz_get_ui (mpz[0]);
  if (mpz_sgn (mpz[0]) < 0)
    ulo = -ulo;
  int lo = ulo & ((1 << LO_TIME_BITS) - 1);
  mpz_fdiv_q_2exp (mpz[0], mpz[0], LO_TIME_BITS);
Paul Eggert's avatar
Paul Eggert committed
475

476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
  return list4 (make_integer_mpz (), make_fixnum (lo),
		make_fixnum (us), make_fixnum (ps));
}

/* Set ROP to T.  */
static void
mpz_set_time (mpz_t rop, time_t t)
{
  if (EXPR_SIGNED (t))
    mpz_set_intmax (rop, t);
  else
    mpz_set_uintmax (rop, t);
}

/* Store into mpz[0] a clock tick count for T, assuming a
   TIMESPEC_HZ-frequency clock.  Use mpz[1] as a temp.  */
static void
timespec_mpz (struct timespec t)
{
Paul Eggert's avatar
Paul Eggert committed
495
  /* mpz[0] = sec * TIMESPEC_HZ + nsec.  */
496 497 498 499 500 501 502 503 504
  mpz_set_ui (mpz[0], t.tv_nsec);
  mpz_set_time (mpz[1], t.tv_sec);
  mpz_addmul_ui (mpz[0], mpz[1], TIMESPEC_HZ);
}

/* Convert T to a Lisp integer counting TIMESPEC_HZ ticks.  */
static Lisp_Object
timespec_ticks (struct timespec t)
{
Paul Eggert's avatar
Paul Eggert committed
505
  /* For speed, use intmax_t arithmetic if it will do.  */
506 507 508 509 510
  intmax_t accum;
  if (FASTER_TIMEFNS
      && !INT_MULTIPLY_WRAPV (t.tv_sec, TIMESPEC_HZ, &accum)
      && !INT_ADD_WRAPV (t.tv_nsec, accum, &accum))
    return make_int (accum);
Paul Eggert's avatar
Paul Eggert committed
511 512

  /* Fall back on bignum arithmetic.  */
513 514 515 516 517 518 519 520 521
  timespec_mpz (t);
  return make_integer_mpz ();
}

/* Convert T to a Lisp integer counting HZ ticks, taking the floor.
   Assume T is valid, but check HZ.  */
static Lisp_Object
lisp_time_hz_ticks (struct lisp_time t, Lisp_Object hz)
{
Paul Eggert's avatar
Paul Eggert committed
522 523 524
  /* The idea is to return the floor of ((T.ticks * HZ) / T.hz).  */

  /* For speed, just return T.ticks if T.hz == HZ.  */
525 526
  if (FASTER_TIMEFNS && EQ (t.hz, hz))
    return t.ticks;
Paul Eggert's avatar
Paul Eggert committed
527 528

  /* Check HZ for validity.  */
529 530 531 532
  if (FIXNUMP (hz))
    {
      if (XFIXNUM (hz) <= 0)
	invalid_hz (hz);
Paul Eggert's avatar
Paul Eggert committed
533 534

      /* For speed, use intmax_t arithmetic if it will do.  */
535 536 537 538 539 540
      intmax_t ticks;
      if (FASTER_TIMEFNS && FIXNUMP (t.ticks) && FIXNUMP (t.hz)
	  && !INT_MULTIPLY_WRAPV (XFIXNUM (t.ticks), XFIXNUM (hz), &ticks))
	return make_int (ticks / XFIXNUM (t.hz)
			 - (ticks % XFIXNUM (t.hz) < 0));
    }
541
  else if (! (BIGNUMP (hz) && 0 < mpz_sgn (*xbignum_val (hz))))
542 543
    invalid_hz (hz);

Paul Eggert's avatar
Paul Eggert committed
544
  /* Fall back on bignum arithmetic.  */
545 546 547 548 549 550 551 552 553 554 555
  mpz_mul (mpz[0],
	   *bignum_integer (&mpz[0], t.ticks),
	   *bignum_integer (&mpz[1], hz));
  mpz_fdiv_q (mpz[0], mpz[0], *bignum_integer (&mpz[1], t.hz));
  return make_integer_mpz ();
}

/* Convert T to a Lisp integer counting seconds, taking the floor.  */
static Lisp_Object
lisp_time_seconds (struct lisp_time t)
{
Paul Eggert's avatar
Paul Eggert committed
556 557
  /* The idea is to return the floor of T.ticks / T.hz.  */

558 559
  if (!FASTER_TIMEFNS)
    return lisp_time_hz_ticks (t, make_fixnum (1));
Paul Eggert's avatar
Paul Eggert committed
560 561

  /* For speed, use EMACS_INT arithmetic if it will do.  */
562 563 564
  if (FIXNUMP (t.ticks) && FIXNUMP (t.hz))
    return make_fixnum (XFIXNUM (t.ticks) / XFIXNUM (t.hz)
			- (XFIXNUM (t.ticks) % XFIXNUM (t.hz) < 0));
Paul Eggert's avatar
Paul Eggert committed
565 566

  /* For speed, inline what lisp_time_hz_ticks would do.  */
567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
  mpz_fdiv_q (mpz[0],
	      *bignum_integer (&mpz[0], t.ticks),
	      *bignum_integer (&mpz[1], t.hz));
  return make_integer_mpz ();
}

/* Convert T to a Lisp timestamp.  */
Lisp_Object
make_lisp_time (struct timespec t)
{
  if (CURRENT_TIME_LIST)
    {
      time_t s = t.tv_sec;
      int ns = t.tv_nsec;
      return list4 (hi_time (s), lo_time (s),
		    make_fixnum (ns / 1000), make_fixnum (ns % 1000 * 1000));
    }
  else
585 586 587 588
    return timespec_to_lisp (t);
}

/* Return (TICKS . HZ) for time T.  */
Eli Zaretskii's avatar
Eli Zaretskii committed
589
Lisp_Object
590 591 592
timespec_to_lisp (struct timespec t)
{
  return Fcons (timespec_ticks (t), timespec_hz);
593 594
}

595
/* Return NUMERATOR / DENOMINATOR, rounded to the nearest double.
596
   Arguments must be Lisp integers, and DENOMINATOR must be positive.  */
597 598 599
static double
frac_to_double (Lisp_Object numerator, Lisp_Object denominator)
{
Paul Eggert's avatar
Paul Eggert committed
600 601 602 603 604 605
  intmax_t intmax_numerator, intmax_denominator;
  if (FASTER_TIMEFNS
      && integer_to_intmax (numerator, &intmax_numerator)
      && integer_to_intmax (denominator, &intmax_denominator)
      && intmax_numerator % intmax_denominator == 0)
    return intmax_numerator / intmax_denominator;
606

Paul Eggert's avatar
Paul Eggert committed
607
  /* Compute number of base-FLT_RADIX digits in numerator and denominator.  */
608 609
  mpz_t const *n = bignum_integer (&mpz[0], numerator);
  mpz_t const *d = bignum_integer (&mpz[1], denominator);
610 611
  ptrdiff_t ndig = mpz_sizeinbase (*n, FLT_RADIX);
  ptrdiff_t ddig = mpz_sizeinbase (*d, FLT_RADIX);
612 613 614 615

  /* Scale with SCALE when doing integer division.  That is, compute
     (N * FLT_RADIX**SCALE) / D [or, if SCALE is negative, N / (D *
     FLT_RADIX**-SCALE)] as a bignum, convert the bignum to double,
Paul Eggert's avatar
Paul Eggert committed
616
     then divide the double by FLT_RADIX**SCALE.  First scale N
617
     (or scale D, if SCALE is negative) ...  */
618
  ptrdiff_t scale = ddig - ndig + DBL_MANT_DIG;
619 620 621 622 623 624 625 626 627 628 629 630 631
  if (scale < 0)
    {
      mpz_mul_2exp (mpz[1], *d, - (scale * LOG2_FLT_RADIX));
      d = &mpz[1];
    }
  else
    {
      /* min so we don't scale tiny numbers as if they were normalized.  */
      scale = min (scale, flt_radix_power_size - 1);

      mpz_mul_2exp (mpz[0], *n, scale * LOG2_FLT_RADIX);
      n = &mpz[0];
    }
Paul Eggert's avatar
Paul Eggert committed
632
  /* ... and then divide, with quotient Q and remainder R.  */
633 634 635 636
  mpz_t *q = &mpz[2];
  mpz_t *r = &mpz[3];
  mpz_tdiv_qr (*q, *r, *n, *d);

Paul Eggert's avatar
Paul Eggert committed
637
  /* The amount to add to the absolute value of Q so that truncating
638 639 640 641 642 643 644 645
     it to double will round correctly.  */
  int incr;

  /* Round the quotient before converting it to double.
     If the quotient is less than FLT_RADIX ** DBL_MANT_DIG,
     round to the nearest integer; otherwise, it is less than
     FLT_RADIX ** (DBL_MANT_DIG + 1) and round it to the nearest
     multiple of FLT_RADIX.  Break ties to even.  */
646
  if (mpz_sizeinbase (*q, FLT_RADIX) <= DBL_MANT_DIG)
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675
    {
      /* Converting to double will use the whole quotient so add 1 to
	 its absolute value as per round-to-even; i.e., if the doubled
	 remainder exceeds the denominator, or exactly equals the
	 denominator and adding 1 would make the quotient even.  */
      mpz_mul_2exp (*r, *r, 1);
      int cmp = mpz_cmpabs (*r, *d);
      incr = cmp > 0 || (cmp == 0 && (FASTER_TIMEFNS && FLT_RADIX == 2
				      ? mpz_odd_p (*q)
				      : mpz_tdiv_ui (*q, FLT_RADIX) & 1));
    }
  else
    {
      /* Converting to double will discard the quotient's low-order digit,
	 so add FLT_RADIX to its absolute value as per round-to-even.  */
      int lo_2digits = mpz_tdiv_ui (*q, FLT_RADIX * FLT_RADIX);
      eassume (0 <= lo_2digits && lo_2digits < FLT_RADIX * FLT_RADIX);
      int lo_digit = lo_2digits % FLT_RADIX;
      incr = ((lo_digit > FLT_RADIX / 2
	       || (lo_digit == FLT_RADIX / 2 && FLT_RADIX % 2 == 0
		   && ((lo_2digits / FLT_RADIX) & 1
		       || mpz_sgn (*r) != 0)))
	      ? FLT_RADIX : 0);
    }

  /* Increment the absolute value of the quotient by INCR.  */
  if (!FASTER_TIMEFNS || incr != 0)
    (mpz_sgn (*n) < 0 ? mpz_sub_ui : mpz_add_ui) (*q, *q, incr);

Paul Eggert's avatar
Paul Eggert committed
676
  /* Rescale the integer Q back to double.  This step does not round.  */
677 678 679 680 681
  return scalbn (mpz_get_d (*q), -scale);
}

/* From a valid timestamp (TICKS . HZ), generate the corresponding
   time values.
682 683 684

   If RESULT is not null, store into *RESULT the converted time.
   Otherwise, store into *DRESULT the number of seconds since the
685
   start of the POSIX Epoch.
686

687
   Return zero, which indicates success.  */
Paul Eggert's avatar
Paul Eggert committed
688
static int
689 690 691 692 693 694 695 696 697
decode_ticks_hz (Lisp_Object ticks, Lisp_Object hz,
		 struct lisp_time *result, double *dresult)
{
  if (result)
    {
      result->ticks = ticks;
      result->hz = hz;
    }
  else
698
    *dresult = frac_to_double (ticks, hz);
Paul Eggert's avatar
Paul Eggert committed
699
  return 0;
700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
}

/* Lisp timestamp classification.  */
enum timeform
  {
   TIMEFORM_INVALID = 0,
   TIMEFORM_HI_LO, /* seconds in the form (HI << LO_TIME_BITS) + LO.  */
   TIMEFORM_HI_LO_US, /* seconds plus microseconds (HI LO US) */
   TIMEFORM_NIL, /* current time in nanoseconds */
   TIMEFORM_HI_LO_US_PS, /* seconds plus micro and picoseconds (HI LO US PS) */
   TIMEFORM_FLOAT, /* time as a float */
   TIMEFORM_TICKS_HZ /* fractional time: HI is ticks, LO is ticks per second */
  };

/* From the valid form FORM and the time components HIGH, LOW, USEC
   and PSEC, generate the corresponding time value.  If LOW is
   floating point, the other components should be zero and FORM should
   not be TIMEFORM_TICKS_HZ.

   If RESULT is not null, store into *RESULT the converted time.
   Otherwise, store into *DRESULT the number of seconds since the
   start of the POSIX Epoch.  Unsuccessful calls may or may not store
   results.

Paul Eggert's avatar
Paul Eggert committed
724 725
   Return zero if successful, an error number otherwise.  */
static int
726 727 728 729 730 731 732 733
decode_time_components (enum timeform form,
			Lisp_Object high, Lisp_Object low,
			Lisp_Object usec, Lisp_Object psec,
			struct lisp_time *result, double *dresult)
{
  switch (form)
    {
    case TIMEFORM_INVALID:
Paul Eggert's avatar
Paul Eggert committed
734
      return EINVAL;
735 736

    case TIMEFORM_TICKS_HZ:
737 738 739 740
      if (INTEGERP (high)
	  && (!NILP (Fnatnump (low)) && !EQ (low, make_fixnum (0))))
	return decode_ticks_hz (high, low, result, dresult);
      return EINVAL;
741 742 743 744 745 746 747 748 749

    case TIMEFORM_FLOAT:
      {
	double t = XFLOAT_DATA (low);
	if (result)
	  return decode_float_time (t, result);
	else
	  {
	    *dresult = t;
Paul Eggert's avatar
Paul Eggert committed
750
	    return 0;
751 752 753 754
	  }
      }

    case TIMEFORM_NIL:
755 756
      return decode_ticks_hz (timespec_ticks (current_timespec ()),
			      timespec_hz, result, dresult);
757 758 759 760 761 762 763

    default:
      break;
    }

  if (! (INTEGERP (high) && INTEGERP (low)
	 && FIXNUMP (usec) && FIXNUMP (psec)))
Paul Eggert's avatar
Paul Eggert committed
764
    return EINVAL;
765 766 767 768 769 770
  EMACS_INT us = XFIXNUM (usec);
  EMACS_INT ps = XFIXNUM (psec);

  /* Normalize out-of-range lower-order components by carrying
     each overflow into the next higher-order component.  */
  us += ps / 1000000 - (ps % 1000000 < 0);
771 772 773 774
  mpz_t *s = &mpz[1];
  mpz_set_intmax (*s, us / 1000000 - (us % 1000000 < 0));
  mpz_add (*s, *s, *bignum_integer (&mpz[0], low));
  mpz_addmul_ui (*s, *bignum_integer (&mpz[0], high), 1 << LO_TIME_BITS);
775 776 777
  ps = ps % 1000000 + 1000000 * (ps % 1000000 < 0);
  us = us % 1000000 + 1000000 * (us % 1000000 < 0);

778 779
  Lisp_Object hz;
  switch (form)
780
    {
781 782 783 784 785
    case TIMEFORM_HI_LO:
      /* Floats and nil were handled above, so it was an integer.  */
      mpz_swap (mpz[0], *s);
      hz = make_fixnum (1);
      break;
786

787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809
    case TIMEFORM_HI_LO_US:
      mpz_set_ui (mpz[0], us);
      mpz_addmul_ui (mpz[0], *s, 1000000);
      hz = make_fixnum (1000000);
      break;

    case TIMEFORM_HI_LO_US_PS:
      {
	#if FASTER_TIMEFNS && TRILLION <= ULONG_MAX
	  unsigned long i = us;
	  mpz_set_ui (mpz[0], i * 1000000 + ps);
	  mpz_addmul_ui (mpz[0], *s, TRILLION);
	#else
	  intmax_t i = us;
	  mpz_set_intmax (mpz[0], i * 1000000 + ps);
	  mpz_addmul (mpz[0], *s, ztrillion);
	#endif
	hz = trillion;
      }
      break;

    default:
      eassume (false);
810 811
    }

812
  return decode_ticks_hz (make_integer_mpz (), hz, result, dresult);
813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
}

enum { DECODE_SECS_ONLY = WARN_OBSOLETE_TIMESTAMPS + 1 };

/* Decode a Lisp timestamp SPECIFIED_TIME that represents a time.

   FLAGS specifies conversion flags.  If FLAGS & DECODE_SECS_ONLY,
   ignore and do not validate any sub-second components of an
   old-format SPECIFIED_TIME.  If FLAGS & WARN_OBSOLETE_TIMESTAMPS,
   diagnose what could be obsolete (HIGH . LOW) timestamps.

   If RESULT is not null, store into *RESULT the converted time;
   otherwise, store into *DRESULT the number of seconds since the
   start of the POSIX Epoch.  Unsuccessful calls may or may not store
   results.

Paul Eggert's avatar
Paul Eggert committed
829 830
   Return the form of SPECIFIED-TIME.  Signal an error if unsuccessful.  */
static enum timeform
831 832
decode_lisp_time (Lisp_Object specified_time, int flags,
		  struct lisp_time *result, double *dresult)
833 834 835 836 837
{
  Lisp_Object high = make_fixnum (0);
  Lisp_Object low = specified_time;
  Lisp_Object usec = make_fixnum (0);
  Lisp_Object psec = make_fixnum (0);
838
  enum timeform form = TIMEFORM_HI_LO;
839

840 841 842 843 844
  if (NILP (specified_time))
    form = TIMEFORM_NIL;
  else if (FLOATP (specified_time))
    form = TIMEFORM_FLOAT;
  else if (CONSP (specified_time))
845 846 847 848 849 850 851
    {
      high = XCAR (specified_time);
      low = XCDR (specified_time);
      if (CONSP (low))
	{
	  Lisp_Object low_tail = XCDR (low);
	  low = XCAR (low);
852
	  if (! (flags & DECODE_SECS_ONLY))
853 854
	    {
	      if (CONSP (low_tail))
855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870
		{
		  usec = XCAR (low_tail);
		  low_tail = XCDR (low_tail);
		  if (CONSP (low_tail))
		    {
		      psec = XCAR (low_tail);
		      form = TIMEFORM_HI_LO_US_PS;
		    }
		  else
		    form = TIMEFORM_HI_LO_US;
		}
	      else if (!NILP (low_tail))
		{
		  usec = low_tail;
		  form = TIMEFORM_HI_LO_US;
		}
871 872 873
	    }
	}
      else
874 875 876 877 878 879
	{
	  if (flags & WARN_OBSOLETE_TIMESTAMPS
	      && RANGED_FIXNUMP (0, low, (1 << LO_TIME_BITS) - 1))
	    message ("obsolete timestamp with cdr %"pI"d", XFIXNUM (low));
	  form = TIMEFORM_TICKS_HZ;
	}
880

881 882
      /* Require LOW to be an integer, as otherwise the computation
	 would be considerably trickier.  */
883
      if (! INTEGERP (low))
884
	form = TIMEFORM_INVALID;
885
    }
886

Paul Eggert's avatar
Paul Eggert committed
887 888 889 890
  int err = decode_time_components (form, high, low, usec, psec,
				    result, dresult);
  if (err)
    time_error (err);
Paul Eggert's avatar
Paul Eggert committed
891
  return form;
892 893
}

894
/* Convert Z to time_t, returning true if it fits.  */
895
static bool
896
mpz_time (mpz_t const z, time_t *t)
897
{
898 899 900 901 902 903 904 905 906 907 908 909 910 911
  if (TYPE_SIGNED (time_t))
    {
      intmax_t i;
      if (! (mpz_to_intmax (z, &i) && TIME_T_MIN <= i && i <= TIME_T_MAX))
	return false;
      *t = i;
    }
  else
    {
      uintmax_t i;
      if (! (mpz_to_uintmax (z, &i) && i <= TIME_T_MAX))
	return false;
      *t = i;
    }
912 913 914
  return true;
}

915 916 917 918
/* Convert T to struct timespec, returning an invalid timespec
   if T does not fit.  */
static struct timespec
lisp_to_timespec (struct lisp_time t)
919
{
920 921 922
  struct timespec result = invalid_timespec ();
  int ns;
  mpz_t *q = &mpz[0];
923
  mpz_t const *qt = q;
924

Paul Eggert's avatar
Paul Eggert committed
925 926 927 928
  /* Floor-divide (T.ticks * TIMESPEC_HZ) by T.hz,
     yielding quotient Q (tv_sec) and remainder NS (tv_nsec).
     Return an invalid timespec if Q does not fit in time_t.
     For speed, prefer fixnum arithmetic if it works.  */
929
  if (FASTER_TIMEFNS && EQ (t.hz, timespec_hz))
930
    {
931
      if (FIXNUMP (t.ticks))
932
	{
933 934 935 936 937 938
	  EMACS_INT s = XFIXNUM (t.ticks) / TIMESPEC_HZ;
	  ns = XFIXNUM (t.ticks) % TIMESPEC_HZ;
	  if (ns < 0)
	    s--, ns += TIMESPEC_HZ;
	  if ((TYPE_SIGNED (time_t) ? TIME_T_MIN <= s : 0 <= s)
	      && s <= TIME_T_MAX)
939
	    {
940 941
	      result.tv_sec = s;
	      result.tv_nsec = ns;
942
	    }
943
	  return result;
944 945
	}
      else
946
	ns = mpz_fdiv_q_ui (*q, *xbignum_val (t.ticks), TIMESPEC_HZ);
947
    }
948
  else if (FASTER_TIMEFNS && EQ (t.hz, make_fixnum (1)))
949
    {
950 951 952 953 954 955 956 957 958 959 960 961 962
      ns = 0;
      if (FIXNUMP (t.ticks))
	{
	  EMACS_INT s = XFIXNUM (t.ticks);
	  if ((TYPE_SIGNED (time_t) ? TIME_T_MIN <= s : 0 <= s)
	      && s <= TIME_T_MAX)
	    {
	      result.tv_sec = s;
	      result.tv_nsec = ns;
	    }
	  return result;
	}
      else
963
	qt = xbignum_val (t.ticks);
964
    }
965
  else
966
    {
967 968 969
      mpz_mul_ui (*q, *bignum_integer (q, t.ticks), TIMESPEC_HZ);
      mpz_fdiv_q (*q, *q, *bignum_integer (&mpz[1], t.hz));
      ns = mpz_fdiv_q_ui (*q, *q, TIMESPEC_HZ);
970 971
    }

Paul Eggert's avatar
Paul Eggert committed
972 973
  /* Check that Q fits in time_t, not merely in T.tv_sec.  With some versions
     of MinGW, tv_sec is a 64-bit type, whereas time_t is a 32-bit type.  */
974
  time_t sec;
975
  if (mpz_time (*qt, &sec))
976 977 978 979
    {
      result.tv_sec = sec;
      result.tv_nsec = ns;
    }
980
  return result;
981 982
}

983 984 985 986 987 988
/* Convert (HIGH LOW USEC PSEC) to struct timespec.
   Return true if successful.  */
bool
list4_to_timespec (Lisp_Object high, Lisp_Object low,
		   Lisp_Object usec, Lisp_Object psec,
		   struct timespec *result)
989
{
990
  struct lisp_time t;
Paul Eggert's avatar
Paul Eggert committed
991 992
  if (decode_time_components (TIMEFORM_HI_LO_US_PS, high, low, usec, psec,
			      &t, 0))
993 994 995
    return false;
  *result = lisp_to_timespec (t);
  return timespec_valid_p (*result);
996 997 998 999
}

/* Decode a Lisp list SPECIFIED_TIME that represents a time.
   If SPECIFIED_TIME is nil, use the current time.
Paul Eggert's avatar
Paul Eggert committed
1000 1001
   Signal an error if SPECIFIED_TIME does not represent a time.
   If PFORM, store the time's form into *PFORM.  */
1002
static struct lisp_time
1003
lisp_time_struct (Lisp_Object specified_time, enum timeform *pform)
1004 1005
{
  struct lisp_time t;
Paul Eggert's avatar
Paul Eggert committed
1006 1007 1008 1009
  enum timeform form
    = decode_lisp_time (specified_time, WARN_OBSOLETE_TIMESTAMPS, &t, 0);
  if (pform)
    *pform = form;
1010 1011 1012
  return t;
}

1013 1014 1015 1016
/* Decode a Lisp list SPECIFIED_TIME that represents a time.
   Discard any low-order (sub-ns) resolution.
   If SPECIFIED_TIME is nil, use the current time.
   Signal an error if SPECIFIED_TIME does not represent a timespec.  */
1017 1018 1019
struct timespec
lisp_time_argument (Lisp_Object specified_time)
{
1020
  struct lisp_time lt = lisp_time_struct (specified_time, 0);
1021 1022 1023 1024 1025 1026
  struct timespec t = lisp_to_timespec (lt);
  if (! timespec_valid_p (t))
    time_overflow ();
  return t;
}

1027 1028
/* Like lisp_time_argument, except decode only the seconds part, and
   do not check the subseconds part.  */
1029 1030 1031
static time_t
lisp_seconds_argument (Lisp_Object specified_time)
{
1032 1033
  int flags = WARN_OBSOLETE_TIMESTAMPS | DECODE_SECS_ONLY;
  struct lisp_time lt;
Paul Eggert's avatar
Paul Eggert committed
1034
  decode_lisp_time (specified_time, flags, &lt, 0);
1035 1036 1037 1038
  struct timespec t = lisp_to_timespec (lt);
  if (! timespec_valid_p (t))
    time_overflow ();
  return t.tv_sec;
1039 1040
}

1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
/* Return the sum of the Lisp integers A and B.
   Subtract instead of adding if SUBTRACT.
   This function is tuned for small B.  */
static Lisp_Object
lispint_arith (Lisp_Object a, Lisp_Object b, bool subtract)
{
  bool mpz_done = false;

  if (FASTER_TIMEFNS && FIXNUMP (b))
    {
      if (EQ (b, make_fixnum (0)))
	return a;
Paul Eggert's avatar
Paul Eggert committed
1053 1054

      /* For speed, use EMACS_INT arithmetic if it will do.  */
1055 1056 1057 1058
      if (FIXNUMP (a))
	return make_int (subtract
			 ? XFIXNUM (a) - XFIXNUM (b)
			 : XFIXNUM (a) + XFIXNUM (b));
Paul Eggert's avatar
Paul Eggert committed
1059 1060

      /* For speed, use mpz_add_ui/mpz_sub_ui if it will do.  */
1061 1062 1063
      if (eabs (XFIXNUM (b)) <= ULONG_MAX)
	{
	  ((XFIXNUM (b) < 0) == subtract ? mpz_add_ui : mpz_sub_ui)
1064
	    (mpz[0], *xbignum_val (a), eabs (XFIXNUM (b)));
1065 1066 1067 1068
	  mpz_done = true;
	}
    }

Paul Eggert's avatar
Paul Eggert committed
1069
  /* Fall back on bignum arithmetic if necessary.  */
1070 1071 1072 1073 1074 1075 1076
  if (!mpz_done)
    (subtract ? mpz_sub : mpz_add) (mpz[0],
				    *bignum_integer (&mpz[0], a),
				    *bignum_integer (&mpz[1], b));
  return make_integer_mpz ();
}

1077
/* Given Lisp operands A and B, add their values, and return the
1078
   result as a Lisp timestamp.  Subtract instead of adding if SUBTRACT.  */
1079 1080 1081 1082 1083 1084 1085 1086 1087
static Lisp_Object
time_arith (Lisp_Object a, Lisp_Object b, bool subtract)
{
  if (FLOATP (a) && !isfinite (XFLOAT_DATA (a)))
    {
      double da = XFLOAT_DATA (a);
      double db = XFLOAT_DATA (Ffloat_time (b));
      return make_float (subtract ? da - db : da + db);
    }
1088 1089
  enum timeform aform, bform;
  struct lisp_time ta = lisp_time_struct (a, &aform);
1090

1091 1092 1093
  if (FLOATP (b) && !isfinite (XFLOAT_DATA (b)))
    return subtract ? make_float (-XFLOAT_DATA (b)) : b;

1094 1095 1096 1097 1098 1099 1100 1101 1102
  /* Subtract nil from nil correctly, and handle other eq values
     quicker while we're at it.  Compare here rather than earlier, to
     handle NaNs and check formats.  */
  struct lisp_time tb;
  if (EQ (a, b))
    bform = aform, tb = ta;
  else
    tb = lisp_time_struct (b, &bform);

1103
  Lisp_Object ticks, hz;
1104

1105
  if (FASTER_TIMEFNS && EQ (ta.hz, tb.hz))
1106
    {
1107
      hz = ta.hz;
1108
      ticks = lispint_arith (ta.ticks, tb.ticks, subtract);
1109 1110 1111 1112
    }
  else
    {
      /* The plan is to decompose ta into na/da and tb into nb/db.
1113 1114 1115
	 Start by computing da and db, their minimum (which will be
	 needed later) and the iticks temporary that will become
	 available once only their minimum is needed.  */
1116 1117
      mpz_t const *da = bignum_integer (&mpz[1], ta.hz);
      mpz_t const *db = bignum_integer (&mpz[2], tb.hz);
1118 1119 1120
      bool da_lt_db = mpz_cmp (*da, *db) < 0;
      mpz_t const *hzmin = da_lt_db ? da : db;
      mpz_t *iticks = &mpz[da_lt_db + 1];
1121 1122 1123 1124 1125 1126 1127

      /* The plan is to compute (na * (db/g) + nb * (da/g)) / lcm (da, db)
	 where g = gcd (da, db).  Start by computing g.  */
      mpz_t *g = &mpz[3];
      mpz_gcd (*g, *da, *db);

      /* fa = da/g, fb = db/g.  */
1128
      mpz_t *fa = &mpz[4], *fb = &mpz[3];
1129 1130
      mpz_divexact (*fa, *da, *g);
      mpz_divexact (*fb, *db, *g);
1131

1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152
      /* ihz = fa * db.  This is equal to lcm (da, db).  */
      mpz_t *ihz = &mpz[0];
      mpz_mul (*ihz, *fa, *db);

      /* When warning about obsolete timestamps, if the smaller
	 denominator comes from a non-(TICKS . HZ) timestamp and could
	 generate a (TICKS . HZ) timestamp that would look obsolete,
	 arrange for the result to have a higher HZ to avoid a
	 spurious warning by a later consumer of this function's
	 returned value.  */
      verify (1 << LO_TIME_BITS <= ULONG_MAX);
      if (WARN_OBSOLETE_TIMESTAMPS
	  && (da_lt_db ? aform : bform) == TIMEFORM_FLOAT
	  && (da_lt_db ? bform : aform) != TIMEFORM_TICKS_HZ
	  && mpz_cmp_ui (*hzmin, 1) > 0
	  && mpz_cmp_ui (*hzmin, 1 << LO_TIME_BITS) < 0)
	{
	  mpz_t *hzmin1 = &mpz[2 - da_lt_db];
	  mpz_set_ui (*hzmin1, 1 << LO_TIME_BITS);
	  hzmin = hzmin1;
	}
1153

1154 1155 1156
      /* iticks = (fb * na) OP (fa * nb), where OP is + or -.  */
      mpz_t const *na = bignum_integer (iticks, ta.ticks);
      mpz_mul (*iticks, *fb, *na);
1157
      mpz_t const *nb = bignum_integer (&mpz[3], tb.ticks);
1158 1159 1160
      (subtract ? mpz_submul : mpz_addmul) (*iticks, *fa, *nb);

      /* Normalize iticks/ihz by dividing both numerator and
Paul Eggert's avatar
Paul Eggert committed
1161 1162
	 denominator by ig = gcd (iticks, ihz).  For speed, though,
	 skip this division if ihz = 1.  */
1163 1164 1165 1166
      mpz_t *ig = &mpz[3];
      mpz_gcd (*ig, *iticks, *ihz);
      if (!FASTER_TIMEFNS || mpz_cmp_ui (*ig, 1) > 0)
	{
1167 1168
	  mpz_divexact (*iticks, *iticks, *ig);
	  mpz_divexact (*ihz, *ihz, *ig);
1169

Paul Eggert's avatar
Paul Eggert committed
1170 1171 1172 1173 1174 1175 1176
	  /* However, if dividing the denominator by ig would cause the
	     denominator to become less than hzmin, rescale the denominator
	     upwards by multiplying the normalized numerator and denominator
	     so that the resulting denominator becomes at least hzmin.
	     This rescaling avoids returning a timestamp that is less precise
	     than both a and b, or a timestamp that looks obsolete when that
	     might be a problem.  */
1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
	  if (!FASTER_TIMEFNS || mpz_cmp (*ihz, *hzmin) < 0)
	    {
	      /* Rescale straightforwardly.  Although this might not
		 yield the minimal denominator that preserves numeric
		 value and is at least hzmin, calculating such a
		 denominator would be too expensive because it would
		 require testing multisets of factors of lcm (da, db).  */
	      mpz_t *rescale = &mpz[3];
	      mpz_cdiv_q (*rescale, *hzmin, *ihz);
	      mpz_mul (*iticks, *iticks, *rescale);
	      mpz_mul (*ihz, *ihz, *rescale);
	    }
	}
Paul Eggert's avatar
Paul Eggert committed
1190 1191

      /* mpz[0] and iticks now correspond to the (HZ . TICKS) pair.  */
1192 1193
      hz = make_integer_mpz ();
      mpz_swap (mpz[0], *iticks);
1194
      ticks = make_integer_mpz ();
1195 1196
    }

Paul Eggert's avatar
Paul Eggert committed
1197
  /* Return an integer if the timestamp resolution is 1,
1198
     otherwise the (TICKS . HZ) form if !CURRENT_TIME_LIST or if
1199
     either input used (TICKS . HZ) form or the result can't be expressed
1200 1201
     exactly in (HI LO US PS) form, otherwise the (HI LO US PS) form
     for backward compatibility.  */
Paul Eggert's avatar
Paul Eggert committed
1202 1203
  return (EQ (hz, make_fixnum (1))
	  ? ticks
1204
	  : (!CURRENT_TIME_LIST
1205 1206 1207
	     || aform == TIMEFORM_TICKS_HZ
	     || bform == TIMEFORM_TICKS_HZ
	     || !trillion_factor (hz))
1208 1209
	  ? Fcons (ticks, hz)
	  : ticks_hz_list4 (ticks, hz));
1210 1211 1212
}

DEFUN ("time-add", Ftime_add, Stime_add, 2, 2, 0,
Paul Eggert's avatar
Paul Eggert committed
1213 1214
       doc: /* Return the sum of two time values A and B, as a time value.
See `format-time-string' for the various forms of a time value.
1215
For example, nil stands for the current time.  */)
1216 1217 1218 1219 1220 1221
  (Lisp_Object a, Lisp_Object b)
{
  return time_arith (a, b, false);
}

DEFUN ("time-subtract", Ftime_subtract, Stime_subtract, 2, 2, 0,
Paul Eggert's avatar
Paul Eggert committed
1222
       doc: /* Return the difference between two time values A and B, as a time value.
1223
You can use `float-time' to convert the difference into elapsed seconds.
Paul Eggert's avatar
Paul Eggert committed
1224
See `format-time-string' for the various forms of a time value.
1225
For example, nil stands for the current time.  */)
1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
  (Lisp_Object a, Lisp_Object b)
{
  return time_arith (a, b, true);
}

/* Return negative, 0, positive if a < b, a == b, a > b respectively.
   Return positive if either a or b is a NaN; this is good enough
   for the current callers.  */
static int
time_cmp (Lisp_Object a, Lisp_Object b)
{
  if ((FLOATP (a) && !isfinite (XFLOAT_DATA (a)))
      || (FLOATP (b) && !isfinite (XFLOAT_DATA (b))))
    {
      double da = FLOATP (a) ? XFLOAT_DATA (a) : 0;
      double db = FLOATP (b) ? XFLOAT_DATA (b) : 0;
      return da < db ? -1 : da != db;
    }

1245 1246
  struct lisp_time ta = lisp_time_struct (a, 0);

1247 1248 1249
  /* Compare nil to nil correctly, and handle other eq values quicker
     while we're at it.  Compare here rather than earlier, to handle
     NaNs and check formats.  */
1250 1251 1252
  if (EQ (a, b))
    return 0;

Paul Eggert's avatar
Paul Eggert committed
1253 1254
  /* Compare (ATICKS . AZ) to (BTICKS . BHZ) by comparing
     ATICKS * BHZ to BTICKS * AHZ.  */
1255
  struct lisp_time tb = lisp_time_struct (b, 0);
1256 1257
  mpz_t const *za = bignum_integer (&mpz[0], ta.ticks);
  mpz_t const *zb = bignum_integer (&mpz[1], tb.ticks);
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268
  if (! (FASTER_TIMEFNS && EQ (ta.hz, tb.hz)))
    {
      /* This could be sped up by looking at the signs, sizes, and
	 number of bits of the two sides; see how GMP does mpq_cmp.
	 It may not be worth the trouble here, though.  */
      mpz_mul (mpz[0], *za, *bignum_integer (&mpz[2], tb.hz));
      mpz_mul (mpz[1], *zb, *bignum_integer (&mpz[2], ta.hz));
      za = &mpz[0];
      zb = &mpz[1];
    }
  return mpz_cmp (*za, *zb);
1269 1270 1271
}

DEFUN ("time-less-p", Ftime_less_p, Stime_less_p, 2, 2, 0,
1272
       doc: /* Return non-nil if time value A is less than time value B.
Paul Eggert's avatar
Paul Eggert committed
1273
See `format-time-string' for the various forms of a time value.
1274 1275
For example, nil stands for the current time.  */)
  (Lisp_Object a, Lisp_Object b)
1276
{
1277
  return time_cmp (a, b) < 0 ? Qt : Qnil;
1278 1279 1280
}

DEFUN ("time-equal-p", Ftime_equal_p, Stime_equal_p, 2, 2, 0,
1281
       doc: /* Return non-nil if A and B are equal time values.
Paul Eggert's avatar
Paul Eggert committed
1282
See `format-time-string' for the various forms of a time value.  */)
1283
  (Lisp_Object a, Lisp_Object b)
1284
{
1285
  return time_cmp (a, b) == 0 ? Qt : Qnil;
1286 1287 1288 1289 1290
}


DEFUN ("float-time", Ffloat_time, Sfloat_time, 0, 1, 0,
       doc: /* Return the current time, as a float number of seconds since the epoch.
Paul Eggert's avatar
Paul Eggert committed
1291 1292 1293
If SPECIFIED-TIME is given, it is a time value to convert to float
instead of the current time.  See `format-time-string' for the various
forms of a time value.
1294 1295

WARNING: Since the result is floating point, it may not be exact.
Paul Eggert's avatar
Paul Eggert committed
1296
If precise time stamps are required, use either `encode-time',
1297 1298 1299 1300
or (if you need time as a string) `format-time-string'.  */)
  (Lisp_Object specified_time)
{
  double t;
Paul Eggert's avatar
Paul Eggert committed
1301
  decode_lisp_time (specified_time, 0, 0, &t);
1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
  return make_float (t);
}

/* Write information into buffer S of size MAXSIZE, according to the
   FORMAT of length FORMAT_LEN, using time information taken from *TP.
   Use the time zone specified by TZ.
   Use NS as the number of nanoseconds in the %N directive.
   Return the number of bytes written, not including the terminating
   '\0'.  If S is NULL, nothing will be written anywhere; so to
   determine how many bytes would be written, use NULL for S and
   ((size_t) -1) for MAXSIZE.

1314
   This function behaves like nstrftime, except it allows NUL
1315 1316 1317 1318 1319 1320 1321
   bytes in FORMAT and it does not support nanoseconds.  */
static size_t
emacs_nmemftime (char *s, size_t maxsize, const char *format,
		 size_t format_len, const struct tm *tp, timezone_t tz, int ns)
{
  size_t total = 0;

1322 1323
  /* Loop through all the NUL-terminated strings in the format
     argument.  Normally there's just one NUL-terminated string, but
1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
     there can be arbitrarily many, concatenated together, if the
     format contains '\0' bytes.  nstrftime stops at the first
     '\0' byte so we must invoke it separately for each such string.  */
  for (;;)
    {
      size_t len;
      size_t result;

      if (s)
	s[0] = '\1';

      result = nstrftime (s, maxsize, format, tp, tz, ns);

      if (s)
	{
	  if (result == 0 && s[0] != '\0')
	    return 0;
	  s += result + 1;
	}

      maxsize -= result + 1;
      total += result;
      len = strlen (format);
      if (len == format_len)
	return total;
      total++;
      format += len + 1;
      format_len -= len + 1;
    }
}

static Lisp_Object
format_time_string (char const *format, ptrdiff_t formatlen,
		    struct timespec t, Lisp_Object zone, struct tm *tmp)
{
  char buffer[4000];
  char *buf = buffer;
  ptrdiff_t size = sizeof buffer;
  size_t len;
  int ns = t.tv_nsec;
  USE_SAFE_ALLOCA;

  timezone_t tz = tzlookup (zone, false);
  /* On some systems, like 32-bit MinGW, tv_sec of struct timespec is
     a 64-bit type, but time_t is a 32-bit type.  emacs_localtime_rz
     expects a pointer to time_t value.  */
  time_t tsec = t.tv_sec;
  tmp = emacs_localtime_rz (tz, &tsec, tmp);
  if (! tmp)
    {
Paul Eggert's avatar
Paul Eggert committed
1374
      int localtime_errno = errno;
1375
      xtzfree (tz);
Paul Eggert's avatar
Paul Eggert committed
1376
      time_error (localtime_errno);
1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406
    }
  synchronize_system_time_locale ();

  while (true)
    {
      buf[0] = '\1';
      len = emacs_nmemftime (buf, size, format, formatlen, tmp, tz, ns);
      if ((0 < len && len < size) || (len == 0 && buf[0] == '\0'))
	break;

      /* Buffer was too small, so make it bigger and try again.  */
      len = emacs_nmemftime (NULL, SIZE_MAX, format, formatlen, tmp, tz, ns);
      if (STRING_BYTES_BOUND <= len)
	{
	  xtzfree (tz);
	  string_overflow ();
	}
      size = len + 1;
      buf = SAFE_ALLOCA (size);
    }

  xtzfree (tz);
  AUTO_STRING_WITH_LEN (bufstring, buf, len);
  Lisp_Object result = code_convert_string_norecord (bufstring,
						     Vlocale_coding_system, 0);
  SAFE_FREE ();
  return result;
}

DEFUN ("format-time-string", Fformat_time_string, Sformat_time_string, 1, 3, 0,
Paul Eggert's avatar
Paul Eggert committed
1407 1408 1409 1410 1411 1412
       doc: /* Use FORMAT-STRING to format the time value TIME.
A time value that is omitted or nil stands for the current time,
a number stands for that many seconds, an integer pair (TICKS . HZ)
stands for TICKS/HZ seconds, and an integer list (HI LO US PS) stands
for HI*2**16 + LO + US/10**6 + PS/10**12 seconds.  This function
treats seconds as time since the epoch of 1970-01-01 00:00:00 UTC.
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447

The optional ZONE is omitted or nil for Emacs local time, t for
Universal Time, `wall' for system wall clock time, or a string as in
the TZ environment variable.  It can also be a list (as from
`current-time-zone') or an integer (as from `decode-time') applied
without consideration for daylight saving time.

The value is a copy of FORMAT-STRING, but with certain constructs replaced
by text that describes the specified date and time in TIME:

%Y is the year, %y within the century, %C the century.
%G is the year corresponding to the ISO week, %g within the century.
%m is the numeric month.
%b and %h are the locale's abbreviated month name, %B the full name.
 (%h is not supported on MS-Windows.)
%d is the day of the month, zero-padded, %e is blank-padded.
%u is the numeric day of week from 1 (Monday) to 7, %w from 0 (Sunday) to 6.
%a is the locale's abbreviated name of the day of week, %A the full name.
%U is the week number starting on Sunday, %W starting on Monday,
 %V according to ISO 8601.
%j is the day of the year.

%H is the hour on a 24-hour clock, %I is on a 12-hour clock, %k is like %H
 only blank-padded, %l is like %I blank-padded.
%p is the locale's equivalent of either AM or PM.
%q is the calendar quarter (1–4).
%M is the minute (00-59).
%S is the second (00-59; 00-60 on platforms with leap seconds)
%s is the number of seconds since 1970-01-01 00:00:00 +0000.
%N is the nanosecond, %6N the microsecond, %3N the millisecond, etc.
%Z is the time zone abbreviation, %z is the numeric form.

%c is the locale's date and time format.
%x is the locale's "preferred" date format.
%D is like "%m/%d/%y".
1448
%F is the ISO 8601 date format (like "%+4Y-%m-%d").
1449 1450 1451 1452 1453 1454 1455

%R is like "%H:%M", %T is like "%H:%M:%S", %r is like "%I:%M:%S %p".
%X is the locale's "preferred" time format.

Finally, %n is a newline, %t is a tab, %% is a literal %, and
unrecognized %-sequences stand for themselves.

1456 1457 1458 1459 1460 1461 1462 1463 1464 1465
A %-sequence can contain optional flags, field width, and a modifier
(in that order) after the `%'.  The flags are:

`-' Do not pad the field.
`_' Pad with spaces.
`0' Pad with zeros.
`+' Pad with zeros and put `+' before nonnegative year numbers with >4 digits.
`^' Use upper case characters if possible.
`#' Use opposite case characters if possible.

1466 1467 1468 1469 1470 1471
A field width N is an unsigned decimal integer with a leading digit
nonzero.  %NX is like %X, but takes up at least N positions.  The
field width is (on GNU/Linux and some other systems) in measured in
bytes, not characters.  It depends on the locale what the width (in
characters) %NX will end up being, especially when there are non-ASCII
characters in %X.
1472 1473 1474 1475 1476

The modifiers are:

`E' Use the locale's alternative version.
`O' Use the locale's number symbols.
1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492

For example, to produce full ISO 8601 format, use "%FT%T%z".

usage: (format-time-string FORMAT-STRING &optional TIME ZONE)  */)
  (Lisp_Object format_string, Lisp_Object timeval, Lisp_Object zone)
{
  struct timespec t = lisp_time_argument (timeval);
  struct tm tm;

  CHECK_STRING (format_string);
  format_string = code_convert_string_norecord (format_string,
						Vlocale_coding_system, 1);
  return format_time_string (SSDATA (format_string), SBYTES (format_string),
			     t, zone, &tm);
}

1493 1494
DEFUN ("decode-time", Fdecode_time, Sdecode_time, 0, 3, 0,
       doc: /* Decode a time value as (SEC MINUTE HOUR DAY MONTH YEAR DOW DST UTCOFF).
Paul Eggert's avatar
Paul Eggert committed
1495 1496
The optional TIME is the time value to convert.  See
`format-time-string' for the various forms of a time value.
1497 1498 1499 1500 1501 1502 1503

The optional ZONE is omitted or nil for Emacs local time, t for
Universal Time, `wall' for system wall clock time, or a string as in
the TZ environment variable.  It can also be a list (as from
`current-time-zone') or an integer (the UTC offset in seconds) applied
without consideration for daylight saving time.

1504
The optional FORM specifies the form of the SEC member.  If `integer',
1505 1506 1507
SEC is an integer; if t, SEC is an integer or (TICKS . HZ) timestamp
with the same precision as TIME.  An omitted or nil FORM is currently
treated like `integer', but this may change in future Emacs versions.
1508

1509 1510 1511
To access (or alter) the elements in the time value, the
`decoded-time-second', `decoded-time-minute', `decoded-time-hour',
`decoded-time-day', `decoded-time-month', `decoded-time-year',
1512 1513
`decoded-time-weekday', `decoded-time-dst' and `decoded-time-zone'
accessors can be used.
1514

1515 1516 1517 1518
The list has the following nine members: SEC is an integer or
Lisp timestamp representing a nonnegative value less than 60
\(or less than 61 if the operating system supports leap seconds).
MINUTE is an integer between 0 and 59.  HOUR is an integer
1519
between 0 and 23.  DAY is an integer between 1 and 31.  MONTH is an
1520 1521
integer between 1 and 12.  YEAR is the year number, an integer; 0
represents 1 BC.  DOW is the day of week, an integer between 0 and 6,
1522 1523 1524
where 0 is Sunday.  DST is t if daylight saving time is in effect,
nil if it is not in effect, and -1 if daylight saving information is
not available.  UTCOFF is an integer indicating the UTC offset in
1525 1526 1527 1528 1529 1530
seconds, i.e., the number of seconds east of Greenwich.  (Note that
Common Lisp has different meanings for DOW and UTCOFF, and its
SEC is always an integer between 0 and 59.)

usage: (decode-time &optional TIME ZONE FORM)  */)
  (Lisp_Object specified_time, Lisp_Object zone, Lisp_Object form)
1531
{
Paul Eggert's avatar
Paul Eggert committed
1532
  /* Compute broken-down local time LOCAL_TM from SPECIFIED_TIME and ZONE.  */
1533 1534 1535 1536 1537
  struct lisp_time lt = lisp_time_struct (specified_time, 0);
  struct timespec ts = lisp_to_timespec (lt);
  if (! timespec_valid_p (ts))
    time_overflow ();
  time_t time_spec = ts.tv_sec;
1538 1539 1540
  struct tm local_tm, gmt_tm;
  timezone_t tz = tzlookup (zone, false);
  struct tm *tm = emacs_localtime_rz (tz, &time_spec, &local_tm);
Paul Eggert's avatar
Paul Eggert committed
1541
  int localtime_errno = errno;
1542 1543
  xtzfree (tz);

Paul Eggert's avatar
Paul Eggert committed
1544 1545
  if (!tm)
    time_error (localtime_errno);
1546

Paul Eggert's avatar
Paul Eggert committed
1547
  /* Let YEAR = LOCAL_TM.tm_year + TM_YEAR_BASE.  */
Paul Eggert's avatar
Paul Eggert committed
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562
  Lisp_Object year;
  if (FASTER_TIMEFNS
      && MOST_NEGATIVE_FIXNUM - TM_YEAR_BASE <= local_tm.tm_year
      && local_tm.tm_year <= MOST_POSITIVE_FIXNUM - TM_YEAR_BASE)
    {
      /* Avoid overflow when INT_MAX - TM_YEAR_BASE < local_tm.tm_year.  */
      EMACS_INT tm_year_base = TM_YEAR_BASE;
      year = make_fixnum (local_tm.tm_year + tm_year_base);
    }
  else
    {
      mpz_set_si (mpz[0], local_tm.tm_year);
      mpz_add_ui (mpz[0], mpz[0], TM_YEAR_BASE);
      year = make_integer_mpz ();
    }
1563

Paul Eggert's avatar
Paul Eggert committed
1564
  /* Compute SEC from LOCAL_TM.tm_sec and HZ.  */
1565 1566 1567 1568 1569
  Lisp_Object hz = lt.hz, sec;
  if (EQ (hz, make_fixnum (1)) || !EQ (form, Qt))
    sec = make_fixnum (local_tm.tm_sec);
  else
    {
Paul Eggert's avatar
Paul Eggert committed
1570 1571 1572
      /* Let TICKS = HZ * LOCAL_TM.tm_sec + mod (LT.ticks, HZ)
	 and SEC = (TICKS . HZ).  */
      Lisp_Object ticks;
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593
      intmax_t n;
      if (FASTER_TIMEFNS && FIXNUMP (lt.ticks) && FIXNUMP (hz)
	  && !INT_MULTIPLY_WRAPV (XFIXNUM (hz), local_tm.tm_sec, &n)
	  && ! (INT_ADD_WRAPV
		(n, (XFIXNUM (lt.ticks) % XFIXNUM (hz)
		     + (XFIXNUM (lt.ticks) % XFIXNUM (hz) < 0
			? XFIXNUM (hz) : 0)),
		 &n)))
	ticks = make_int (n);
      else
	{
	  mpz_fdiv_r (mpz[0],
		      *bignum_integer (&mpz[0], lt.ticks),
		      *bignum_integer (&mpz[1], hz));
	  mpz_addmul_ui (mpz[0], *bignum_integer (&mpz[1], hz),
			 local_tm.tm_sec);
	  ticks = make_integer_mpz ();
	}
      sec = Fcons (ticks, hz);