[project @ 1998-01-22 11:07:36 by sof]
[ghc-hetmet.git] / ghc / lib / required / Time.lhs
1 %
2 % (c) The GRASP/AQUA Project, Glasgow University, 1995-97
3 %
4 \section[Time]{Haskell 1.4 Time of Day Library}
5
6 The {\em Time} library provides standard functionality for
7 clock times, including timezone information (i.e, the functionality of
8 "time.h",  adapted to the Haskell environment), It follows RFC 1129 in
9 its use of Coordinated Universal Time (UTC).
10
11 \begin{code}
12 {-# OPTIONS -#include "cbits/timezone.h" -#include "cbits/stgio.h"  #-}
13
14 module Time 
15        (
16         Month,
17         Day,
18         CalendarTime(CalendarTime),
19         TimeDiff(TimeDiff),
20         ClockTime(..), -- non-standard, lib. report gives this as abstract
21
22         getClockTime, 
23         addToClockTime, 
24         diffClockTimes,
25
26         toCalendarTime, 
27         toUTCTime, 
28         toClockTime,
29         calendarTimeToString, 
30         formatCalendarTime
31        ) where
32
33 import PrelBase
34 import ST
35 import IOBase
36 import ArrBase
37 import STBase
38 import Unsafe   ( unsafePerformIO )
39 import ST
40 import Ix
41 import Addr
42 import Char     ( intToDigit )
43 import PackBase ( unpackCString )
44 import Locale
45
46 \end{code}
47
48 One way to partition and give name to chunks of a year and a week:
49
50 \begin{code}
51 data Month
52  = January   | February | March    | April
53  | May       | June     | July     | August
54  | September | October  | November | December
55  deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
56
57 data Day 
58  = Sunday | Monday | Tuesday | Wednesday
59  | Thursday | Friday | Saturday
60  deriving (Eq, Ord, Enum, Bounded, Ix, Read, Show)
61
62 \end{code}
63
64 @ClockTime@ is an abstract type, used for the internal clock time.
65 Clock times may be compared, converted to strings, or converted to an
66 external calendar time @CalendarTime@.
67
68 \begin{code}
69 data ClockTime = TOD Integer Integer deriving (Eq, Ord)
70 \end{code}
71
72 When a @ClockTime@ is shown, it is converted to a string of the form
73 @"Mon Nov 28 21:45:41 GMT 1994"@.
74
75 For now, we are restricted to roughly:
76 Fri Dec 13 20:45:52 1901 through Tue Jan 19 03:14:07 2038, because
77 we use the C library routines based on 32 bit integers.
78
79 \begin{code}
80 instance Show ClockTime where
81     showsPrec p (TOD sec@(J# a# s# d#) nsec) = showString $ unsafePerformIO $
82             allocChars 32               >>= \ buf ->
83             _ccall_ showTime (I# s#) (ByteArray bottom d#) buf
84                                         >>= \ str ->
85             return (unpackCString str)
86
87     showList = showList__ (showsPrec 0)
88 \end{code}
89
90
91 @CalendarTime@ is a user-readable and manipulable
92 representation of the internal $ClockTime$ type.  The
93 numeric fields have the following ranges.
94
95 \begin{verbatim}
96 Value         Range             Comments
97 -----         -----             --------
98
99 year    -maxInt .. maxInt       [Pre-Gregorian dates are inaccurate]
100 mon           0 .. 11           [Jan = 0, Dec = 11]
101 day           1 .. 31
102 hour          0 .. 23
103 min           0 .. 59
104 sec           0 .. 61           [Allows for two leap seconds]
105 picosec       0 .. (10^12)-1    [This could be over-precise?]
106 wday          0 .. 6            [Sunday = 0, Saturday = 6]
107 yday          0 .. 365          [364 in non-Leap years]
108 tz       -43200 .. 43200        [Variation from UTC in seconds]
109 \end{verbatim}
110
111 The {\em tzname} field is the name of the time zone.  The {\em isdst}
112 field indicates whether Daylight Savings Time would be in effect.
113
114 \begin{code}
115 data CalendarTime 
116  = CalendarTime  {
117      ctYear    :: Int,
118      ctMonth   :: Int,
119      ctDay     :: Int,
120      ctHour    :: Int,
121      ctMin     :: Int,
122      ctSec     :: Int,
123      ctPicosec :: Integer,
124      ctWDay    :: Day,
125      ctYDay    :: Int,
126      ctTZName  :: String,
127      ctTZ      :: Int,
128      ctIsDST   :: Bool
129  }
130  deriving (Eq,Ord,Read,Show)
131
132 \end{code}
133
134 The @TimeDiff@ type records the difference between two clock times in
135 a user-readable way.
136
137 \begin{code}
138 data TimeDiff
139  = TimeDiff {
140      tdYear    :: Int,
141      tdMonth   :: Int,
142      tdDay     :: Int,
143      tdHour    :: Int,
144      tdMin     :: Int,
145      tdSec     :: Int,
146      tdPicosec :: Integer -- not standard
147    }
148    deriving (Eq,Ord,Read,Show)
149 \end{code}
150
151 @getClockTime@ returns the current time in its internal representation.
152
153 \begin{code}
154 getClockTime :: IO ClockTime
155 getClockTime =
156     malloc1                                         >>= \ i1 ->
157     malloc1                                         >>= \ i2 ->
158     _ccall_ getClockTime i1 i2                      >>= \ rc ->
159     if rc == 0 
160         then
161             cvtUnsigned i1                          >>= \ sec ->
162             cvtUnsigned i2                          >>= \ nsec ->
163             return (TOD sec (nsec * 1000))
164         else
165             constructErrorAndFail "getClockTime"
166   where
167     malloc1 = IO $ \ s# ->
168         case newIntArray# 1# s# of 
169           StateAndMutableByteArray# s2# barr# -> 
170                 IOok s2# (MutableByteArray bottom barr#)
171
172     --  The C routine fills in an unsigned word.  We don't have 
173     --  `unsigned2Integer#,' so we freeze the data bits and use them 
174     --  for an MP_INT structure.  Note that zero is still handled specially,
175     --  although (J# 1# 1# (ptr to 0#)) is probably acceptable to gmp.
176
177     cvtUnsigned (MutableByteArray _ arr#) = IO $ \ s# ->
178         case readIntArray# arr# 0# s# of 
179           StateAndInt# s2# r# ->
180             if r# ==# 0# 
181                 then IOok s2# 0
182                 else case unsafeFreezeByteArray# arr# s2# of
183                         StateAndByteArray# s3# frozen# -> 
184                                 IOok s3# (J# 1# 1# frozen#)
185
186 \end{code}
187
188 @addToClockTime@ {\em d} {\em t} adds a time difference {\em d} and a
189 clock time {\em t} to yield a new clock time.  The difference {\em d}
190 may be either positive or negative.  @[diffClockTimes@ {\em t1} {\em
191 t2} returns the difference between two clock times {\em t1} and {\em
192 t2} as a @TimeDiff@.
193
194
195 \begin{code}
196 addToClockTime  :: TimeDiff  -> ClockTime -> ClockTime
197 addToClockTime (TimeDiff year mon day hour min sec psec) 
198                (TOD c_sec c_psec) = unsafePerformIO $
199     allocWords (``sizeof(time_t)'') >>= \ res ->
200     _ccall_ toClockSec year mon day hour min sec 0 res 
201                                     >>= \ ptr@(A# ptr#) ->
202     if ptr /= ``NULL'' 
203         then let
204                diff_sec  = (int2Integer# (indexIntOffAddr# ptr# 0#))
205                diff_psec = psec
206              in
207              return (TOD (c_sec + diff_sec) (c_psec + diff_psec))
208         else
209             error "Time.addToClockTime: can't perform conversion of TimeDiff"
210
211
212 diffClockTimes  :: ClockTime -> ClockTime -> TimeDiff
213 diffClockTimes tod_a tod_b =
214   let
215    CalendarTime year_a mon_a day_a hour_a min_a sec_a psec_a _ _ _ _ _ = toCalendarTime tod_a
216    CalendarTime year_b mon_b day_b hour_b min_b sec_b psec_b _ _ _ _ _ = toCalendarTime tod_b
217   in
218   TimeDiff (year_a - year_b) 
219            (mon_a  - mon_b) 
220            (day_a  - day_b)
221            (hour_a - hour_b)
222            (min_b  - min_a)
223            (sec_a  - sec_b)
224            (psec_a - psec_b)
225 \end{code}
226
227 @toCalendarTime@ {\em t} converts {\em t} to a local time, modified by
228 the current timezone and daylight savings time settings.  @toUTCTime@
229 {\em t} converts {\em t} into UTC time.  @toClockTime@ {\em l}
230 converts {\em l} into the corresponding internal @ClockTime@.  The
231 {\em wday}, {\em yday}, {\em tzname}, and {\em isdst} fields are
232 ignored.
233
234 \begin{code}
235 toCalendarTime :: ClockTime -> CalendarTime
236 toCalendarTime (TOD sec@(J# a# s# d#) psec) = unsafePerformIO $
237     allocWords (``sizeof(struct tm)''::Int)         >>= \ res ->
238     allocChars 32                                   >>= \ zoneNm ->
239     _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm   >>= \ () ->
240     _ccall_ toLocalTime (I# s#) (ByteArray bottom d#) res
241                                                     >>= \ tm ->
242     if tm == (``NULL''::Addr) 
243         then error "Time.toCalendarTime: out of range"
244         else
245             _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm       >>= \ sec ->
246             _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm       >>= \ min ->
247             _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm      >>= \ hour ->
248             _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm      >>= \ mday ->
249             _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm       >>= \ mon ->
250             _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm      >>= \ year ->
251             _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm      >>= \ wday ->
252             _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm      >>= \ yday ->
253             _casm_ ``%r = ((struct tm *)%0)->tm_isdst;'' tm     >>= \ isdst ->
254             _ccall_ ZONE tm                                     >>= \ zone ->
255             _ccall_ GMTOFF tm                                   >>= \ tz ->
256             let
257              tzname = unpackCString zone
258             in
259             return (CalendarTime (1900+year) mon mday hour min sec psec 
260                           (toEnum wday) yday tzname tz (isdst /= 0))
261
262 toUTCTime :: ClockTime -> CalendarTime
263 toUTCTime  (TOD sec@(J# a# s# d#) psec) = unsafePerformIO (
264         allocWords (``sizeof(struct tm)''::Int)                     >>= \ res ->
265         allocChars 32                                               >>= \ zoneNm ->
266         _casm_ ``SETZONE((struct tm *)%0,(char *)%1); '' res zoneNm >>= \ () ->
267         _ccall_ toUTCTime (I# s#) (ByteArray bottom d#) res
268                                                     >>= \ tm ->
269     if tm == (``NULL''::Addr) 
270         then error "Time.toUTCTime: out of range"
271         else
272             _casm_ ``%r = ((struct tm *)%0)->tm_sec;'' tm       >>= \ sec ->
273             _casm_ ``%r = ((struct tm *)%0)->tm_min;'' tm       >>= \ min ->
274             _casm_ ``%r = ((struct tm *)%0)->tm_hour;'' tm      >>= \ hour ->
275             _casm_ ``%r = ((struct tm *)%0)->tm_mday;'' tm      >>= \ mday ->
276             _casm_ ``%r = ((struct tm *)%0)->tm_mon;'' tm       >>= \ mon ->
277             _casm_ ``%r = ((struct tm *)%0)->tm_year;'' tm      >>= \ year ->
278             _casm_ ``%r = ((struct tm *)%0)->tm_wday;'' tm      >>= \ wday ->
279             _casm_ ``%r = ((struct tm *)%0)->tm_yday;'' tm      >>= \ yday ->
280             return (CalendarTime (1900+year) mon mday hour min sec psec 
281                           (toEnum wday) yday "UTC" 0 False)
282     )
283
284 toClockTime :: CalendarTime -> ClockTime
285 toClockTime (CalendarTime year mon mday hour min sec psec wday yday tzname tz isdst) =
286     if psec < 0 || psec > 999999999999 then
287         error "Time.toClockTime: picoseconds out of range"
288     else if tz < -43200 || tz > 43200 then
289         error "Time.toClockTime: timezone offset out of range"
290     else
291         unsafePerformIO (
292             allocWords (``sizeof(time_t)'') >>= \ res ->
293             _ccall_ toClockSec year mon mday hour min sec isDst res
294                                                     >>= \ ptr@(A# ptr#) ->
295             if ptr /= ``NULL'' then
296                 return (TOD (int2Integer# (indexIntOffAddr# ptr# 0#)) psec)
297             else
298                 error "Time.toClockTime: can't perform conversion"
299         )
300     where
301      isDst = if isdst then (1::Int) else 0
302
303 bottom :: (Int,Int)
304 bottom = error "Time.bottom"
305
306
307 -- (copied from PosixUtil, for now)
308 -- Allocate a mutable array of characters with no indices.
309
310 allocChars :: Int -> IO (MutableByteArray RealWorld ())
311 allocChars (I# size#) = IO $ \ s# ->
312     case newCharArray# size# s# of 
313       StateAndMutableByteArray# s2# barr# -> 
314         IOok s2# (MutableByteArray bot barr#)
315   where
316     bot = error "Time.allocChars"
317
318 -- Allocate a mutable array of words with no indices
319
320 allocWords :: Int -> IO (MutableByteArray RealWorld ())
321 allocWords (I# size#) = IO $ \ s# ->
322     case newIntArray# size# s# of 
323       StateAndMutableByteArray# s2# barr# -> 
324         IOok s2# (MutableByteArray bot barr#)
325   where
326     bot = error "Time.allocWords"
327
328 \end{code}
329
330 \begin{code}
331 calendarTimeToString  :: CalendarTime -> String
332 calendarTimeToString  =  formatCalendarTime defaultTimeLocale "%c"
333
334 formatCalendarTime :: TimeLocale -> String -> CalendarTime -> String
335 formatCalendarTime l fmt ct@(CalendarTime year mon day hour min sec sdec 
336                                            wday yday tzname _ _) =
337         doFmt fmt
338   where doFmt ('%':c:cs) = decode c ++ doFmt cs
339         doFmt (c:cs) = c : doFmt cs
340         doFmt "" = ""
341         to12 h = let h' = h `mod` 12 in if h == 0 then 12 else h
342         decode 'A' = fst (wDays l  !! fromEnum wday)
343         decode 'a' = snd (wDays l  !! fromEnum wday)
344         decode 'B' = fst (months l !! fromEnum mon)
345         decode 'b' = snd (months l !! fromEnum mon)
346         decode 'h' = snd (months l !! fromEnum mon)
347         decode 'C' = show2 (year `quot` 100)
348         decode 'c' = doFmt (dateTimeFmt l)
349         decode 'D' = doFmt "%m/%d/%y"
350         decode 'd' = show2 day
351         decode 'e' = show2' day
352         decode 'H' = show2 hour
353         decode 'I' = show2 (to12 hour)
354         decode 'j' = show3 yday
355         decode 'k' = show2' hour
356         decode 'l' = show2' (to12 hour)
357         decode 'M' = show2 min
358         decode 'm' = show2 (fromEnum mon+1)
359         decode 'n' = "\n"
360         decode 'p' = (if hour < 12 then fst else snd) (amPm l)
361         decode 'R' = doFmt "%H:%M"
362         decode 'r' = doFmt (time12Fmt l)
363         decode 'T' = doFmt "%H:%M:%S"
364         decode 't' = "\t"
365         decode 'S' = show2 sec
366         decode 's' = show2 sec -- Implementation-dependent, sez the lib doc..
367         decode 'U' = show2 ((yday + 7 - fromEnum wday) `div` 7)
368         decode 'u' = show (let n = fromEnum wday in 
369                            if n == 0 then 7 else n)
370         decode 'V' = 
371             let (week, days) = 
372                    (yday + 7 - if fromEnum wday > 0 then 
373                                fromEnum wday - 1 else 6) `divMod` 7
374             in  show2 (if days >= 4 then
375                           week+1 
376                        else if week == 0 then 53 else week)
377
378         decode 'W' = 
379             show2 ((yday + 7 - if fromEnum wday > 0 then 
380                                fromEnum wday - 1 else 6) `div` 7)
381         decode 'w' = show (fromEnum wday)
382         decode 'X' = doFmt (timeFmt l)
383         decode 'x' = doFmt (dateFmt l)
384         decode 'Y' = show year
385         decode 'y' = show2 (year `rem` 100)
386         decode 'Z' = tzname
387         decode '%' = "%"
388         decode c   = [c]
389
390 show2, show2', show3 :: Int -> String
391 show2 x = [intToDigit (x `quot` 10), intToDigit (x `rem` 10)]
392
393 show2' x = if x < 10 then [ ' ', intToDigit x] else show2 x
394
395 show3 x = intToDigit (x `quot` 100) : show2 (x `rem` 100)
396 \end{code}