OSDN Git Service

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