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