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