OSDN Git Service

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