OSDN Git Service

Licensing changes to GPLv3 resp. GPLv3 with GCC Runtime Exception.
[pf3gnuchains/gcc-fork.git] / gcc / ada / a-calend.adb
1 ------------------------------------------------------------------------------
2 --                                                                          --
3 --                         GNAT RUN-TIME COMPONENTS                         --
4 --                                                                          --
5 --                         A D A . C A L E N D A R                          --
6 --                                                                          --
7 --                                 B o d y                                  --
8 --                                                                          --
9 --          Copyright (C) 1992-2009, Free Software Foundation, Inc.         --
10 --                                                                          --
11 -- GNAT is free software;  you can  redistribute it  and/or modify it under --
12 -- terms of the  GNU General Public License as published  by the Free Soft- --
13 -- ware  Foundation;  either version 3,  or (at your option) any later ver- --
14 -- sion.  GNAT is distributed in the hope that it will be useful, but WITH- --
15 -- OUT ANY WARRANTY;  without even the  implied warranty of MERCHANTABILITY --
16 -- or FITNESS FOR A PARTICULAR PURPOSE.                                     --
17 --                                                                          --
18 -- As a special exception under Section 7 of GPL version 3, you are granted --
19 -- additional permissions described in the GCC Runtime Library Exception,   --
20 -- version 3.1, as published by the Free Software Foundation.               --
21 --                                                                          --
22 -- You should have received a copy of the GNU General Public License and    --
23 -- a copy of the GCC Runtime Library Exception along with this program;     --
24 -- see the files COPYING3 and COPYING.RUNTIME respectively.  If not, see    --
25 -- <http://www.gnu.org/licenses/>.                                          --
26 --                                                                          --
27 -- GNAT was originally developed  by the GNAT team at  New York University. --
28 -- Extensive contributions were provided by Ada Core Technologies Inc.      --
29 --                                                                          --
30 ------------------------------------------------------------------------------
31
32 with Ada.Unchecked_Conversion;
33
34 with System.OS_Primitives;
35
36 package body Ada.Calendar is
37
38    --------------------------
39    -- Implementation Notes --
40    --------------------------
41
42    --  In complex algorithms, some variables of type Ada.Calendar.Time carry
43    --  suffix _S or _N to denote units of seconds or nanoseconds.
44    --
45    --  Because time is measured in different units and from different origins
46    --  on various targets, a system independent model is incorporated into
47    --  Ada.Calendar. The idea behind the design is to encapsulate all target
48    --  dependent machinery in a single package, thus providing a uniform
49    --  interface to all existing and any potential children.
50
51    --     package Ada.Calendar
52    --        procedure Split (5 parameters) -------+
53    --                                              | Call from local routine
54    --     private                                  |
55    --        package Formatting_Operations         |
56    --           procedure Split (11 parameters) <--+
57    --        end Formatting_Operations             |
58    --     end Ada.Calendar                         |
59    --                                              |
60    --     package Ada.Calendar.Formatting          | Call from child routine
61    --        procedure Split (9 or 10 parameters) -+
62    --     end Ada.Calendar.Formatting
63
64    --  The behaviour of the interfacing routines is controlled via various
65    --  flags. All new Ada 2005 types from children of Ada.Calendar are
66    --  emulated by a similar type. For instance, type Day_Number is replaced
67    --  by Integer in various routines. One ramification of this model is that
68    --  the caller site must perform validity checks on returned results.
69    --  The end result of this model is the lack of target specific files per
70    --  child of Ada.Calendar (a-calfor, a-calfor-vms, a-calfor-vxwors, etc).
71
72    -----------------------
73    -- Local Subprograms --
74    -----------------------
75
76    procedure Check_Within_Time_Bounds (T : Time_Rep);
77    --  Ensure that a time representation value falls withing the bounds of Ada
78    --  time. Leap seconds support is taken into account.
79
80    procedure Cumulative_Leap_Seconds
81      (Start_Date    : Time_Rep;
82       End_Date      : Time_Rep;
83       Elapsed_Leaps : out Natural;
84       Next_Leap     : out Time_Rep);
85    --  Elapsed_Leaps is the sum of the leap seconds that have occurred on or
86    --  after Start_Date and before (strictly before) End_Date. Next_Leap_Sec
87    --  represents the next leap second occurrence on or after End_Date. If
88    --  there are no leaps seconds after End_Date, End_Of_Time is returned.
89    --  End_Of_Time can be used as End_Date to count all the leap seconds that
90    --  have occurred on or after Start_Date.
91    --
92    --  Note: Any sub seconds of Start_Date and End_Date are discarded before
93    --  the calculations are done. For instance: if 113 seconds is a leap
94    --  second (it isn't) and 113.5 is input as an End_Date, the leap second
95    --  at 113 will not be counted in Leaps_Between, but it will be returned
96    --  as Next_Leap_Sec. Thus, if the caller wants to know if the End_Date is
97    --  a leap second, the comparison should be:
98    --
99    --     End_Date >= Next_Leap_Sec;
100    --
101    --  After_Last_Leap is designed so that this comparison works without
102    --  having to first check if Next_Leap_Sec is a valid leap second.
103
104    function Duration_To_Time_Rep is
105      new Ada.Unchecked_Conversion (Duration, Time_Rep);
106    --  Convert a duration value into a time representation value
107
108    function Time_Rep_To_Duration is
109      new Ada.Unchecked_Conversion (Time_Rep, Duration);
110    --  Convert a time representation value into a duration value
111
112    -----------------
113    -- Local Types --
114    -----------------
115
116    --  An integer time duration. The type is used whenever a positive elapsed
117    --  duration is needed, for instance when splitting a time value. Here is
118    --  how Time_Rep and Time_Dur are related:
119
120    --            'First  Ada_Low                  Ada_High  'Last
121    --  Time_Rep: +-------+------------------------+---------+
122    --  Time_Dur:         +------------------------+---------+
123    --                    0                                  'Last
124
125    type Time_Dur is range 0 .. 2 ** 63 - 1;
126
127    --------------------------
128    -- Leap seconds control --
129    --------------------------
130
131    Flag : Integer;
132    pragma Import (C, Flag, "__gl_leap_seconds_support");
133    --  This imported value is used to determine whether the compilation had
134    --  binder flag "-y" present which enables leap seconds. A value of zero
135    --  signifies no leap seconds support while a value of one enables the
136    --  support.
137
138    Leap_Support : constant Boolean := Flag = 1;
139    --  The above flag controls the usage of leap seconds in all Ada.Calendar
140    --  routines.
141
142    Leap_Seconds_Count : constant Natural := 23;
143
144    ---------------------
145    -- Local Constants --
146    ---------------------
147
148    Ada_Min_Year          : constant Year_Number := Year_Number'First;
149    Secs_In_Four_Years    : constant := (3 * 365 + 366) * Secs_In_Day;
150    Secs_In_Non_Leap_Year : constant := 365 * Secs_In_Day;
151
152    --  Lower and upper bound of Ada time. The zero (0) value of type Time is
153    --  positioned at year 2150. Note that the lower and upper bound account
154    --  for the non-leap centennial years.
155
156    Ada_Low  : constant Time_Rep := -(61 * 366 + 188 * 365) * Nanos_In_Day;
157    Ada_High : constant Time_Rep :=  (60 * 366 + 190 * 365) * Nanos_In_Day;
158
159    --  Even though the upper bound of time is 2399-12-31 23:59:59.999999999
160    --  UTC, it must be increased to include all leap seconds.
161
162    Ada_High_And_Leaps : constant Time_Rep :=
163                           Ada_High + Time_Rep (Leap_Seconds_Count) * Nano;
164
165    --  Two constants used in the calculations of elapsed leap seconds.
166    --  End_Of_Time is later than Ada_High in time zone -28. Start_Of_Time
167    --  is earlier than Ada_Low in time zone +28.
168
169    End_Of_Time   : constant Time_Rep :=
170                      Ada_High + Time_Rep (3) * Nanos_In_Day;
171    Start_Of_Time : constant Time_Rep :=
172                      Ada_Low - Time_Rep (3) * Nanos_In_Day;
173
174    --  The Unix lower time bound expressed as nanoseconds since the
175    --  start of Ada time in UTC.
176
177    Unix_Min : constant Time_Rep :=
178                 Ada_Low + Time_Rep (17 * 366 + 52 * 365) * Nanos_In_Day;
179
180    Cumulative_Days_Before_Month :
181      constant array (Month_Number) of Natural :=
182        (0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334);
183
184    --  The following table contains the hard time values of all existing leap
185    --  seconds. The values are produced by the utility program xleaps.adb.
186
187    Leap_Second_Times : constant array (1 .. Leap_Seconds_Count) of Time_Rep :=
188      (-5601484800000000000,
189       -5585587199000000000,
190       -5554051198000000000,
191       -5522515197000000000,
192       -5490979196000000000,
193       -5459356795000000000,
194       -5427820794000000000,
195       -5396284793000000000,
196       -5364748792000000000,
197       -5317487991000000000,
198       -5285951990000000000,
199       -5254415989000000000,
200       -5191257588000000000,
201       -5112287987000000000,
202       -5049129586000000000,
203       -5017593585000000000,
204       -4970332784000000000,
205       -4938796783000000000,
206       -4907260782000000000,
207       -4859827181000000000,
208       -4812566380000000000,
209       -4765132779000000000,
210       -4544207978000000000);
211
212    ---------
213    -- "+" --
214    ---------
215
216    function "+" (Left : Time; Right : Duration) return Time is
217       pragma Unsuppress (Overflow_Check);
218       Left_N : constant Time_Rep := Time_Rep (Left);
219    begin
220       return Time (Left_N + Duration_To_Time_Rep (Right));
221    exception
222       when Constraint_Error =>
223          raise Time_Error;
224    end "+";
225
226    function "+" (Left : Duration; Right : Time) return Time is
227    begin
228       return Right + Left;
229    end "+";
230
231    ---------
232    -- "-" --
233    ---------
234
235    function "-" (Left : Time; Right : Duration) return Time is
236       pragma Unsuppress (Overflow_Check);
237       Left_N : constant Time_Rep := Time_Rep (Left);
238    begin
239       return Time (Left_N - Duration_To_Time_Rep (Right));
240    exception
241       when Constraint_Error =>
242          raise Time_Error;
243    end "-";
244
245    function "-" (Left : Time; Right : Time) return Duration is
246       pragma Unsuppress (Overflow_Check);
247
248       --  The bounds of type Duration expressed as time representations
249
250       Dur_Low  : constant Time_Rep := Duration_To_Time_Rep (Duration'First);
251       Dur_High : constant Time_Rep := Duration_To_Time_Rep (Duration'Last);
252
253       Res_N : Time_Rep;
254
255    begin
256       Res_N := Time_Rep (Left) - Time_Rep (Right);
257
258       --  Due to the extended range of Ada time, "-" is capable of producing
259       --  results which may exceed the range of Duration. In order to prevent
260       --  the generation of bogus values by the Unchecked_Conversion, we apply
261       --  the following check.
262
263       if Res_N < Dur_Low
264         or else Res_N > Dur_High
265       then
266          raise Time_Error;
267       end if;
268
269       return Time_Rep_To_Duration (Res_N);
270    exception
271       when Constraint_Error =>
272          raise Time_Error;
273    end "-";
274
275    ---------
276    -- "<" --
277    ---------
278
279    function "<" (Left, Right : Time) return Boolean is
280    begin
281       return Time_Rep (Left) < Time_Rep (Right);
282    end "<";
283
284    ----------
285    -- "<=" --
286    ----------
287
288    function "<=" (Left, Right : Time) return Boolean is
289    begin
290       return Time_Rep (Left) <= Time_Rep (Right);
291    end "<=";
292
293    ---------
294    -- ">" --
295    ---------
296
297    function ">" (Left, Right : Time) return Boolean is
298    begin
299       return Time_Rep (Left) > Time_Rep (Right);
300    end ">";
301
302    ----------
303    -- ">=" --
304    ----------
305
306    function ">=" (Left, Right : Time) return Boolean is
307    begin
308       return Time_Rep (Left) >= Time_Rep (Right);
309    end ">=";
310
311    ------------------------------
312    -- Check_Within_Time_Bounds --
313    ------------------------------
314
315    procedure Check_Within_Time_Bounds (T : Time_Rep) is
316    begin
317       if Leap_Support then
318          if T < Ada_Low or else T > Ada_High_And_Leaps then
319             raise Time_Error;
320          end if;
321       else
322          if T < Ada_Low or else T > Ada_High then
323             raise Time_Error;
324          end if;
325       end if;
326    end Check_Within_Time_Bounds;
327
328    -----------
329    -- Clock --
330    -----------
331
332    function Clock return Time is
333       Elapsed_Leaps : Natural;
334       Next_Leap_N   : Time_Rep;
335
336       --  The system clock returns the time in UTC since the Unix Epoch of
337       --  1970-01-01 00:00:00.0. We perform an origin shift to the Ada Epoch
338       --  by adding the number of nanoseconds between the two origins.
339
340       Res_N : Time_Rep :=
341                 Duration_To_Time_Rep (System.OS_Primitives.Clock) +
342                   Unix_Min;
343
344    begin
345       --  If the target supports leap seconds, determine the number of leap
346       --  seconds elapsed until this moment.
347
348       if Leap_Support then
349          Cumulative_Leap_Seconds
350            (Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
351
352          --  The system clock may fall exactly on a leap second
353
354          if Res_N >= Next_Leap_N then
355             Elapsed_Leaps := Elapsed_Leaps + 1;
356          end if;
357
358       --  The target does not support leap seconds
359
360       else
361          Elapsed_Leaps := 0;
362       end if;
363
364       Res_N := Res_N + Time_Rep (Elapsed_Leaps) * Nano;
365
366       return Time (Res_N);
367    end Clock;
368
369    -----------------------------
370    -- Cumulative_Leap_Seconds --
371    -----------------------------
372
373    procedure Cumulative_Leap_Seconds
374      (Start_Date    : Time_Rep;
375       End_Date      : Time_Rep;
376       Elapsed_Leaps : out Natural;
377       Next_Leap     : out Time_Rep)
378    is
379       End_Index   : Positive;
380       End_T       : Time_Rep := End_Date;
381       Start_Index : Positive;
382       Start_T     : Time_Rep := Start_Date;
383
384    begin
385       --  Both input dates must be normalized to UTC
386
387       pragma Assert (Leap_Support and then End_Date >= Start_Date);
388
389       Next_Leap := End_Of_Time;
390
391       --  Make sure that the end date does not exceed the upper bound
392       --  of Ada time.
393
394       if End_Date > Ada_High then
395          End_T := Ada_High;
396       end if;
397
398       --  Remove the sub seconds from both dates
399
400       Start_T := Start_T - (Start_T mod Nano);
401       End_T   := End_T   - (End_T   mod Nano);
402
403       --  Some trivial cases:
404       --                     Leap 1 . . . Leap N
405       --  ---+========+------+############+-------+========+-----
406       --     Start_T  End_T                       Start_T  End_T
407
408       if End_T < Leap_Second_Times (1) then
409          Elapsed_Leaps := 0;
410          Next_Leap     := Leap_Second_Times (1);
411          return;
412
413       elsif Start_T > Leap_Second_Times (Leap_Seconds_Count) then
414          Elapsed_Leaps := 0;
415          Next_Leap     := End_Of_Time;
416          return;
417       end if;
418
419       --  Perform the calculations only if the start date is within the leap
420       --  second occurrences table.
421
422       if Start_T <= Leap_Second_Times (Leap_Seconds_Count) then
423
424          --    1    2                  N - 1   N
425          --  +----+----+--  . . .  --+-------+---+
426          --  | T1 | T2 |             | N - 1 | N |
427          --  +----+----+--  . . .  --+-------+---+
428          --         ^                   ^
429          --         | Start_Index       | End_Index
430          --         +-------------------+
431          --             Leaps_Between
432
433          --  The idea behind the algorithm is to iterate and find two
434          --  closest dates which are after Start_T and End_T. Their
435          --  corresponding index difference denotes the number of leap
436          --  seconds elapsed.
437
438          Start_Index := 1;
439          loop
440             exit when Leap_Second_Times (Start_Index) >= Start_T;
441             Start_Index := Start_Index + 1;
442          end loop;
443
444          End_Index := Start_Index;
445          loop
446             exit when End_Index > Leap_Seconds_Count
447               or else Leap_Second_Times (End_Index) >= End_T;
448             End_Index := End_Index + 1;
449          end loop;
450
451          if End_Index <= Leap_Seconds_Count then
452             Next_Leap := Leap_Second_Times (End_Index);
453          end if;
454
455          Elapsed_Leaps := End_Index - Start_Index;
456
457       else
458          Elapsed_Leaps := 0;
459       end if;
460    end Cumulative_Leap_Seconds;
461
462    ---------
463    -- Day --
464    ---------
465
466    function Day (Date : Time) return Day_Number is
467       D : Day_Number;
468       Y : Year_Number;
469       M : Month_Number;
470       S : Day_Duration;
471       pragma Unreferenced (Y, M, S);
472    begin
473       Split (Date, Y, M, D, S);
474       return D;
475    end Day;
476
477    -------------
478    -- Is_Leap --
479    -------------
480
481    function Is_Leap (Year : Year_Number) return Boolean is
482    begin
483       --  Leap centennial years
484
485       if Year mod 400 = 0 then
486          return True;
487
488       --  Non-leap centennial years
489
490       elsif Year mod 100 = 0 then
491          return False;
492
493       --  Regular years
494
495       else
496          return Year mod 4 = 0;
497       end if;
498    end Is_Leap;
499
500    -----------
501    -- Month --
502    -----------
503
504    function Month (Date : Time) return Month_Number is
505       Y : Year_Number;
506       M : Month_Number;
507       D : Day_Number;
508       S : Day_Duration;
509       pragma Unreferenced (Y, D, S);
510    begin
511       Split (Date, Y, M, D, S);
512       return M;
513    end Month;
514
515    -------------
516    -- Seconds --
517    -------------
518
519    function Seconds (Date : Time) return Day_Duration is
520       Y : Year_Number;
521       M : Month_Number;
522       D : Day_Number;
523       S : Day_Duration;
524       pragma Unreferenced (Y, M, D);
525    begin
526       Split (Date, Y, M, D, S);
527       return S;
528    end Seconds;
529
530    -----------
531    -- Split --
532    -----------
533
534    procedure Split
535      (Date    : Time;
536       Year    : out Year_Number;
537       Month   : out Month_Number;
538       Day     : out Day_Number;
539       Seconds : out Day_Duration)
540    is
541       H  : Integer;
542       M  : Integer;
543       Se : Integer;
544       Ss : Duration;
545       Le : Boolean;
546
547       pragma Unreferenced (H, M, Se, Ss, Le);
548
549    begin
550       --  Even though the input time zone is UTC (0), the flag Is_Ada_05 will
551       --  ensure that Split picks up the local time zone.
552
553       Formatting_Operations.Split
554         (Date      => Date,
555          Year      => Year,
556          Month     => Month,
557          Day       => Day,
558          Day_Secs  => Seconds,
559          Hour      => H,
560          Minute    => M,
561          Second    => Se,
562          Sub_Sec   => Ss,
563          Leap_Sec  => Le,
564          Is_Ada_05 => False,
565          Time_Zone => 0);
566
567       --  Validity checks
568
569       if not Year'Valid
570         or else not Month'Valid
571         or else not Day'Valid
572         or else not Seconds'Valid
573       then
574          raise Time_Error;
575       end if;
576    end Split;
577
578    -------------
579    -- Time_Of --
580    -------------
581
582    function Time_Of
583      (Year    : Year_Number;
584       Month   : Month_Number;
585       Day     : Day_Number;
586       Seconds : Day_Duration := 0.0) return Time
587    is
588       --  The values in the following constants are irrelevant, they are just
589       --  placeholders; the choice of constructing a Day_Duration value is
590       --  controlled by the Use_Day_Secs flag.
591
592       H  : constant Integer := 1;
593       M  : constant Integer := 1;
594       Se : constant Integer := 1;
595       Ss : constant Duration := 0.1;
596
597    begin
598       --  Validity checks
599
600       if not Year'Valid
601         or else not Month'Valid
602         or else not Day'Valid
603         or else not Seconds'Valid
604       then
605          raise Time_Error;
606       end if;
607
608       --  Even though the input time zone is UTC (0), the flag Is_Ada_05 will
609       --  ensure that Split picks up the local time zone.
610
611       return
612         Formatting_Operations.Time_Of
613           (Year         => Year,
614            Month        => Month,
615            Day          => Day,
616            Day_Secs     => Seconds,
617            Hour         => H,
618            Minute       => M,
619            Second       => Se,
620            Sub_Sec      => Ss,
621            Leap_Sec     => False,
622            Use_Day_Secs => True,
623            Is_Ada_05    => False,
624            Time_Zone    => 0);
625    end Time_Of;
626
627    ----------
628    -- Year --
629    ----------
630
631    function Year (Date : Time) return Year_Number is
632       Y : Year_Number;
633       M : Month_Number;
634       D : Day_Number;
635       S : Day_Duration;
636       pragma Unreferenced (M, D, S);
637    begin
638       Split (Date, Y, M, D, S);
639       return Y;
640    end Year;
641
642    --  The following packages assume that Time is a signed 64 bit integer
643    --  type, the units are nanoseconds and the origin is the start of Ada
644    --  time (1901-01-01 00:00:00.0 UTC).
645
646    ---------------------------
647    -- Arithmetic_Operations --
648    ---------------------------
649
650    package body Arithmetic_Operations is
651
652       ---------
653       -- Add --
654       ---------
655
656       function Add (Date : Time; Days : Long_Integer) return Time is
657          pragma Unsuppress (Overflow_Check);
658          Date_N : constant Time_Rep := Time_Rep (Date);
659       begin
660          return Time (Date_N + Time_Rep (Days) * Nanos_In_Day);
661       exception
662          when Constraint_Error =>
663             raise Time_Error;
664       end Add;
665
666       ----------------
667       -- Difference --
668       ----------------
669
670       procedure Difference
671         (Left         : Time;
672          Right        : Time;
673          Days         : out Long_Integer;
674          Seconds      : out Duration;
675          Leap_Seconds : out Integer)
676       is
677          Res_Dur       : Time_Dur;
678          Earlier       : Time_Rep;
679          Elapsed_Leaps : Natural;
680          Later         : Time_Rep;
681          Negate        : Boolean := False;
682          Next_Leap_N   : Time_Rep;
683          Sub_Secs      : Duration;
684          Sub_Secs_Diff : Time_Rep;
685
686       begin
687          --  Both input time values are assumed to be in UTC
688
689          if Left >= Right then
690             Later   := Time_Rep (Left);
691             Earlier := Time_Rep (Right);
692          else
693             Later   := Time_Rep (Right);
694             Earlier := Time_Rep (Left);
695             Negate  := True;
696          end if;
697
698          --  If the target supports leap seconds, process them
699
700          if Leap_Support then
701             Cumulative_Leap_Seconds
702               (Earlier, Later, Elapsed_Leaps, Next_Leap_N);
703
704             if Later >= Next_Leap_N then
705                Elapsed_Leaps := Elapsed_Leaps + 1;
706             end if;
707
708          --  The target does not support leap seconds
709
710          else
711             Elapsed_Leaps := 0;
712          end if;
713
714          --  Sub seconds processing. We add the resulting difference to one
715          --  of the input dates in order to account for any potential rounding
716          --  of the difference in the next step.
717
718          Sub_Secs_Diff := Later mod Nano - Earlier mod Nano;
719          Earlier       := Earlier + Sub_Secs_Diff;
720          Sub_Secs      := Duration (Sub_Secs_Diff) / Nano_F;
721
722          --  Difference processing. This operation should be able to calculate
723          --  the difference between opposite values which are close to the end
724          --  and start of Ada time. To accommodate the large range, we convert
725          --  to seconds. This action may potentially round the two values and
726          --  either add or drop a second. We compensate for this issue in the
727          --  previous step.
728
729          Res_Dur :=
730            Time_Dur (Later / Nano - Earlier / Nano) - Time_Dur (Elapsed_Leaps);
731
732          Days         := Long_Integer (Res_Dur / Secs_In_Day);
733          Seconds      := Duration (Res_Dur mod Secs_In_Day) + Sub_Secs;
734          Leap_Seconds := Integer (Elapsed_Leaps);
735
736          if Negate then
737             Days    := -Days;
738             Seconds := -Seconds;
739
740             if Leap_Seconds /= 0 then
741                Leap_Seconds := -Leap_Seconds;
742             end if;
743          end if;
744       end Difference;
745
746       --------------
747       -- Subtract --
748       --------------
749
750       function Subtract (Date : Time; Days : Long_Integer) return Time is
751          pragma Unsuppress (Overflow_Check);
752          Date_N : constant Time_Rep := Time_Rep (Date);
753       begin
754          return Time (Date_N - Time_Rep (Days) * Nanos_In_Day);
755       exception
756          when Constraint_Error =>
757             raise Time_Error;
758       end Subtract;
759
760    end Arithmetic_Operations;
761
762    ---------------------------
763    -- Conversion_Operations --
764    ---------------------------
765
766    package body Conversion_Operations is
767
768       Epoch_Offset : constant Time_Rep :=
769                        (136 * 365 + 44 * 366) * Nanos_In_Day;
770       --  The difference between 2150-1-1 UTC and 1970-1-1 UTC expressed in
771       --  nanoseconds. Note that year 2100 is non-leap.
772
773       -----------------
774       -- To_Ada_Time --
775       -----------------
776
777       function To_Ada_Time (Unix_Time : Long_Integer) return Time is
778          pragma Unsuppress (Overflow_Check);
779          Unix_Rep : constant Time_Rep := Time_Rep (Unix_Time) * Nano;
780       begin
781          return Time (Unix_Rep - Epoch_Offset);
782       exception
783          when Constraint_Error =>
784             raise Time_Error;
785       end To_Ada_Time;
786
787       -----------------
788       -- To_Ada_Time --
789       -----------------
790
791       function To_Ada_Time
792         (tm_year  : Integer;
793          tm_mon   : Integer;
794          tm_day   : Integer;
795          tm_hour  : Integer;
796          tm_min   : Integer;
797          tm_sec   : Integer;
798          tm_isdst : Integer) return Time
799       is
800          pragma Unsuppress (Overflow_Check);
801          Year   : Year_Number;
802          Month  : Month_Number;
803          Day    : Day_Number;
804          Second : Integer;
805          Leap   : Boolean;
806          Result : Time_Rep;
807
808       begin
809          --  Input processing
810
811          Year  := Year_Number (1900 + tm_year);
812          Month := Month_Number (1 + tm_mon);
813          Day   := Day_Number (tm_day);
814
815          --  Step 1: Validity checks of input values
816
817          if not Year'Valid
818            or else not Month'Valid
819            or else not Day'Valid
820            or else tm_hour not in 0 .. 24
821            or else tm_min not in 0 .. 59
822            or else tm_sec not in 0 .. 60
823            or else tm_isdst not in -1 .. 1
824          then
825             raise Time_Error;
826          end if;
827
828          --  Step 2: Potential leap second
829
830          if tm_sec = 60 then
831             Leap   := True;
832             Second := 59;
833          else
834             Leap   := False;
835             Second := tm_sec;
836          end if;
837
838          --  Step 3: Calculate the time value
839
840          Result :=
841            Time_Rep
842              (Formatting_Operations.Time_Of
843                (Year         => Year,
844                 Month        => Month,
845                 Day          => Day,
846                 Day_Secs     => 0.0,      --  Time is given in h:m:s
847                 Hour         => tm_hour,
848                 Minute       => tm_min,
849                 Second       => Second,
850                 Sub_Sec      => 0.0,      --  No precise sub second given
851                 Leap_Sec     => Leap,
852                 Use_Day_Secs => False,    --  Time is given in h:m:s
853                 Is_Ada_05    => True,     --  Force usage of explicit time zone
854                 Time_Zone    => 0));      --  Place the value in UTC
855
856          --  Step 4: Daylight Savings Time
857
858          if tm_isdst = 1 then
859             Result := Result + Time_Rep (3_600) * Nano;
860          end if;
861
862          return Time (Result);
863
864       exception
865          when Constraint_Error =>
866             raise Time_Error;
867       end To_Ada_Time;
868
869       -----------------
870       -- To_Duration --
871       -----------------
872
873       function To_Duration
874         (tv_sec  : Long_Integer;
875          tv_nsec : Long_Integer) return Duration
876       is
877          pragma Unsuppress (Overflow_Check);
878       begin
879          return Duration (tv_sec) + Duration (tv_nsec) / Nano_F;
880       end To_Duration;
881
882       ------------------------
883       -- To_Struct_Timespec --
884       ------------------------
885
886       procedure To_Struct_Timespec
887         (D       : Duration;
888          tv_sec  : out Long_Integer;
889          tv_nsec : out Long_Integer)
890       is
891          pragma Unsuppress (Overflow_Check);
892          Secs      : Duration;
893          Nano_Secs : Duration;
894
895       begin
896          --  Seconds extraction, avoid potential rounding errors
897
898          Secs   := D - 0.5;
899          tv_sec := Long_Integer (Secs);
900
901          --  Nanoseconds extraction
902
903          Nano_Secs := D - Duration (tv_sec);
904          tv_nsec := Long_Integer (Nano_Secs * Nano);
905       end To_Struct_Timespec;
906
907       ------------------
908       -- To_Struct_Tm --
909       ------------------
910
911       procedure To_Struct_Tm
912         (T       : Time;
913          tm_year : out Integer;
914          tm_mon  : out Integer;
915          tm_day  : out Integer;
916          tm_hour : out Integer;
917          tm_min  : out Integer;
918          tm_sec  : out Integer)
919       is
920          pragma Unsuppress (Overflow_Check);
921          Year      : Year_Number;
922          Month     : Month_Number;
923          Second    : Integer;
924          Day_Secs  : Day_Duration;
925          Sub_Sec   : Duration;
926          Leap_Sec  : Boolean;
927
928       begin
929          --  Step 1: Split the input time
930
931          Formatting_Operations.Split
932            (T, Year, Month, tm_day, Day_Secs,
933             tm_hour, tm_min, Second, Sub_Sec, Leap_Sec, True, 0);
934
935          --  Step 2: Correct the year and month
936
937          tm_year := Year - 1900;
938          tm_mon  := Month - 1;
939
940          --  Step 3: Handle leap second occurrences
941
942          if Leap_Sec then
943             tm_sec := 60;
944          else
945             tm_sec := Second;
946          end if;
947       end To_Struct_Tm;
948
949       ------------------
950       -- To_Unix_Time --
951       ------------------
952
953       function To_Unix_Time (Ada_Time : Time) return Long_Integer is
954          pragma Unsuppress (Overflow_Check);
955          Ada_Rep : constant Time_Rep := Time_Rep (Ada_Time);
956       begin
957          return Long_Integer ((Ada_Rep + Epoch_Offset) / Nano);
958       exception
959          when Constraint_Error =>
960             raise Time_Error;
961       end To_Unix_Time;
962    end Conversion_Operations;
963
964    ----------------------
965    -- Delay_Operations --
966    ----------------------
967
968    package body Delay_Operations is
969
970       -----------------
971       -- To_Duration --
972       -----------------
973
974       function To_Duration (Date : Time) return Duration is
975          Elapsed_Leaps : Natural;
976          Next_Leap_N   : Time_Rep;
977          Res_N         : Time_Rep;
978
979       begin
980          Res_N := Time_Rep (Date);
981
982          --  If the target supports leap seconds, remove any leap seconds
983          --  elapsed up to the input date.
984
985          if Leap_Support then
986             Cumulative_Leap_Seconds
987               (Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
988
989             --  The input time value may fall on a leap second occurrence
990
991             if Res_N >= Next_Leap_N then
992                Elapsed_Leaps := Elapsed_Leaps + 1;
993             end if;
994
995          --  The target does not support leap seconds
996
997          else
998             Elapsed_Leaps := 0;
999          end if;
1000
1001          Res_N := Res_N - Time_Rep (Elapsed_Leaps) * Nano;
1002
1003          --  Perform a shift in origins, note that enforcing type Time on
1004          --  both operands will invoke Ada.Calendar."-".
1005
1006          return Time (Res_N) - Time (Unix_Min);
1007       end To_Duration;
1008
1009    end Delay_Operations;
1010
1011    ---------------------------
1012    -- Formatting_Operations --
1013    ---------------------------
1014
1015    package body Formatting_Operations is
1016
1017       -----------------
1018       -- Day_Of_Week --
1019       -----------------
1020
1021       function Day_Of_Week (Date : Time) return Integer is
1022          Y  : Year_Number;
1023          Mo : Month_Number;
1024          D  : Day_Number;
1025          Ds : Day_Duration;
1026          H  : Integer;
1027          Mi : Integer;
1028          Se : Integer;
1029          Su : Duration;
1030          Le : Boolean;
1031
1032          pragma Unreferenced (Ds, H, Mi, Se, Su, Le);
1033
1034          Day_Count : Long_Integer;
1035          Res_Dur   : Time_Dur;
1036          Res_N     : Time_Rep;
1037
1038       begin
1039          Formatting_Operations.Split
1040            (Date      => Date,
1041             Year      => Y,
1042             Month     => Mo,
1043             Day       => D,
1044             Day_Secs  => Ds,
1045             Hour      => H,
1046             Minute    => Mi,
1047             Second    => Se,
1048             Sub_Sec   => Su,
1049             Leap_Sec  => Le,
1050             Is_Ada_05 => True,
1051             Time_Zone => 0);
1052
1053          --  Build a time value in the middle of the same day
1054
1055          Res_N :=
1056            Time_Rep
1057              (Formatting_Operations.Time_Of
1058                (Year         => Y,
1059                 Month        => Mo,
1060                 Day          => D,
1061                 Day_Secs     => 0.0,
1062                 Hour         => 12,
1063                 Minute       => 0,
1064                 Second       => 0,
1065                 Sub_Sec      => 0.0,
1066                 Leap_Sec     => False,
1067                 Use_Day_Secs => False,
1068                 Is_Ada_05    => True,
1069                 Time_Zone    => 0));
1070
1071          --  Determine the elapsed seconds since the start of Ada time
1072
1073          Res_Dur := Time_Dur (Res_N / Nano - Ada_Low / Nano);
1074
1075          --  Count the number of days since the start of Ada time. 1901-1-1
1076          --  GMT was a Tuesday.
1077
1078          Day_Count := Long_Integer (Res_Dur / Secs_In_Day) + 1;
1079
1080          return Integer (Day_Count mod 7);
1081       end Day_Of_Week;
1082
1083       -----------
1084       -- Split --
1085       -----------
1086
1087       procedure Split
1088         (Date      : Time;
1089          Year      : out Year_Number;
1090          Month     : out Month_Number;
1091          Day       : out Day_Number;
1092          Day_Secs  : out Day_Duration;
1093          Hour      : out Integer;
1094          Minute    : out Integer;
1095          Second    : out Integer;
1096          Sub_Sec   : out Duration;
1097          Leap_Sec  : out Boolean;
1098          Is_Ada_05 : Boolean;
1099          Time_Zone : Long_Integer)
1100       is
1101          --  The following constants represent the number of nanoseconds
1102          --  elapsed since the start of Ada time to and including the non
1103          --  leap centennial years.
1104
1105          Year_2101 : constant Time_Rep := Ada_Low +
1106                        Time_Rep (49 * 366 + 151 * 365) * Nanos_In_Day;
1107          Year_2201 : constant Time_Rep := Ada_Low +
1108                        Time_Rep (73 * 366 + 227 * 365) * Nanos_In_Day;
1109          Year_2301 : constant Time_Rep := Ada_Low +
1110                        Time_Rep (97 * 366 + 303 * 365) * Nanos_In_Day;
1111
1112          Date_Dur       : Time_Dur;
1113          Date_N         : Time_Rep;
1114          Day_Seconds    : Natural;
1115          Elapsed_Leaps  : Natural;
1116          Four_Year_Segs : Natural;
1117          Hour_Seconds   : Natural;
1118          Is_Leap_Year   : Boolean;
1119          Next_Leap_N    : Time_Rep;
1120          Rem_Years      : Natural;
1121          Sub_Sec_N      : Time_Rep;
1122          Year_Day       : Natural;
1123
1124       begin
1125          Date_N := Time_Rep (Date);
1126
1127          --  Step 1: Leap seconds processing in UTC
1128
1129          if Leap_Support then
1130             Cumulative_Leap_Seconds
1131               (Start_Of_Time, Date_N, Elapsed_Leaps, Next_Leap_N);
1132
1133             Leap_Sec := Date_N >= Next_Leap_N;
1134
1135             if Leap_Sec then
1136                Elapsed_Leaps := Elapsed_Leaps + 1;
1137             end if;
1138
1139          --  The target does not support leap seconds
1140
1141          else
1142             Elapsed_Leaps := 0;
1143             Leap_Sec      := False;
1144          end if;
1145
1146          Date_N := Date_N - Time_Rep (Elapsed_Leaps) * Nano;
1147
1148          --  Step 2: Time zone processing. This action converts the input date
1149          --  from GMT to the requested time zone.
1150
1151          if Is_Ada_05 then
1152             if Time_Zone /= 0 then
1153                Date_N := Date_N + Time_Rep (Time_Zone) * 60 * Nano;
1154             end if;
1155
1156          --  Ada 83 and 95
1157
1158          else
1159             declare
1160                Off : constant Long_Integer :=
1161                        Time_Zones_Operations.UTC_Time_Offset (Time (Date_N));
1162             begin
1163                Date_N := Date_N + Time_Rep (Off) * Nano;
1164             end;
1165          end if;
1166
1167          --  Step 3: Non-leap centennial year adjustment in local time zone
1168
1169          --  In order for all divisions to work properly and to avoid more
1170          --  complicated arithmetic, we add fake February 29s to dates which
1171          --  occur after a non-leap centennial year.
1172
1173          if Date_N >= Year_2301 then
1174             Date_N := Date_N + Time_Rep (3) * Nanos_In_Day;
1175
1176          elsif Date_N >= Year_2201 then
1177             Date_N := Date_N + Time_Rep (2) * Nanos_In_Day;
1178
1179          elsif Date_N >= Year_2101 then
1180             Date_N := Date_N + Time_Rep (1) * Nanos_In_Day;
1181          end if;
1182
1183          --  Step 4: Sub second processing in local time zone
1184
1185          Sub_Sec_N := Date_N mod Nano;
1186          Sub_Sec   := Duration (Sub_Sec_N) / Nano_F;
1187          Date_N    := Date_N - Sub_Sec_N;
1188
1189          --  Convert Date_N into a time duration value, changing the units
1190          --  to seconds.
1191
1192          Date_Dur := Time_Dur (Date_N / Nano - Ada_Low / Nano);
1193
1194          --  Step 5: Year processing in local time zone. Determine the number
1195          --  of four year segments since the start of Ada time and the input
1196          --  date.
1197
1198          Four_Year_Segs := Natural (Date_Dur / Secs_In_Four_Years);
1199
1200          if Four_Year_Segs > 0 then
1201             Date_Dur := Date_Dur - Time_Dur (Four_Year_Segs) *
1202                                    Secs_In_Four_Years;
1203          end if;
1204
1205          --  Calculate the remaining non-leap years
1206
1207          Rem_Years := Natural (Date_Dur / Secs_In_Non_Leap_Year);
1208
1209          if Rem_Years > 3 then
1210             Rem_Years := 3;
1211          end if;
1212
1213          Date_Dur := Date_Dur - Time_Dur (Rem_Years) * Secs_In_Non_Leap_Year;
1214
1215          Year := Ada_Min_Year + Natural (4 * Four_Year_Segs + Rem_Years);
1216          Is_Leap_Year := Is_Leap (Year);
1217
1218          --  Step 6: Month and day processing in local time zone
1219
1220          Year_Day := Natural (Date_Dur / Secs_In_Day) + 1;
1221
1222          Month := 1;
1223
1224          --  Processing for months after January
1225
1226          if Year_Day > 31 then
1227             Month    := 2;
1228             Year_Day := Year_Day - 31;
1229
1230             --  Processing for a new month or a leap February
1231
1232             if Year_Day > 28
1233               and then (not Is_Leap_Year or else Year_Day > 29)
1234             then
1235                Month    := 3;
1236                Year_Day := Year_Day - 28;
1237
1238                if Is_Leap_Year then
1239                   Year_Day := Year_Day - 1;
1240                end if;
1241
1242                --  Remaining months
1243
1244                while Year_Day > Days_In_Month (Month) loop
1245                   Year_Day := Year_Day - Days_In_Month (Month);
1246                   Month    := Month + 1;
1247                end loop;
1248             end if;
1249          end if;
1250
1251          --  Step 7: Hour, minute, second and sub second processing in local
1252          --  time zone.
1253
1254          Day          := Day_Number (Year_Day);
1255          Day_Seconds  := Integer (Date_Dur mod Secs_In_Day);
1256          Day_Secs     := Duration (Day_Seconds) + Sub_Sec;
1257          Hour         := Day_Seconds / 3_600;
1258          Hour_Seconds := Day_Seconds mod 3_600;
1259          Minute       := Hour_Seconds / 60;
1260          Second       := Hour_Seconds mod 60;
1261       end Split;
1262
1263       -------------
1264       -- Time_Of --
1265       -------------
1266
1267       function Time_Of
1268         (Year         : Year_Number;
1269          Month        : Month_Number;
1270          Day          : Day_Number;
1271          Day_Secs     : Day_Duration;
1272          Hour         : Integer;
1273          Minute       : Integer;
1274          Second       : Integer;
1275          Sub_Sec      : Duration;
1276          Leap_Sec     : Boolean := False;
1277          Use_Day_Secs : Boolean := False;
1278          Is_Ada_05    : Boolean := False;
1279          Time_Zone    : Long_Integer := 0) return Time
1280       is
1281          Count         : Integer;
1282          Elapsed_Leaps : Natural;
1283          Next_Leap_N   : Time_Rep;
1284          Res_N         : Time_Rep;
1285          Rounded_Res_N : Time_Rep;
1286
1287       begin
1288          --  Step 1: Check whether the day, month and year form a valid date
1289
1290          if Day > Days_In_Month (Month)
1291            and then (Day /= 29 or else Month /= 2 or else not Is_Leap (Year))
1292          then
1293             raise Time_Error;
1294          end if;
1295
1296          --  Start accumulating nanoseconds from the low bound of Ada time
1297
1298          Res_N := Ada_Low;
1299
1300          --  Step 2: Year processing and centennial year adjustment. Determine
1301          --  the number of four year segments since the start of Ada time and
1302          --  the input date.
1303
1304          Count := (Year - Year_Number'First) / 4;
1305          Res_N := Res_N + Time_Rep (Count) * Secs_In_Four_Years * Nano;
1306
1307          --  Note that non-leap centennial years are automatically considered
1308          --  leap in the operation above. An adjustment of several days is
1309          --  required to compensate for this.
1310
1311          if Year > 2300 then
1312             Res_N := Res_N - Time_Rep (3) * Nanos_In_Day;
1313
1314          elsif Year > 2200 then
1315             Res_N := Res_N - Time_Rep (2) * Nanos_In_Day;
1316
1317          elsif Year > 2100 then
1318             Res_N := Res_N - Time_Rep (1) * Nanos_In_Day;
1319          end if;
1320
1321          --  Add the remaining non-leap years
1322
1323          Count := (Year - Year_Number'First) mod 4;
1324          Res_N := Res_N + Time_Rep (Count) * Secs_In_Non_Leap_Year * Nano;
1325
1326          --  Step 3: Day of month processing. Determine the number of days
1327          --  since the start of the current year. Do not add the current
1328          --  day since it has not elapsed yet.
1329
1330          Count := Cumulative_Days_Before_Month (Month) + Day - 1;
1331
1332          --  The input year is leap and we have passed February
1333
1334          if Is_Leap (Year)
1335            and then Month > 2
1336          then
1337             Count := Count + 1;
1338          end if;
1339
1340          Res_N := Res_N + Time_Rep (Count) * Nanos_In_Day;
1341
1342          --  Step 4: Hour, minute, second and sub second processing
1343
1344          if Use_Day_Secs then
1345             Res_N := Res_N + Duration_To_Time_Rep (Day_Secs);
1346
1347          else
1348             Res_N := Res_N +
1349               Time_Rep (Hour * 3_600 + Minute * 60 + Second) * Nano;
1350
1351             if Sub_Sec = 1.0 then
1352                Res_N := Res_N + Time_Rep (1) * Nano;
1353             else
1354                Res_N := Res_N + Duration_To_Time_Rep (Sub_Sec);
1355             end if;
1356          end if;
1357
1358          --  At this point, the generated time value should be withing the
1359          --  bounds of Ada time.
1360
1361          Check_Within_Time_Bounds (Res_N);
1362
1363          --  Step 4: Time zone processing. At this point we have built an
1364          --  arbitrary time value which is not related to any time zone.
1365          --  For simplicity, the time value is normalized to GMT, producing
1366          --  a uniform representation which can be treated by arithmetic
1367          --  operations for instance without any additional corrections.
1368
1369          if Is_Ada_05 then
1370             if Time_Zone /= 0 then
1371                Res_N := Res_N - Time_Rep (Time_Zone) * 60 * Nano;
1372             end if;
1373
1374          --  Ada 83 and 95
1375
1376          else
1377             declare
1378                Current_Off   : constant Long_Integer :=
1379                                  Time_Zones_Operations.UTC_Time_Offset
1380                                    (Time (Res_N));
1381                Current_Res_N : constant Time_Rep :=
1382                                  Res_N - Time_Rep (Current_Off) * Nano;
1383                Off           : constant Long_Integer :=
1384                                  Time_Zones_Operations.UTC_Time_Offset
1385                                    (Time (Current_Res_N));
1386             begin
1387                Res_N := Res_N - Time_Rep (Off) * Nano;
1388             end;
1389          end if;
1390
1391          --  Step 5: Leap seconds processing in GMT
1392
1393          if Leap_Support then
1394             Cumulative_Leap_Seconds
1395               (Start_Of_Time, Res_N, Elapsed_Leaps, Next_Leap_N);
1396
1397             Res_N := Res_N + Time_Rep (Elapsed_Leaps) * Nano;
1398
1399             --  An Ada 2005 caller requesting an explicit leap second or an
1400             --  Ada 95 caller accounting for an invisible leap second.
1401
1402             if Leap_Sec
1403               or else Res_N >= Next_Leap_N
1404             then
1405                Res_N := Res_N + Time_Rep (1) * Nano;
1406             end if;
1407
1408             --  Leap second validity check
1409
1410             Rounded_Res_N := Res_N - (Res_N mod Nano);
1411
1412             if Is_Ada_05
1413               and then Leap_Sec
1414               and then Rounded_Res_N /= Next_Leap_N
1415             then
1416                raise Time_Error;
1417             end if;
1418          end if;
1419
1420          return Time (Res_N);
1421       end Time_Of;
1422
1423    end Formatting_Operations;
1424
1425    ---------------------------
1426    -- Time_Zones_Operations --
1427    ---------------------------
1428
1429    package body Time_Zones_Operations is
1430
1431       --  The Unix time bounds in nanoseconds: 1970/1/1 .. 2037/1/1
1432
1433       Unix_Min : constant Time_Rep := Ada_Low +
1434                    Time_Rep (17 * 366 +  52 * 365) * Nanos_In_Day;
1435
1436       Unix_Max : constant Time_Rep := Ada_Low +
1437                    Time_Rep (34 * 366 + 102 * 365) * Nanos_In_Day +
1438                    Time_Rep (Leap_Seconds_Count) * Nano;
1439
1440       --  The following constants denote February 28 during non-leap
1441       --  centennial years, the units are nanoseconds.
1442
1443       T_2100_2_28 : constant Time_Rep := Ada_Low +
1444                       (Time_Rep (49 * 366 + 150 * 365 + 59) * Secs_In_Day +
1445                        Time_Rep (Leap_Seconds_Count)) * Nano;
1446
1447       T_2200_2_28 : constant Time_Rep := Ada_Low +
1448                       (Time_Rep (73 * 366 + 226 * 365 + 59) * Secs_In_Day +
1449                        Time_Rep (Leap_Seconds_Count)) * Nano;
1450
1451       T_2300_2_28 : constant Time_Rep := Ada_Low +
1452                       (Time_Rep (97 * 366 + 302 * 365 + 59) * Secs_In_Day +
1453                        Time_Rep (Leap_Seconds_Count)) * Nano;
1454
1455       --  56 years (14 leap years + 42 non leap years) in nanoseconds:
1456
1457       Nanos_In_56_Years : constant := (14 * 366 + 42 * 365) * Nanos_In_Day;
1458
1459       --  Base C types. There is no point dragging in Interfaces.C just for
1460       --  these four types.
1461
1462       type char_Pointer is access Character;
1463       subtype int is Integer;
1464       subtype long is Long_Integer;
1465       type long_Pointer is access all long;
1466
1467       --  The Ada equivalent of struct tm and type time_t
1468
1469       type tm is record
1470          tm_sec    : int;           --  seconds after the minute (0 .. 60)
1471          tm_min    : int;           --  minutes after the hour (0 .. 59)
1472          tm_hour   : int;           --  hours since midnight (0 .. 24)
1473          tm_mday   : int;           --  day of the month (1 .. 31)
1474          tm_mon    : int;           --  months since January (0 .. 11)
1475          tm_year   : int;           --  years since 1900
1476          tm_wday   : int;           --  days since Sunday (0 .. 6)
1477          tm_yday   : int;           --  days since January 1 (0 .. 365)
1478          tm_isdst  : int;           --  Daylight Savings Time flag (-1 .. 1)
1479          tm_gmtoff : long;          --  offset from UTC in seconds
1480          tm_zone   : char_Pointer;  --  timezone abbreviation
1481       end record;
1482
1483       type tm_Pointer is access all tm;
1484
1485       subtype time_t is long;
1486       type time_t_Pointer is access all time_t;
1487
1488       procedure localtime_tzoff
1489        (C   : time_t_Pointer;
1490         res : tm_Pointer;
1491         off : long_Pointer);
1492       pragma Import (C, localtime_tzoff, "__gnat_localtime_tzoff");
1493       --  This is a lightweight wrapper around the system library function
1494       --  localtime_r. Parameter 'off' captures the UTC offset which is either
1495       --  retrieved from the tm struct or calculated from the 'timezone' extern
1496       --  and the tm_isdst flag in the tm struct.
1497
1498       ---------------------
1499       -- UTC_Time_Offset --
1500       ---------------------
1501
1502       function UTC_Time_Offset (Date : Time) return Long_Integer is
1503          Adj_Cent : Integer := 0;
1504          Date_N   : Time_Rep;
1505          Offset   : aliased long;
1506          Secs_T   : aliased time_t;
1507          Secs_TM  : aliased tm;
1508
1509       begin
1510          Date_N := Time_Rep (Date);
1511
1512          --  Dates which are 56 years apart fall on the same day, day light
1513          --  saving and so on. Non-leap centennial years violate this rule by
1514          --  one day and as a consequence, special adjustment is needed.
1515
1516          if Date_N > T_2100_2_28 then
1517             if Date_N > T_2200_2_28 then
1518                if Date_N > T_2300_2_28 then
1519                   Adj_Cent := 3;
1520                else
1521                   Adj_Cent := 2;
1522                end if;
1523
1524             else
1525                Adj_Cent := 1;
1526             end if;
1527          end if;
1528
1529          if Adj_Cent > 0 then
1530             Date_N := Date_N - Time_Rep (Adj_Cent) * Nanos_In_Day;
1531          end if;
1532
1533          --  Shift the date within bounds of Unix time
1534
1535          while Date_N < Unix_Min loop
1536             Date_N := Date_N + Nanos_In_56_Years;
1537          end loop;
1538
1539          while Date_N >= Unix_Max loop
1540             Date_N := Date_N - Nanos_In_56_Years;
1541          end loop;
1542
1543          --  Perform a shift in origins from Ada to Unix
1544
1545          Date_N := Date_N - Unix_Min;
1546
1547          --  Convert the date into seconds
1548
1549          Secs_T := time_t (Date_N / Nano);
1550
1551          localtime_tzoff
1552            (Secs_T'Unchecked_Access,
1553             Secs_TM'Unchecked_Access,
1554             Offset'Unchecked_Access);
1555
1556          return Offset;
1557       end UTC_Time_Offset;
1558
1559    end Time_Zones_Operations;
1560
1561 --  Start of elaboration code for Ada.Calendar
1562
1563 begin
1564    System.OS_Primitives.Initialize;
1565 end Ada.Calendar;