* numbers.h (SCM_MAKINUM, SCM_I_MAKINUM): Renamed SCM_MAKINUM to
[bpt/guile.git] / libguile / stime.c
1 /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2003, 2004 Free Software Foundation, Inc.
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 */
17
18
19 \f
20
21 #define _GNU_SOURCE /* ask glibc for everything, in particular strptime */
22 #define _POSIX_C_SOURCE 199506L /* for gmtime_r prototype */
23
24 #if HAVE_CONFIG_H
25 # include <config.h>
26 #endif
27
28 #include <stdio.h>
29 #include <errno.h>
30
31 #include "libguile/_scm.h"
32 #include "libguile/feature.h"
33 #include "libguile/strings.h"
34 #include "libguile/vectors.h"
35
36 #include "libguile/validate.h"
37 #include "libguile/stime.h"
38
39 #ifdef HAVE_UNISTD_H
40 #include <unistd.h>
41 #endif
42
43 \f
44 # ifdef HAVE_SYS_TYPES_H
45 # include <sys/types.h>
46 # endif
47
48 #ifdef HAVE_STRING_H
49 #include <string.h>
50 #endif
51
52 #ifdef HAVE_SYS_TIMES_H
53 # include <sys/times.h>
54 #endif
55
56 #ifdef HAVE_SYS_TIMEB_H
57 # include <sys/timeb.h>
58 #endif
59
60 #if HAVE_CRT_EXTERNS_H
61 #include <crt_externs.h> /* for Darwin _NSGetEnviron */
62 #endif
63
64 #ifndef tzname /* For SGI. */
65 extern char *tzname[]; /* RS6000 and others reject char **tzname. */
66 #endif
67 #if defined (__MINGW32__)
68 # define tzname _tzname
69 #endif
70
71 #if ! HAVE_DECL_STRPTIME
72 extern char *strptime ();
73 #endif
74
75 #ifdef __STDC__
76 # define timet time_t
77 #else
78 # define timet long
79 #endif
80
81 extern char ** environ;
82
83 /* On Apple Darwin in a shared library there's no "environ" to access
84 directly, instead the address of that variable must be obtained with
85 _NSGetEnviron(). */
86 #if HAVE__NSGETENVIRON && defined (PIC)
87 #define environ (*_NSGetEnviron())
88 #endif
89
90
91 #ifdef HAVE_TIMES
92 static
93 timet mytime()
94 {
95 struct tms time_buffer;
96 times(&time_buffer);
97 return time_buffer.tms_utime + time_buffer.tms_stime;
98 }
99 #else
100 # ifdef LACK_CLOCK
101 # define mytime() ((time((timet*)0) - scm_your_base) * SCM_TIME_UNITS_PER_SECOND)
102 # else
103 # define mytime clock
104 # endif
105 #endif
106
107 #ifdef HAVE_FTIME
108 struct timeb scm_your_base = {0};
109 #else
110 timet scm_your_base = 0;
111 #endif
112
113 SCM_DEFINE (scm_get_internal_real_time, "get-internal-real-time", 0, 0, 0,
114 (),
115 "Return the number of time units since the interpreter was\n"
116 "started.")
117 #define FUNC_NAME s_scm_get_internal_real_time
118 {
119 #ifdef HAVE_FTIME
120 struct timeb time_buffer;
121
122 SCM tmp;
123 ftime (&time_buffer);
124 time_buffer.time -= scm_your_base.time;
125 tmp = scm_long2num (time_buffer.millitm - scm_your_base.millitm);
126 tmp = scm_sum (tmp,
127 scm_product (SCM_I_MAKINUM (1000),
128 SCM_I_MAKINUM (time_buffer.time)));
129 return scm_quotient (scm_product (tmp, SCM_I_MAKINUM (SCM_TIME_UNITS_PER_SECOND)),
130 SCM_I_MAKINUM (1000));
131 #else
132 return scm_long2num((time((timet*)0) - scm_your_base) * (int)SCM_TIME_UNITS_PER_SECOND);
133 #endif /* HAVE_FTIME */
134 }
135 #undef FUNC_NAME
136
137
138 #ifdef HAVE_TIMES
139 SCM_DEFINE (scm_times, "times", 0, 0, 0,
140 (void),
141 "Return an object with information about real and processor\n"
142 "time. The following procedures accept such an object as an\n"
143 "argument and return a selected component:\n"
144 "\n"
145 "@table @code\n"
146 "@item tms:clock\n"
147 "The current real time, expressed as time units relative to an\n"
148 "arbitrary base.\n"
149 "@item tms:utime\n"
150 "The CPU time units used by the calling process.\n"
151 "@item tms:stime\n"
152 "The CPU time units used by the system on behalf of the calling\n"
153 "process.\n"
154 "@item tms:cutime\n"
155 "The CPU time units used by terminated child processes of the\n"
156 "calling process, whose status has been collected (e.g., using\n"
157 "@code{waitpid}).\n"
158 "@item tms:cstime\n"
159 "Similarly, the CPU times units used by the system on behalf of\n"
160 "terminated child processes.\n"
161 "@end table")
162 #define FUNC_NAME s_scm_times
163 {
164 struct tms t;
165 clock_t rv;
166
167 SCM result = scm_c_make_vector (5, SCM_UNDEFINED);
168 rv = times (&t);
169 if (rv == -1)
170 SCM_SYSERROR;
171 SCM_VECTOR_SET (result, 0, scm_long2num (rv));
172 SCM_VECTOR_SET (result, 1, scm_long2num (t.tms_utime));
173 SCM_VECTOR_SET (result, 2, scm_long2num (t.tms_stime));
174 SCM_VECTOR_SET (result ,3, scm_long2num (t.tms_cutime));
175 SCM_VECTOR_SET (result, 4, scm_long2num (t.tms_cstime));
176 return result;
177 }
178 #undef FUNC_NAME
179 #endif /* HAVE_TIMES */
180
181 static long scm_my_base = 0;
182
183 long
184 scm_c_get_internal_run_time ()
185 {
186 return mytime () - scm_my_base;
187 }
188
189 SCM_DEFINE (scm_get_internal_run_time, "get-internal-run-time", 0, 0, 0,
190 (void),
191 "Return the number of time units of processor time used by the\n"
192 "interpreter. Both @emph{system} and @emph{user} time are\n"
193 "included but subprocesses are not.")
194 #define FUNC_NAME s_scm_get_internal_run_time
195 {
196 return scm_long2num (scm_c_get_internal_run_time ());
197 }
198 #undef FUNC_NAME
199
200 /* For reference, note that current-time and gettimeofday both should be
201 protected against setzone/restorezone changes in another thread, since on
202 DOS the system time is normally kept as local time, which means TZ
203 affects the return from current-time and gettimeofday. Not sure if DJGPP
204 etc actually has concurrent multi-threading, but it seems prudent not to
205 make assumptions about this. */
206
207 SCM_DEFINE (scm_current_time, "current-time", 0, 0, 0,
208 (void),
209 "Return the number of seconds since 1970-01-01 00:00:00 UTC,\n"
210 "excluding leap seconds.")
211 #define FUNC_NAME s_scm_current_time
212 {
213 timet timv;
214
215 SCM_DEFER_INTS;
216 if ((timv = time (0)) == -1)
217 SCM_MISC_ERROR ("current time not available", SCM_EOL);
218 SCM_ALLOW_INTS;
219 return scm_long2num((long) timv);
220 }
221 #undef FUNC_NAME
222
223 SCM_DEFINE (scm_gettimeofday, "gettimeofday", 0, 0, 0,
224 (void),
225 "Return a pair containing the number of seconds and microseconds\n"
226 "since 1970-01-01 00:00:00 UTC, excluding leap seconds. Note:\n"
227 "whether true microsecond resolution is available depends on the\n"
228 "operating system.")
229 #define FUNC_NAME s_scm_gettimeofday
230 {
231 #ifdef HAVE_GETTIMEOFDAY
232 struct timeval time;
233
234 SCM_DEFER_INTS;
235 if (gettimeofday (&time, NULL) == -1)
236 SCM_SYSERROR;
237 SCM_ALLOW_INTS;
238 return scm_cons (scm_long2num ((long) time.tv_sec),
239 scm_long2num ((long) time.tv_usec));
240 #else
241 # ifdef HAVE_FTIME
242 struct timeb time;
243
244 ftime(&time);
245 return scm_cons (scm_long2num ((long) time.time),
246 SCM_I_MAKINUM (time.millitm * 1000));
247 # else
248 timet timv;
249
250 SCM_DEFER_INTS;
251 if ((timv = time (0)) == -1)
252 SCM_SYSERROR;
253 SCM_ALLOW_INTS;
254 return scm_cons (scm_long2num (timv), SCM_I_MAKINUM (0));
255 # endif
256 #endif
257 }
258 #undef FUNC_NAME
259
260 static SCM
261 filltime (struct tm *bd_time, int zoff, const char *zname)
262 {
263 SCM result = scm_c_make_vector (11, SCM_UNDEFINED);
264
265 SCM_VECTOR_SET (result,0, SCM_I_MAKINUM (bd_time->tm_sec));
266 SCM_VECTOR_SET (result,1, SCM_I_MAKINUM (bd_time->tm_min));
267 SCM_VECTOR_SET (result,2, SCM_I_MAKINUM (bd_time->tm_hour));
268 SCM_VECTOR_SET (result,3, SCM_I_MAKINUM (bd_time->tm_mday));
269 SCM_VECTOR_SET (result,4, SCM_I_MAKINUM (bd_time->tm_mon));
270 SCM_VECTOR_SET (result,5, SCM_I_MAKINUM (bd_time->tm_year));
271 SCM_VECTOR_SET (result,6, SCM_I_MAKINUM (bd_time->tm_wday));
272 SCM_VECTOR_SET (result,7, SCM_I_MAKINUM (bd_time->tm_yday));
273 SCM_VECTOR_SET (result,8, SCM_I_MAKINUM (bd_time->tm_isdst));
274 SCM_VECTOR_SET (result,9, SCM_I_MAKINUM (zoff));
275 SCM_VECTOR_SET (result,10, zname ? scm_makfrom0str (zname) : SCM_BOOL_F);
276 return result;
277 }
278
279 static char tzvar[3] = "TZ";
280
281 /* if zone is set, create a temporary environment with only a TZ
282 string. other threads or interrupt handlers shouldn't be allowed
283 to run until the corresponding restorezone is called. hence the use
284 of a static variable for tmpenv is no big deal. */
285 static char **
286 setzone (SCM zone, int pos, const char *subr)
287 {
288 char **oldenv = 0;
289
290 if (!SCM_UNBNDP (zone))
291 {
292 static char *tmpenv[2];
293 char *buf;
294
295 SCM_ASSERT (SCM_STRINGP (zone), zone, pos, subr);
296 buf = scm_malloc (SCM_STRING_LENGTH (zone) + sizeof (tzvar) + 1);
297 sprintf (buf, "%s=%s", tzvar, SCM_STRING_CHARS (zone));
298 oldenv = environ;
299 tmpenv[0] = buf;
300 tmpenv[1] = 0;
301 environ = tmpenv;
302 }
303 return oldenv;
304 }
305
306 static void
307 restorezone (SCM zone, char **oldenv, const char *subr SCM_UNUSED)
308 {
309 if (!SCM_UNBNDP (zone))
310 {
311 free (environ[0]);
312 environ = oldenv;
313 #ifdef HAVE_TZSET
314 /* for the possible benefit of user code linked with libguile. */
315 tzset();
316 #endif
317 }
318 }
319
320 SCM_DEFINE (scm_localtime, "localtime", 1, 1, 0,
321 (SCM time, SCM zone),
322 "Return an object representing the broken down components of\n"
323 "@var{time}, an integer like the one returned by\n"
324 "@code{current-time}. The time zone for the calculation is\n"
325 "optionally specified by @var{zone} (a string), otherwise the\n"
326 "@code{TZ} environment variable or the system default is used.")
327 #define FUNC_NAME s_scm_localtime
328 {
329 timet itime;
330 struct tm *ltptr, lt, *utc;
331 SCM result;
332 int zoff;
333 char *zname = 0;
334 char **oldenv;
335 int err;
336
337 itime = SCM_NUM2LONG (1, time);
338
339 /* deferring interupts is essential since a) setzone may install a temporary
340 environment b) localtime uses a static buffer. */
341 SCM_DEFER_INTS;
342 oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
343 #ifdef LOCALTIME_CACHE
344 tzset ();
345 #endif
346 /* POSIX says localtime sets errno, but C99 doesn't say that.
347 Give a sensible default value in case localtime doesn't set it. */
348 errno = EINVAL;
349 ltptr = localtime (&itime);
350 err = errno;
351 if (ltptr)
352 {
353 const char *ptr;
354
355 /* copy zone name before calling gmtime or restoring zone. */
356 #if defined (HAVE_TM_ZONE)
357 ptr = ltptr->tm_zone;
358 #elif defined (HAVE_TZNAME)
359 ptr = tzname[ (ltptr->tm_isdst == 1) ? 1 : 0 ];
360 #else
361 ptr = "";
362 #endif
363 zname = scm_malloc (strlen (ptr) + 1);
364 strcpy (zname, ptr);
365 }
366 /* the struct is copied in case localtime and gmtime share a buffer. */
367 if (ltptr)
368 lt = *ltptr;
369 /* POSIX says gmtime sets errno, but C99 doesn't say that.
370 Give a sensible default value in case gmtime doesn't set it. */
371 errno = EINVAL;
372 utc = gmtime (&itime);
373 if (utc == NULL)
374 err = errno;
375 restorezone (zone, oldenv, FUNC_NAME);
376 /* delayed until zone has been restored. */
377 errno = err;
378 if (utc == NULL || ltptr == NULL)
379 SCM_SYSERROR;
380
381 /* calculate timezone offset in seconds west of UTC. */
382 zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
383 + utc->tm_sec - lt.tm_sec;
384 if (utc->tm_year < lt.tm_year)
385 zoff -= 24 * 60 * 60;
386 else if (utc->tm_year > lt.tm_year)
387 zoff += 24 * 60 * 60;
388 else if (utc->tm_yday < lt.tm_yday)
389 zoff -= 24 * 60 * 60;
390 else if (utc->tm_yday > lt.tm_yday)
391 zoff += 24 * 60 * 60;
392
393 result = filltime (&lt, zoff, zname);
394 SCM_ALLOW_INTS;
395 if (zname)
396 free (zname);
397 return result;
398 }
399 #undef FUNC_NAME
400
401 /* tm_zone is normally a pointer, not an array within struct tm, so we might
402 have to worry about the lifespan of what it points to. The posix specs
403 don't seem to say anything about this, let's assume here that tm_zone
404 will be a constant and therefore no protection or anything is needed
405 until we copy it in filltime(). */
406
407 SCM_DEFINE (scm_gmtime, "gmtime", 1, 0, 0,
408 (SCM time),
409 "Return an object representing the broken down components of\n"
410 "@var{time}, an integer like the one returned by\n"
411 "@code{current-time}. The values are calculated for UTC.")
412 #define FUNC_NAME s_scm_gmtime
413 {
414 timet itime;
415 struct tm bd_buf, *bd_time;
416 const char *zname;
417
418 itime = SCM_NUM2LONG (1, time);
419
420 /* POSIX says gmtime sets errno, but C99 doesn't say that.
421 Give a sensible default value in case gmtime doesn't set it. */
422 errno = EINVAL;
423
424 #if HAVE_GMTIME_R
425 bd_time = gmtime_r (&itime, &bd_buf);
426 #else
427 SCM_DEFER_INTS;
428 bd_time = gmtime (&itime);
429 if (bd_time != NULL)
430 bd_buf = *bd_time;
431 SCM_ALLOW_INTS;
432 #endif
433 if (bd_time == NULL)
434 SCM_SYSERROR;
435
436 #if HAVE_STRUCT_TM_TM_ZONE
437 zname = bd_buf.tm_zone;
438 #else
439 zname = "GMT";
440 #endif
441 return filltime (&bd_buf, 0, zname);
442 }
443 #undef FUNC_NAME
444
445 /* copy time components from a Scheme object to a struct tm. */
446 static void
447 bdtime2c (SCM sbd_time, struct tm *lt, int pos, const char *subr)
448 {
449 SCM const *velts;
450 int i;
451
452 SCM_ASSERT (SCM_VECTORP (sbd_time)
453 && SCM_VECTOR_LENGTH (sbd_time) == 11,
454 sbd_time, pos, subr);
455 velts = SCM_VELTS (sbd_time);
456 for (i = 0; i < 10; i++)
457 {
458 SCM_ASSERT (SCM_INUMP (velts[i]), sbd_time, pos, subr);
459 }
460 SCM_ASSERT (scm_is_false (velts[10]) || SCM_STRINGP (velts[10]),
461 sbd_time, pos, subr);
462
463 lt->tm_sec = SCM_INUM (velts[0]);
464 lt->tm_min = SCM_INUM (velts[1]);
465 lt->tm_hour = SCM_INUM (velts[2]);
466 lt->tm_mday = SCM_INUM (velts[3]);
467 lt->tm_mon = SCM_INUM (velts[4]);
468 lt->tm_year = SCM_INUM (velts[5]);
469 lt->tm_wday = SCM_INUM (velts[6]);
470 lt->tm_yday = SCM_INUM (velts[7]);
471 lt->tm_isdst = SCM_INUM (velts[8]);
472 #ifdef HAVE_TM_ZONE
473 lt->tm_gmtoff = SCM_INUM (velts[9]);
474 if (scm_is_false (velts[10]))
475 lt->tm_zone = NULL;
476 else
477 lt->tm_zone = SCM_STRING_CHARS (velts[10]);
478 #endif
479 }
480
481 SCM_DEFINE (scm_mktime, "mktime", 1, 1, 0,
482 (SCM sbd_time, SCM zone),
483 "@var{bd-time} is an object representing broken down time and @code{zone}\n"
484 "is an optional time zone specifier (otherwise the TZ environment variable\n"
485 "or the system default is used).\n\n"
486 "Returns a pair: the car is a corresponding\n"
487 "integer time value like that returned\n"
488 "by @code{current-time}; the cdr is a broken down time object, similar to\n"
489 "as @var{bd-time} but with normalized values.")
490 #define FUNC_NAME s_scm_mktime
491 {
492 timet itime;
493 struct tm lt, *utc;
494 SCM result;
495 int zoff;
496 char *zname = 0;
497 char **oldenv;
498 int err;
499
500 bdtime2c (sbd_time, &lt, SCM_ARG1, FUNC_NAME);
501
502 SCM_DEFER_INTS;
503 oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
504 #ifdef LOCALTIME_CACHE
505 tzset ();
506 #endif
507 itime = mktime (&lt);
508 /* POSIX doesn't say mktime sets errno, and on glibc 2.3.2 for instance it
509 doesn't. Force a sensible value for our error message. */
510 err = EINVAL;
511
512 if (itime != -1)
513 {
514 const char *ptr;
515
516 /* copy zone name before calling gmtime or restoring the zone. */
517 #if defined (HAVE_TM_ZONE)
518 ptr = lt.tm_zone;
519 #elif defined (HAVE_TZNAME)
520 ptr = tzname[ (lt.tm_isdst == 1) ? 1 : 0 ];
521 #else
522 ptr = "";
523 #endif
524 zname = scm_malloc (strlen (ptr) + 1);
525 strcpy (zname, ptr);
526 }
527
528 /* get timezone offset in seconds west of UTC. */
529 /* POSIX says gmtime sets errno, but C99 doesn't say that.
530 Give a sensible default value in case gmtime doesn't set it. */
531 utc = gmtime (&itime);
532 if (utc == NULL)
533 err = errno;
534
535 restorezone (zone, oldenv, FUNC_NAME);
536 /* delayed until zone has been restored. */
537 errno = err;
538 if (utc == NULL || itime == -1)
539 SCM_SYSERROR;
540
541 zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
542 + utc->tm_sec - lt.tm_sec;
543 if (utc->tm_year < lt.tm_year)
544 zoff -= 24 * 60 * 60;
545 else if (utc->tm_year > lt.tm_year)
546 zoff += 24 * 60 * 60;
547 else if (utc->tm_yday < lt.tm_yday)
548 zoff -= 24 * 60 * 60;
549 else if (utc->tm_yday > lt.tm_yday)
550 zoff += 24 * 60 * 60;
551
552 result = scm_cons (scm_long2num ((long) itime),
553 filltime (&lt, zoff, zname));
554 SCM_ALLOW_INTS;
555 if (zname)
556 free (zname);
557 return result;
558 }
559 #undef FUNC_NAME
560
561 #ifdef HAVE_TZSET
562 SCM_DEFINE (scm_tzset, "tzset", 0, 0, 0,
563 (void),
564 "Initialize the timezone from the TZ environment variable\n"
565 "or the system default. It's not usually necessary to call this procedure\n"
566 "since it's done automatically by other procedures that depend on the\n"
567 "timezone.")
568 #define FUNC_NAME s_scm_tzset
569 {
570 tzset();
571 return SCM_UNSPECIFIED;
572 }
573 #undef FUNC_NAME
574 #endif /* HAVE_TZSET */
575
576 SCM_DEFINE (scm_strftime, "strftime", 2, 0, 0,
577 (SCM format, SCM stime),
578 "Formats a time specification @var{time} using @var{template}. @var{time}\n"
579 "is an object with time components in the form returned by @code{localtime}\n"
580 "or @code{gmtime}. @var{template} is a string which can include formatting\n"
581 "specifications introduced by a @code{%} character. The formatting of\n"
582 "month and day names is dependent on the current locale. The value returned\n"
583 "is the formatted string.\n"
584 "@xref{Formatting Date and Time, , , libc, The GNU C Library Reference Manual}.)")
585 #define FUNC_NAME s_scm_strftime
586 {
587 struct tm t;
588
589 char *tbuf;
590 int size = 50;
591 char *fmt, *myfmt;
592 int len;
593 SCM result;
594
595 SCM_VALIDATE_STRING (1, format);
596 bdtime2c (stime, &t, SCM_ARG2, FUNC_NAME);
597
598 fmt = SCM_STRING_CHARS (format);
599 len = SCM_STRING_LENGTH (format);
600
601 /* Ugly hack: strftime can return 0 if its buffer is too small,
602 but some valid time strings (e.g. "%p") can sometimes produce
603 a zero-byte output string! Workaround is to prepend a junk
604 character to the format string, so that valid returns are always
605 nonzero. */
606 myfmt = scm_malloc (len+2);
607 *myfmt = 'x';
608 strncpy(myfmt+1, fmt, len);
609 myfmt[len+1] = 0;
610
611 tbuf = scm_malloc (size);
612 {
613 #if !defined (HAVE_TM_ZONE)
614 /* it seems the only way to tell non-GNU versions of strftime what
615 zone to use (for the %Z format) is to set TZ in the
616 environment. interrupts and thread switching must be deferred
617 until TZ is restored. */
618 char **oldenv = NULL;
619 SCM *velts = (SCM *) SCM_VELTS (stime);
620 int have_zone = 0;
621
622 if (scm_is_true (velts[10]) && *SCM_STRING_CHARS (velts[10]) != 0)
623 {
624 /* it's not required that the TZ setting be correct, just that
625 it has the right name. so try something like TZ=EST0.
626 using only TZ=EST would be simpler but it doesn't work on
627 some OSs, e.g., Solaris. */
628 SCM zone =
629 scm_string_append (scm_cons (velts[10],
630 scm_cons (scm_makfrom0str ("0"),
631 SCM_EOL)));
632
633 have_zone = 1;
634 SCM_DEFER_INTS;
635 oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
636 }
637 #endif
638
639 #ifdef LOCALTIME_CACHE
640 tzset ();
641 #endif
642
643 /* POSIX says strftime returns 0 on buffer overrun, but old
644 systems (i.e. libc 4 on GNU/Linux) might return `size' in that
645 case. */
646 while ((len = strftime (tbuf, size, myfmt, &t)) == 0 || len == size)
647 {
648 free (tbuf);
649 size *= 2;
650 tbuf = scm_malloc (size);
651 }
652
653 #if !defined (HAVE_TM_ZONE)
654 if (have_zone)
655 {
656 restorezone (velts[10], oldenv, FUNC_NAME);
657 SCM_ALLOW_INTS;
658 }
659 #endif
660 }
661
662 result = scm_mem2string (tbuf + 1, len - 1);
663 free (tbuf);
664 free (myfmt);
665 return result;
666 }
667 #undef FUNC_NAME
668
669 #ifdef HAVE_STRPTIME
670 SCM_DEFINE (scm_strptime, "strptime", 2, 0, 0,
671 (SCM format, SCM string),
672 "Performs the reverse action to @code{strftime}, parsing\n"
673 "@var{string} according to the specification supplied in\n"
674 "@var{template}. The interpretation of month and day names is\n"
675 "dependent on the current locale. The value returned is a pair.\n"
676 "The car has an object with time components\n"
677 "in the form returned by @code{localtime} or @code{gmtime},\n"
678 "but the time zone components\n"
679 "are not usefully set.\n"
680 "The cdr reports the number of characters from @var{string}\n"
681 "which were used for the conversion.")
682 #define FUNC_NAME s_scm_strptime
683 {
684 struct tm t;
685 char *fmt, *str, *rest;
686
687 SCM_VALIDATE_STRING (1, format);
688 SCM_VALIDATE_STRING (2, string);
689
690 fmt = SCM_STRING_CHARS (format);
691 str = SCM_STRING_CHARS (string);
692
693 /* initialize the struct tm */
694 #define tm_init(field) t.field = 0
695 tm_init (tm_sec);
696 tm_init (tm_min);
697 tm_init (tm_hour);
698 tm_init (tm_mday);
699 tm_init (tm_mon);
700 tm_init (tm_year);
701 tm_init (tm_wday);
702 tm_init (tm_yday);
703 #undef tm_init
704
705 /* GNU glibc strptime() "%s" is affected by the current timezone, since it
706 reads a UTC time_t value and converts with localtime_r() to set the tm
707 fields, hence the use of SCM_DEFER_INTS. */
708 t.tm_isdst = -1;
709 SCM_DEFER_INTS;
710 if ((rest = strptime (str, fmt, &t)) == NULL)
711 {
712 /* POSIX doesn't say strptime sets errno, and on glibc 2.3.2 for
713 instance it doesn't. Force a sensible value for our error
714 message. */
715 errno = EINVAL;
716 SCM_SYSERROR;
717 }
718
719 SCM_ALLOW_INTS;
720 return scm_cons (filltime (&t, 0, NULL), SCM_I_MAKINUM (rest - str));
721 }
722 #undef FUNC_NAME
723 #endif /* HAVE_STRPTIME */
724
725 void
726 scm_init_stime()
727 {
728 scm_c_define ("internal-time-units-per-second",
729 scm_long2num((long) SCM_TIME_UNITS_PER_SECOND));
730
731 #ifdef HAVE_FTIME
732 if (!scm_your_base.time) ftime(&scm_your_base);
733 #else
734 if (!scm_your_base) time(&scm_your_base);
735 #endif
736
737 if (!scm_my_base) scm_my_base = mytime();
738
739 scm_add_feature ("current-time");
740 #include "libguile/stime.x"
741 }
742
743
744 /*
745 Local Variables:
746 c-file-style: "gnu"
747 End:
748 */