/
local-time.lisp
1886 lines (1715 loc) · 85.3 KB
/
local-time.lisp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(in-package #:local-time)
;;; Types
(defclass timestamp ()
((day :accessor day-of :initarg :day :initform 0 :type integer)
(sec :accessor sec-of :initarg :sec :initform 0 :type integer)
(nsec :accessor nsec-of :initarg :nsec :initform 0 :type (integer 0 999999999))))
(defstruct subzone
(abbrev nil)
(offset nil)
(daylight-p nil))
(defstruct timezone
(transitions #(0) :type simple-vector)
(indexes #(0) :type simple-vector)
(subzones #() :type simple-vector)
(leap-seconds nil :type list)
(path nil)
(name "anonymous" :type string)
(loaded nil :type boolean))
(deftype timezone-offset ()
'(integer -43200 50400))
(defun %valid-time-of-day? (timestamp)
(zerop (day-of timestamp)))
(deftype time-of-day ()
'(and timestamp
(satisfies %valid-time-of-day?)))
(defun %valid-date? (timestamp)
(and (zerop (sec-of timestamp))
(zerop (nsec-of timestamp))))
(deftype date ()
'(and timestamp
(satisfies %valid-date?)))
(define-condition invalid-timezone-file (error)
((path :accessor path-of :initarg :path))
(:report (lambda (condition stream)
(format stream "The file at ~a is not a timezone file."
(path-of condition)))))
(define-condition invalid-time-specification (error)
()
(:report "The time specification is invalid"))
(define-condition invalid-timestring (error)
((timestring :accessor timestring-of :initarg :timestring)
(failure :accessor failure-of :initarg :failure))
(:report (lambda (condition stream)
(format stream "Failed to parse ~S as an rfc3339 time: ~S"
(timestring-of condition)
(failure-of condition)))))
(defmethod make-load-form ((self timestamp) &optional environment)
(make-load-form-saving-slots self :environment environment))
;;; Declaims
(declaim (inline now format-timestring %get-current-time
format-rfc3339-timestring to-rfc3339-timestring
format-rfc1123-timestring to-rfc1123-timestring)
(ftype (function (&rest t) string) format-rfc3339-timestring)
(ftype (function (&rest t) string) format-timestring)
(ftype (function (&rest t) fixnum) local-timezone)
(ftype (function (&rest t) (values
timezone-offset
boolean
string)) timestamp-subzone)
(ftype (function (timestamp &key (:timezone timezone) (:offset (or null integer)))
(values (integer 0 999999999)
(integer 0 59)
(integer 0 59)
(integer 0 23)
(integer 1 31)
(integer 1 12)
(integer -1000000 1000000)
(integer 0 6)
t
timezone-offset
simple-string))
decode-timestamp))
;;; Variables
(defvar *default-timezone*)
(defparameter *default-timezone-repository-path*
(flet ((try (project-home-directory)
(when project-home-directory
(ignore-errors
(truename
(merge-pathnames "zoneinfo/"
(make-pathname :directory (pathname-directory project-home-directory))))))))
(or (when (find-package "ASDF")
(let ((path (eval (read-from-string
"(let ((system (asdf:find-system :local-time nil)))
(when system
(asdf:component-pathname system)))"))))
(try path)))
(let ((path (or #.*compile-file-truename*
*load-truename*)))
(when path
(try (merge-pathnames "../" path)))))))
;;; Month information
(defparameter +month-names+
#("" "January" "February" "March" "April" "May" "June" "July" "August"
"September" "October" "November" "December"))
(defparameter +short-month-names+
#("" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov"
"Dec"))
(defparameter +day-names+
#("Sunday" "Monday" "Tuesday" "Wednesday" "Thursday" "Friday" "Saturday"))
(defparameter +day-names-as-keywords+
#(:sunday :monday :tuesday :wednesday :thursday :friday :saturday))
(defparameter +short-day-names+
#("Sun" "Mon" "Tue" "Wed" "Thu" "Fri" "Sat"))
(defparameter +minimal-day-names+
#("Su" "Mo" "Tu" "We" "Th" "Fr" "Sa"))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defconstant +months-per-year+ 12)
(defconstant +days-per-week+ 7)
(defconstant +hours-per-day+ 24)
(defconstant +minutes-per-day+ 1440)
(defconstant +minutes-per-hour+ 60)
(defconstant +seconds-per-day+ 86400)
(defconstant +seconds-per-hour+ 3600)
(defconstant +seconds-per-minute+ 60)
(defconstant +usecs-per-day+ 86400000000))
(defparameter +iso-8601-date-format+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +iso-8601-time-format+
'((:hour 2) #\: (:min 2) #\: (:sec 2) #\. (:usec 6)))
(defparameter +iso-8601-format+
;; 2008-11-18T02:32:00.586931+01:00
(append +iso-8601-date-format+ (list #\T) +iso-8601-time-format+ (list :gmt-offset-or-z)))
(defparameter +rfc3339-format+ +iso-8601-format+)
(defparameter +rfc3339-format/date-only+
'((:year 4) #\- (:month 2) #\- (:day 2)))
(defparameter +asctime-format+
'(:short-weekday #\space :short-month #\space (:day 2 #\space) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space
(:year 4)))
(defparameter +rfc-1123-format+
;; Sun, 06 Nov 1994 08:49:37 GMT
'(:short-weekday ", " (:day 2) #\space :short-month #\space (:year 4) #\space
(:hour 2) #\: (:min 2) #\: (:sec 2) #\space :gmt-offset-hhmm)
"See the RFC 1123 for the details about the possible values of the timezone field.")
(defparameter +iso-week-date-format+
;; 2009-W53-5
'((:iso-week-year 4) #\- #\W (:iso-week-number 2) #\- (:iso-week-day 1)))
(eval-when (:compile-toplevel :load-toplevel :execute)
(defparameter +rotated-month-days-without-leap-day+
#.(coerce #(31 30 31 30 31 31 30 31 30 31 31 28)
'(simple-array fixnum (*))))
(defparameter +rotated-month-offsets-without-leap-day+
(coerce
(cons 0
(loop with sum = 0
for days :across +rotated-month-days-without-leap-day+
collect (incf sum days)))
'(simple-array fixnum (*)))))
;; The astronomical julian date offset is the number of days between
;; the current date and -4713-01-01T00:00:00+00:00
(defparameter +astronomical-julian-date-offset+ -2451605)
;; The modified julian date is the number of days between the current
;; date and 1858-11-17T12:00:00+00:00. TODO: For the sake of simplicity,
;; we currently just do the date arithmetic and don't adjust for the
;; time of day.
(defparameter +modified-julian-date-offset+ -51604)
(defun %guess-offset (seconds days &optional timezone)
;; try converting the local time to a timestamp using each available
;; subtimezone, until we find one where the offset matches the offset that
;; applies at that time (according to the transition table).
;;
;; Consequence for ambiguous cases:
;; Whichever subtimezone is listed first in the tzinfo database will be
;; the one that we pick to resolve ambiguous local time representations.
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-values-to-unix seconds days))
(subzone-idx (if (zerop (length (timezone-indexes zone)))
0
(elt (timezone-indexes zone)
(transition-position unix-time
(timezone-transitions zone)))))
(subzone (elt (timezone-subzones zone) subzone-idx)))
(subzone-offset subzone)))
(defun %read-binary-integer (stream byte-count &optional (signed nil))
"Read BYTE-COUNT bytes from the binary stream STREAM, and return an integer which is its representation in network byte order (MSB). If SIGNED is true, interprets the most significant bit as a sign indicator."
(loop
:with result = 0
:for offset :from (* (1- byte-count) 8) :downto 0 :by 8
:do (setf (ldb (byte 8 offset) result) (read-byte stream))
:finally (if signed
(let ((high-bit (* byte-count 8)))
(if (logbitp (1- high-bit) result)
(return (- result (ash 1 high-bit)))
(return result)))
(return result))))
(defun %string-from-unsigned-byte-vector (vector offset)
"Returns a string created from the vector of unsigned bytes VECTOR starting at OFFSET which is terminated by a 0."
(declare (type (vector (unsigned-byte 8)) vector))
(let* ((null-pos (or (position 0 vector :start offset) (length vector)))
(result (make-string (- null-pos offset))))
(loop for input-index :from offset :upto (1- null-pos)
for output-index :upfrom 0
do (setf (aref result output-index) (code-char (aref vector input-index))))
result))
(defun %find-first-std-offset (timezone-indexes timestamp-info)
(let ((subzone-idx (find-if 'subzone-daylight-p
timezone-indexes
:key (lambda (x) (aref timestamp-info x)))))
(subzone-offset (aref timestamp-info (or subzone-idx 0)))))
(defun %tz-verify-magic-number (inf zone)
;; read and verify magic number
(let ((magic-buf (make-array 4 :element-type 'unsigned-byte)))
(read-sequence magic-buf inf :start 0 :end 4)
(when (string/= (map 'string #'code-char magic-buf) "TZif" :end1 4)
(error 'invalid-timezone-file :path (timezone-path zone))))
;; skip 16 bytes for "future use"
(let ((ignore-buf (make-array 16 :element-type 'unsigned-byte)))
(read-sequence ignore-buf inf :start 0 :end 16)))
(defun %tz-read-header (inf)
`(:utc-count ,(%read-binary-integer inf 4)
:wall-count ,(%read-binary-integer inf 4)
:leap-count ,(%read-binary-integer inf 4)
:transition-count ,(%read-binary-integer inf 4)
:type-count ,(%read-binary-integer inf 4)
:abbrev-length ,(%read-binary-integer inf 4)))
(defun %tz-read-transitions (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4 t))))
(defun %tz-read-indexes (inf count)
(make-array count
:initial-contents
(loop for idx from 1 upto count
collect (%read-binary-integer inf 1))))
(defun %tz-read-subzone (inf count)
(loop for idx from 1 upto count
collect (list (%read-binary-integer inf 4 t)
(%read-binary-integer inf 1)
(%read-binary-integer inf 1))))
(defun leap-seconds-sec (leap-seconds)
(car leap-seconds))
(defun leap-seconds-adjustment (leap-seconds)
(cdr leap-seconds))
(defun %tz-read-leap-seconds (inf count)
(when (plusp count)
(loop for idx from 1 upto count
collect (%read-binary-integer inf 4) into sec
collect (%read-binary-integer inf 4) into adjustment
finally (return (cons (make-array count :initial-contents sec)
(make-array count :initial-contents adjustment))))))
(defun %tz-read-abbrevs (inf length)
(let ((a (make-array length :element-type '(unsigned-byte 8))))
(read-sequence a inf
:start 0
:end length)
a))
(defun %tz-read-indicators (inf length)
;; read standard/wall indicators
(let ((buf (make-array length :element-type '(unsigned-byte 8))))
(read-sequence buf inf
:start 0
:end length)
(make-array length
:element-type 'bit
:initial-contents buf)))
(defun %tz-make-subzones (raw-info abbrevs gmt-indicators std-indicators)
(declare (ignore gmt-indicators std-indicators))
;; TODO: handle TZ environment variables, which use the gmt and std
;; indicators
(make-array (length raw-info)
:element-type 'subzone
:initial-contents
(loop for info in raw-info collect
(make-subzone
:offset (first info)
:daylight-p (/= (second info) 0)
:abbrev (%string-from-unsigned-byte-vector abbrevs (third info))))))
(defun %realize-timezone (zone &optional reload)
"If timezone has not already been loaded or RELOAD is non-NIL, loads the timezone information from its associated unix file. If the file is not a valid timezone file, the condition INVALID-TIMEZONE-FILE will be signaled."
(when (or reload (not (timezone-loaded zone)))
(with-open-file (inf (timezone-path zone)
:direction :input
:element-type 'unsigned-byte)
(%tz-verify-magic-number inf zone)
;; read header values
(let* ((header (%tz-read-header inf))
(timezone-transitions (%tz-read-transitions inf (getf header :transition-count)))
(subzone-indexes (%tz-read-indexes inf (getf header :transition-count)))
(subzone-raw-info (%tz-read-subzone inf (getf header :type-count)))
(abbreviation-buf (%tz-read-abbrevs inf (getf header :abbrev-length)))
(leap-second-info (%tz-read-leap-seconds inf (getf header :leap-count)))
(std-indicators (%tz-read-indicators inf (getf header :wall-count)))
(gmt-indicators (%tz-read-indicators inf (getf header :utc-count)))
(subzone-info (%tz-make-subzones subzone-raw-info
abbreviation-buf
gmt-indicators
std-indicators)))
(setf (timezone-transitions zone) timezone-transitions)
(setf (timezone-indexes zone) subzone-indexes)
(setf (timezone-subzones zone) subzone-info)
(setf (timezone-leap-seconds zone) leap-second-info))
(setf (timezone-loaded zone) t)))
zone)
(eval-when (:compile-toplevel :load-toplevel :execute)
(defun %make-simple-timezone (name abbrev offset)
(let ((subzone (local-time::make-subzone :offset offset
:daylight-p nil
:abbrev abbrev)))
(local-time::make-timezone
:subzones (make-array 1 :initial-contents (list subzone))
:path nil
:name name
:loaded t)))
;; to be used as #+#.(local-time::package-with-symbol? "SB-EXT" "GET-TIME-OF-DAY")
(defun package-with-symbol? (package name)
(if (and (find-package package)
(find-symbol name package))
'(:and)
'(:or))))
(defparameter +utc-zone+ (%make-simple-timezone "Coordinated Universal Time" "UTC" 0))
(defparameter +gmt-zone+ (%make-simple-timezone "Greenwich Mean Time" "GMT" 0))
(defparameter +none-zone+ (%make-simple-timezone "Explicit Offset Given" "NONE" 0))
(defmacro define-timezone (zone-name zone-file &key (load nil))
"Define zone-name (a symbol or a string) as a new timezone, lazy-loaded from zone-file (a pathname designator relative to the zoneinfo directory on this system. If load is true, load immediately."
(declare (type (or string symbol) zone-name))
(let ((zone-sym (if (symbolp zone-name) zone-name (intern zone-name))))
`(prog1
(defparameter ,zone-sym (make-timezone :path ,zone-file
:name ,(if (symbolp zone-name)
(string-downcase (symbol-name zone-name))
zone-name)))
,@(when load
`((%realize-timezone ,zone-sym))))))
(eval-when (:load-toplevel :execute)
(let ((default-timezone-file #p"/etc/localtime"))
(handler-case
(define-timezone *default-timezone* default-timezone-file :load t)
(t ()
(setf *default-timezone* +utc-zone+)))))
(defparameter *location-name->timezone* (make-hash-table :test 'equal)
"A hashtable with entries like \"Europe/Budapest\" -> timezone-instance")
(defparameter *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal)
"A hashtable of \"CEST\" -> list of timezones with \"CEST\" subzone")
(defun find-timezone-by-location-name (name)
(when (zerop (hash-table-count *location-name->timezone*))
(error "Seems like the timezone repository has not yet been loaded. Hint: see REREAD-TIMEZONE-REPOSITORY."))
(gethash name *location-name->timezone*))
(defun timezone= (timezone-1 timezone-2)
"Return two values indicating the relationship between timezone-1 and timezone-2. The first value is whether the two timezones are equal and the second value indicates whether it is sure or not.
In other words:
\(values t t) means timezone-1 and timezone-2 are definitely equal.
\(values nil t) means timezone-1 and timezone-2 are definitely different.
\(values nil nil) means that it couldn't be determined."
(if (or (eq timezone-1 timezone-2)
(equalp timezone-1 timezone-2))
(values t t)
(values nil nil)))
(defun reread-timezone-repository (&key (timezone-repository *default-timezone-repository-path*))
(check-type timezone-repository (or pathname string))
(let ((root-directory (fad:directory-exists-p timezone-repository)))
(unless root-directory
(error "REREAD-TIMEZONE-REPOSITORY was called with invalid PROJECT-DIRECTORY (~A)."
timezone-repository))
(let ((cutoff-position (length (princ-to-string root-directory))))
(flet ((visitor (file)
(handler-case
(let* ((full-name (subseq (princ-to-string file) cutoff-position))
(name (pathname-name file))
(timezone (%realize-timezone (make-timezone :path file :name name))))
(setf (gethash full-name *location-name->timezone*) timezone)
(map nil (lambda (subzone)
(push timezone (gethash (subzone-abbrev subzone)
*abbreviated-subzone-name->timezone-list*)))
(timezone-subzones timezone)))
(invalid-timezone-file () nil))))
(setf *location-name->timezone* (make-hash-table :test 'equal))
(setf *abbreviated-subzone-name->timezone-list* (make-hash-table :test 'equal))
(cl-fad:walk-directory root-directory #'visitor :directories nil
:test (lambda (file)
(not (find "Etc" (pathname-directory file) :test #'string=)))
:follow-symlinks nil)
(cl-fad:walk-directory (merge-pathnames "Etc/" root-directory) #'visitor :directories nil)))))
(defmacro make-timestamp (&rest args)
`(make-instance 'timestamp ,@args))
(defun clone-timestamp (timestamp)
(make-instance 'timestamp
:nsec (nsec-of timestamp)
:sec (sec-of timestamp)
:day (day-of timestamp)))
(defun transition-position (needle haystack)
(declare (type integer needle)
(type (simple-array integer (*)) haystack))
(loop
with start = 0
with end = (1- (length haystack))
for middle = (floor (+ end start) 2)
while (and (< start end)
(/= needle (elt haystack middle)))
do (cond
((> needle (elt haystack middle))
(setf start (1+ middle)))
(t
(setf end (1- middle))))
finally
(return (max 0 (cond
((minusp end)
0)
((= needle (elt haystack middle))
middle)
((>= needle (elt haystack end))
end)
(t
(1- end)))))))
(defun timestamp-subtimezone (timestamp timezone)
"Return as multiple values the time zone as the number of seconds east of UTC, a boolean daylight-saving-p, and the customary abbreviation of the timezone."
(declare (type timestamp timestamp)
(type (or null timezone) timezone))
(let* ((zone (%realize-timezone (or timezone *default-timezone*)))
(unix-time (timestamp-to-unix timestamp))
(subzone-idx (if (zerop (length (timezone-indexes zone)))
0
(elt (timezone-indexes zone)
(transition-position unix-time
(timezone-transitions zone)))))
(subzone (elt (timezone-subzones zone) subzone-idx)))
(values
(subzone-offset subzone)
(subzone-daylight-p subzone)
(subzone-abbrev subzone))))
(defun %adjust-to-offset (sec day offset)
"Returns two values, the values of new DAY and SEC slots of the timestamp adjusted to the given timezone."
(declare (type integer sec day offset))
(multiple-value-bind (offset-day offset-sec)
(truncate offset +seconds-per-day+)
(let* ((new-sec (+ sec offset-sec))
(new-day (+ day offset-day)))
(cond ((minusp new-sec)
(incf new-sec +seconds-per-day+)
(decf new-day))
((>= new-sec +seconds-per-day+)
(incf new-day)
(decf new-sec +seconds-per-day+)))
(values new-sec new-day))))
(defun %adjust-to-timezone (source timezone &optional offset)
(%adjust-to-offset (sec-of source)
(day-of source)
(or offset
(timestamp-subtimezone source timezone))))
(defun timestamp-minimize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-minimize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(encode-timestamp 0
(if (> part-count 0) 0 sec)
(if (> part-count 1) 0 min)
(if (> part-count 2) 0 hour)
(if (> part-count 3) 1 day)
(if (> part-count 4) 1 month)
year
:offset (if timezone nil offset)
:timezone timezone
:into into))))
(defun timestamp-maximize-part (timestamp part &key
(timezone *default-timezone*)
into)
(let* ((timestamp-parts '(:nsec :sec :min :hour :day :month))
(part-count (position part timestamp-parts)))
(assert part-count nil
"timestamp-maximize-part called with invalid part ~a (expected one of ~a)"
part
timestamp-parts)
(multiple-value-bind (nsec sec min hour day month year day-of-week daylight-saving-time-p offset)
(decode-timestamp timestamp :timezone timezone)
(declare (ignore nsec day-of-week daylight-saving-time-p))
(let ((month (if (> part-count 4) 12 month)))
(encode-timestamp 999999999
(if (> part-count 0) 59 sec)
(if (> part-count 1) 59 min)
(if (> part-count 2) 23 hour)
(if (> part-count 3) (days-in-month month year) day)
month
year
:offset (if timezone nil offset)
:timezone timezone
:into into)))))
(defmacro with-decoded-timestamp ((&key nsec sec minute hour day month year day-of-week daylight-p timezone offset)
timestamp &body forms)
"This macro binds variables to the decoded elements of TIMESTAMP. The TIMEZONE argument is used for decoding the timestamp, and is not bound by the macro. The value of DAY-OF-WEEK starts from 0 which means Sunday."
(let ((ignores)
(types)
(variables))
(macrolet ((initialize (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(progn
(unless ,var
(setf ,var (gensym))
(push ,var ignores))
(push ,var variables)))
(setf ignores (nreverse ignores))
(setf variables (nreverse variables))))
(declare-fixnum-type (&rest vars)
`(progn
,@(loop
:for var :in vars
:collect `(when ,var
(push `(type fixnum ,,var) types)))
(setf types (nreverse types)))))
(when nsec
(push `(type (integer 0 999999999) ,nsec) types))
(declare-fixnum-type sec minute hour day month year)
(initialize nsec sec minute hour day month year day-of-week daylight-p))
`(multiple-value-bind (,@variables)
(decode-timestamp ,timestamp :timezone ,(or timezone '*default-timezone*) :offset ,offset)
(declare (ignore ,@ignores) ,@types)
,@forms)))
(defun %normalize-month-year-pair (month year)
"Normalizes the month/year pair: in case month is < 1 or > 12 the month and year are corrected to handle the overflow."
(multiple-value-bind (year-offset month-minus-one)
(floor (1- month) 12)
(values (1+ month-minus-one)
(+ year year-offset))))
(defun days-in-month (month year)
"Returns the number of days in the given month of the specified year."
(let ((normal-days (aref +rotated-month-days-without-leap-day+
(mod (+ month 9) 12))))
(if (and (= month 2)
(or (and (zerop (mod year 4))
(plusp (mod year 100)))
(zerop (mod year 400))))
(1+ normal-days) ; February on a leap year
normal-days)))
;; TODO scan all uses of FIX-OVERFLOW-IN-DAYS and decide where it's ok to silently fix and where should be and error reported
(defun %fix-overflow-in-days (day month year)
"In case the day number is higher than the maximal possible for the given month/year pair, returns the last day of the month."
(let ((max-day (days-in-month month year)))
(if (> day max-day)
max-day
day)))
(eval-when (:compile-toplevel :load-toplevel)
(defun %list-length= (num list)
"Tests for a list of length NUM without traversing the entire list to get the length."
(let ((c (nthcdr (1- num) list)))
(and c (endp (cdr c)))))
(defun %expand-adjust-timestamp-changes (timestamp changes visitor)
(loop
:with params = ()
:with functions = ()
:for change in changes
:do
(progn
(assert (or
(%list-length= 3 change)
(and (%list-length= 2 change)
(symbolp (first change))
(or (string= (first change) :timezone)
(string= (first change) :utc-offset)))
(and (%list-length= 4 change)
(symbolp (third change))
(or (string= (third change) :to)
(string= (third change) :by))))
nil "Syntax error in expression ~S" change)
(let ((operation (first change))
(part (second change))
(value (if (%list-length= 3 change)
(third change)
(fourth change))))
(cond
((string= operation :set)
(push `(%set-timestamp-part ,part ,value) functions))
((string= operation :offset)
(push `(%offset-timestamp-part ,part ,value) functions))
((string= operation :utc-offset)
(push part params)
(push :utc-offset params))
((string= operation :timezone)
(push part params)
(push :timezone params))
(t (error "Unexpected operation ~S" operation)))))
:finally
(loop
:for (function part value) in functions
:do
(funcall visitor `(,function ,timestamp ,part ,value ,@params)))))
(defun %expand-adjust-timestamp (timestamp changes &key functional)
(let* ((old (gensym "OLD"))
(new (if functional
(gensym "NEW")
old))
(forms (list)))
(%expand-adjust-timestamp-changes old changes
(lambda (change)
(push
`(progn
(multiple-value-bind (nsec sec day)
,change
(setf (nsec-of ,new) nsec)
(setf (sec-of ,new) sec)
(setf (day-of ,new) day))
,@(when functional
`((setf ,old ,new))))
forms)))
(setf forms (nreverse forms))
`(let* ((,old ,timestamp)
,@(when functional
`((,new (clone-timestamp ,old)))))
,@forms
,old)))
) ; eval-when
(defmacro adjust-timestamp (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional t))
(defmacro adjust-timestamp! (timestamp &body changes)
(%expand-adjust-timestamp timestamp changes :functional nil))
(defun %set-timestamp-part (time part new-value &key (timezone *default-timezone*) utc-offset)
;; TODO think about error signalling. when, how to disable if it makes sense, ...
(case part
((:nsec :sec-of-day :day)
(let ((nsec (nsec-of time))
(sec (sec-of time))
(day (day-of time)))
(case part
(:nsec (setf nsec (coerce new-value '(integer 0 999999999))))
(:sec-of-day (setf sec (coerce new-value `(integer 0 ,+seconds-per-day+))))
(:day (setf day new-value)))
(values nsec sec day)))
(otherwise
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year :timezone timezone :offset utc-offset)
time
(ecase part
(:sec (setf sec new-value))
(:minute (setf minute new-value))
(:hour (setf hour new-value))
(:day-of-month (setf day new-value))
(:month (setf month new-value)
(setf day (%fix-overflow-in-days day month year)))
(:year (setf year new-value)
(setf day (%fix-overflow-in-days day month year))))
(encode-timestamp-into-values nsec sec minute hour day month year :timezone timezone :offset utc-offset)))))
(defun %offset-timestamp-part (time part offset &key (timezone *default-timezone*) utc-offset)
"Returns a time adjusted by the specified OFFSET. Takes care of
different kinds of overflows. The setting :day-of-week is possible
using a keyword symbol name of a week-day (see
+DAY-NAMES-AS-KEYWORDS+) as value. In that case point the result to
the previous day given by OFFSET."
(labels ((direct-adjust (part offset nsec sec day)
(cond ((eq part :day-of-week)
(with-decoded-timestamp (:day-of-week day-of-week
:nsec nsec :sec sec :minute minute :hour hour
:day day :month month :year year
:timezone timezone :offset utc-offset)
time
(let ((position (position offset +day-names-as-keywords+ :test #'eq)))
(assert position (position) "~S is not a valid day name" offset)
(let ((offset (+ (- (if (zerop day-of-week)
7
day-of-week))
position)))
(incf day offset)
(cond
((< day 1)
(decf month)
(when (< month 1)
(setf month 12)
(decf year))
(setf day (+ (days-in-month month year) day)))
((let ((days-in-month (days-in-month month year)))
(when (< days-in-month day)
(incf month)
(when (= month 13)
(setf month 1)
(incf year))
(decf day days-in-month)))))
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset utc-offset)))))
((zerop offset)
;; The offset is zero, so just return the parts of the timestamp object
(values nsec sec day))
(t
(let ((old-utc-offset (or utc-offset
(timestamp-subtimezone time timezone)))
new-utc-offset)
(tagbody
top
(ecase part
(:nsec
(multiple-value-bind (sec-offset new-nsec)
(floor (+ offset nsec) 1000000000)
;; the time might need to be adjusted a bit more if q != 0
(setf part :sec
offset sec-offset
nsec new-nsec)
(go top)))
((:sec :minute :hour)
(multiple-value-bind (days-offset new-sec)
(floor (+ sec (* offset (ecase part
(:sec 1)
(:minute +seconds-per-minute+)
(:hour +seconds-per-hour+))))
+seconds-per-day+)
(return-from direct-adjust (values nsec new-sec (+ day days-offset)))))
(:day
(incf day offset)
(setf new-utc-offset (or utc-offset
(timestamp-subtimezone (make-timestamp :nsec nsec :sec sec :day day)
timezone)))
(when (not (= old-utc-offset
new-utc-offset))
;; We hit the DST boundary. We need to restart again
;; with :sec, but this time we know both old and new
;; UTC offset will be the same, so it's safe to do
(setf part :sec
offset (- old-utc-offset
new-utc-offset)
old-utc-offset new-utc-offset)
(go top))
(return-from direct-adjust (values nsec sec day)))))))))
(safe-adjust (part offset time)
(with-decoded-timestamp (:nsec nsec :sec sec :minute minute :hour hour :day day
:month month :year year :timezone timezone :offset utc-offset)
time
(multiple-value-bind (month-new year-new)
(%normalize-month-year-pair
(+ (ecase part
(:month offset)
(:year (* 12 offset)))
month)
year)
;; Almost there. However, it is necessary to check for
;; overflows first
(encode-timestamp-into-values nsec sec minute hour
(%fix-overflow-in-days day month-new year-new)
month-new year-new
:timezone timezone :offset utc-offset)))))
(ecase part
((:nsec :sec :minute :hour :day :day-of-week)
(direct-adjust part offset
(nsec-of time)
(sec-of time)
(day-of time)))
((:month :year) (safe-adjust part offset time)))))
;; TODO merge this functionality into timestamp-difference
(defun timestamp-whole-year-difference (time-a time-b)
"Returns the number of whole years elapsed between time-a and time-b (hint: anniversaries)."
(declare (type timestamp time-b time-a))
(multiple-value-bind (nsec-b sec-b minute-b hour-b day-b month-b year-b day-of-week-b daylight-p-b offset-b)
(decode-timestamp time-b)
(declare (ignore day-of-week-b daylight-p-b))
(multiple-value-bind (nsec-a sec-a minute-a hour-a day-a month-a year-a)
(decode-timestamp time-a)
(declare (ignore nsec-a sec-a minute-a hour-a day-a month-a))
(let ((year-difference (- year-a year-b)))
(if (timestamp<= (encode-timestamp nsec-b sec-b minute-b hour-b
(if (= month-b 2)
(min 28 day-b)
day-b)
month-b
(+ year-difference year-b)
:offset offset-b)
time-a)
year-difference
(1- year-difference))))))
(defun timestamp-difference (time-a time-b)
"Returns the difference between TIME-A and TIME-B in seconds"
(let ((nsec (- (nsec-of time-a) (nsec-of time-b)))
(second (- (sec-of time-a) (sec-of time-b)))
(day (- (day-of time-a) (day-of time-b))))
(when (minusp nsec)
(decf second)
(incf nsec 1000000000))
(when (minusp second)
(decf day)
(incf second +seconds-per-day+))
(let ((result (+ (* day +seconds-per-day+)
second)))
(unless (zerop nsec)
;; this incf turns the result into a float, so only do this when necessary
(incf result (/ nsec 1000000000d0)))
result)))
(defun timestamp+ (time amount unit &optional (timezone *default-timezone*) offset)
(multiple-value-bind (nsec sec day)
(%offset-timestamp-part time unit amount :timezone timezone :utc-offset offset)
(make-timestamp :nsec nsec
:sec sec
:day day)))
(defun timestamp- (time amount unit &optional (timezone *default-timezone*) offset)
(timestamp+ time (- amount) unit timezone offset))
(defun timestamp-day-of-week (timestamp &key (timezone *default-timezone*) offset)
(mod (+ 3 (nth-value 1 (%adjust-to-timezone timestamp timezone offset))) 7))
;; TODO read
;; http://java.sun.com/j2se/1.4.2/docs/api/java/util/GregorianCalendar.html
;; (or something else, sorry :) this scheme only works back until
;; 1582, the start of the gregorian calendar. see also
;; DECODE-TIMESTAMP when fixing if fixing is desired at all.
(defun valid-timestamp-p (nsec sec minute hour day month year)
"Returns T if the time values refer to a valid time, otherwise returns NIL."
(and (<= 0 nsec 999999999)
(<= 0 sec 59)
(<= 0 minute 59)
(<= 0 hour 23)
(<= 1 month 12)
(<= 1 day (days-in-month month year))
(/= year 0)))
(defun encode-timestamp-into-values (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset)
"Returns (VALUES NSEC SEC DAY ZONE) ready to be used for
instantiating a new timestamp object. If the specified time is
invalid, the condition INVALID-TIME-SPECIFICATION is raised."
;; If the user provided an explicit offset, we use that. Otherwise,
(declare (type integer nsec sec minute hour day month year)
(type (or integer null) offset))
(unless (valid-timestamp-p nsec sec minute hour day month year)
(error 'invalid-time-specification))
(let* ((0-based-rotated-month (if (>= month 3)
(- month 3)
(+ month 9)))
(internal-year (if (< month 3)
(- year 2001)
(- year 2000)))
(years-as-days (years-to-days internal-year))
(sec (+ (* hour +seconds-per-hour+)
(* minute +seconds-per-minute+)
sec))
(days-from-zero-point (+ years-as-days
(aref +rotated-month-offsets-without-leap-day+ 0-based-rotated-month)
(1- day)))
(used-offset (or offset
(%guess-offset sec
days-from-zero-point
timezone))))
(multiple-value-bind (utc-sec utc-day)
(%adjust-to-offset sec days-from-zero-point (- used-offset))
(values nsec utc-sec utc-day))))
(defun encode-timestamp (nsec sec minute hour day month year
&key (timezone *default-timezone*) offset into)
"Return a new TIMESTAMP instance corresponding to the specified time
elements."
(declare (type integer nsec sec minute hour day month year))
(multiple-value-bind (nsec sec day)
(encode-timestamp-into-values nsec sec minute hour day month year
:timezone timezone :offset offset)
(if into
(progn
(setf (nsec-of into) nsec)
(setf (sec-of into) sec)
(setf (day-of into) day)
into)
(make-timestamp
:nsec nsec
:sec sec
:day day))))
(defun universal-to-timestamp (universal &key (nsec 0))
"Returns a timestamp corresponding to the given universal time."
;; universal time is seconds from 1900-01-01T00:00:00Z.
(let ((adjusted-universal (- universal #.(encode-universal-time 0 0 0 1 3 2000 0))))
(multiple-value-bind (day second)
(floor adjusted-universal +seconds-per-day+)
(make-timestamp :day day :sec second :nsec nsec))))
(defun timestamp-to-universal (timestamp)
"Return the UNIVERSAL-TIME corresponding to the TIMESTAMP"
;; universal time is seconds from 1900-01-01T00:00:00Z
(+ (* (day-of timestamp) +seconds-per-day+)
(sec-of timestamp)
#.(encode-universal-time 0 0 0 1 3 2000 0)))
(defun unix-to-timestamp (unix &key (nsec 0))
"Return a TIMESTAMP corresponding to UNIX, which is the number of seconds since the unix epoch, 1970-01-01T00:00:00Z."
(multiple-value-bind (days secs)
(floor unix +seconds-per-day+)
(make-timestamp :day (- days 11017) :sec secs :nsec nsec)))
(defun timestamp-values-to-unix (seconds day)
"Return the Unix time correspondint to the values used to encode a TIMESTAMP"
(+ (* (+ day 11017) +seconds-per-day+) seconds))
(defun timestamp-to-unix (timestamp)
"Return the Unix time corresponding to the TIMESTAMP"
(declare (type timestamp timestamp))
(timestamp-values-to-unix (sec-of timestamp) (day-of timestamp)))
#+(and allegro (not os-windows))
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Allegro common lisp requires some toplevel hoops through which to
;; jump in order to call unix's gettimeofday properly.
(ff:def-foreign-type timeval
(:struct (tv_sec :long)
(tv_usec :long)))
(ff:def-foreign-call
(allegro-ffi-gettimeofday "gettimeofday")
((timeval (* timeval))
;; and do this to allow a 0 for NULL
(timezone :foreign-address))
:returning (:int fixnum)))
#+(and allegro os-windows)
(eval-when (:compile-toplevel :load-toplevel :execute)
;; Allegro common lisp requires some toplevel hoops through which to
;; jump in order to call unix's gettimeofday properly.
(ff:def-foreign-type filetime
(:struct (|dwLowDateTime| :int)
(|dwHighDateTime| :int)))
(ff:def-foreign-call
(allegro-ffi-get-system-time-as-file-time "GetSystemTimeAsFileTime")
((filetime (* filetime)))
:returning :void))