]> Cypherpunks.ru repositories - gotai64n.git/blob - leapsecs.go
Unify copyright comment format
[gotai64n.git] / leapsecs.go
1 /*
2 go.cypherpunks.ru/tai64n -- Pure Go TAI64/TAI64N implementation
3 Copyright (C) 2020-2023 Sergey Matveev <stargrave@stargrave.org>
4
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, version 3 of the License.
8
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 GNU General Public License for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program.  If not, see <http://www.gnu.org/licenses/>.
16 */
17
18 package tai64n
19
20 import (
21         "sort"
22         "time"
23 )
24
25 const Leapsecs1972 = 10
26
27 // Database of Unix timestamps of the time when leap second occurred.
28 // Library contains and initializes it with leap seconds up to 2016-12-31.
29 var LeapsecsDB []int64
30
31 // TAI<->UTC difference for the given Unix timestamp.
32 func LeapsecsDiff(t int64) int {
33         for i, leap := range LeapsecsDB {
34                 if t > leap {
35                         return len(LeapsecsDB) - i
36                 }
37         }
38         return 0
39 }
40
41 // Add currently known (LeapsecsDB) leap seconds, not including initial
42 // 1972-01-01 10-seconds offset.
43 func LeapsecsAdd(t time.Time) time.Time {
44         return t.Add(time.Second * time.Duration(LeapsecsDiff(t.Unix())))
45 }
46
47 // Opposite of LeapsecsAdd().
48 func LeapsecsSub(t time.Time) time.Time {
49         return t.Add(-time.Second * time.Duration(LeapsecsDiff(t.Unix())))
50 }
51
52 type Int64s []int64
53
54 func (a Int64s) Len() int           { return len(a) }
55 func (a Int64s) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
56 func (a Int64s) Less(i, j int) bool { return a[i] > a[j] }
57
58 // Load "leapsecs.dat"-like database: concatenated TAI64 leap seconds.
59 // Function panics if encoding is invalid.
60 func LeapsecsDBLoad(buf []byte) {
61         db := make([]int64, 0, len(buf)/TAI64Size)
62         for i := 0; i < len(buf); i += TAI64Size {
63                 db = append(db, (ToTime(buf[i:i+TAI64Size]).Unix()/86400)*86400)
64         }
65         sort.Sort(Int64s(db))
66         LeapsecsDB = db
67 }