timer-deque-rs 0.6.0

A OS based timer and timer queue which implements timeout queues of different types.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
/*-
 * timer-deque-rs - a Rust crate which provides timer and timer queues based on target OS
 *  functionality.
 * 
 * Copyright (C) 2025 Aleksandr Morozov alex@nixd.org
 *  4neko.org alex@4neko.org
 * 
 * The timer-rs crate can be redistributed and/or modified
 * under the terms of either of the following licenses:
 *
 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
 *                     
 *   2. The MIT License (MIT)
 *                     
 *   3. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
 */

use std::{borrow::Cow, cmp::Ordering, fmt, io::{self}, ops, os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd}, sync::Arc, time::Duration};

use chrono::{DateTime, TimeZone};
use nix::libc::{self, ECANCELED, EWOULDBLOCK};
use bitflags::bitflags;


use crate::{common, timer_portable::portable_error::TimerPortResult};

#[cfg(target_os = "linux")]
pub use super::linux::timer_fd_linux::TimerFdInternal;

#[cfg(
    all(
        any(
            target_os = "freebsd",
            target_os = "dragonfly",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "macos",
        ),
        feature = "bsd_use_timerfd"
    )
)]
pub use super::bsd::timer_fd_bsd::TimerFdInternal;

#[cfg(
    all(
        any(
            target_os = "freebsd",
            target_os = "dragonfly",
            target_os = "netbsd",
            target_os = "openbsd",
            target_os = "macos",
        ),
        not(feature = "bsd_use_timerfd")
    )
)]
pub use super::bsd::timer_kqueue_fd_bsd::TimerFdInternal;


/// A timer type
#[allow(non_camel_case_types)]
#[repr(i32)]
#[derive(Debug)]
pub enum TimerType
{
    /// A settable system-wide real-time clock.
    CLOCK_REALTIME = libc::CLOCK_REALTIME,

    /// A nonsettable monotonically increasing clock that measures  time
    /// from some unspecified point in the past that does not change af‐
    /// ter system startup.

    CLOCK_MONOTONIC = libc::CLOCK_MONOTONIC,

    
    /// Like CLOCK_MONOTONIC, this is a monotonically increasing  clock.
    /// However,  whereas the CLOCK_MONOTONIC clock does not measure the
    /// time while a system is suspended, the CLOCK_BOOTTIME clock  does
    /// include  the time during which the system is suspended.  This is
    /// useful  for  applications  that  need   to   be   suspend-aware.
    /// CLOCK_REALTIME is not suitable for such applications, since that
    /// clock is affected by discontinuous changes to the system clock.
    #[cfg(target_os = "linux")]
    CLOCK_BOOTTIME = libc::CLOCK_BOOTTIME,

    /// This clock is like CLOCK_REALTIME, but will wake the  system  if
    /// it  is suspended.  The caller must have the CAP_WAKE_ALARM capa‐
    /// bility in order to set a timer against this clock.
    #[cfg(target_os = "linux")]
    CLOCK_REALTIME_ALARM = libc::CLOCK_REALTIME_ALARM,

    /// This clock is like CLOCK_BOOTTIME, but will wake the  system  if
    /// it  is suspended.  The caller must have the CAP_WAKE_ALARM capa‐
    /// bility in order to set a timer against this clock.
    #[cfg(target_os = "linux")]
    CLOCK_BOOTTIME_ALARM = libc::CLOCK_BOOTTIME_ALARM,
}

/*
impl Into<libc::clockid_t> for TimerType 
{
    fn into(self) -> libc::clockid_t
    {
        match self
        {
            Self::CLOCK_REALTIME        => return ,
            Self::CLOCK_MONOTONIC       => return ,
            #[cfg(target_os = "linux")]
            Self::CLOCK_BOOTTIME        => return libc::CLOCK_BOOTTIME,
            #[cfg(target_os = "linux")]
            Self::CLOCK_REALTIME_ALARM  => return libc::CLOCK_REALTIME_ALARM,
            #[cfg(target_os = "linux")]
            Self::CLOCK_BOOTTIME_ALARM  => return libc::CLOCK_BOOTTIME_ALARM,
            #[cfg(any(
                target_os = "freebsd",
                target_os = "dragonfly",
                target_os = "netbsd",
                target_os = "openbsd",
                target_os = "macos",
            ))]
            _ => return libc::CLOCK_REALTIME,
        }
    }
}*/

impl From<TimerType> for libc::clockid_t 
{
    fn from(value: TimerType) -> Self 
    {
        return value as libc::clockid_t;
    }
}


bitflags! {     
    /// Flags controling the type of the timer type.  
    #[derive(Default, Debug, Clone, Copy, PartialEq, Eq)] 
    pub struct TimerFlags: i32  
    {     
        /// Set the O_NONBLOCK file status flag on the open file  de‐
        /// scription  (see  open(2)) referred to by the new file de‐
        /// scriptor.  Using this flag saves extra calls to  fcntl(2)
        /// to achieve the same result.
        const TFD_NONBLOCK = libc::TFD_NONBLOCK;

        /// Set  the  close-on-exec (FD_CLOEXEC) flag on the new file
        /// descriptor.  See the description of the O_CLOEXEC flag in
        /// open(2) for reasons why this may be useful.
        const TFD_CLOEXEC = libc::TFD_CLOEXEC;
    }
}


bitflags! {     
    /// A bit mask that can include the values.
    #[derive(Default, Debug, Eq, PartialEq, Clone, Copy)] 
    pub struct TimerSetTimeFlags: i32  
    {     
        /// > Interpret  new_value.it_value as an absolute value on the timer's
        /// > clock.  The timer will expire when the value of the timer's clock
        /// > reaches the value specified in new_value.it_value.
        const TFD_TIMER_ABSTIME = libc::TFD_TIMER_ABSTIME;

        /// > If this flag is specified along with  TFD_TIMER_ABSTIME  and  the
        /// > clock  for  this timer is CLOCK_REALTIME or CLOCK_REALTIME_ALARM,
        /// > then mark this timer as cancelable if the real-time clock  under‐
        /// > goes  a  discontinuous change (settimeofday(2), clock_settime(2),
        /// > or similar).  When  such  changes  occur,  a  current  or  future
        /// > read(2)  from  the file descriptor will fail with the error 
        /// > ECANCELED.
        const TFD_TIMER_CANCEL_ON_SET = libc::TFD_TIMER_CANCEL_ON_SET;
    }
}


/// A trait which defines a standart interface for the different time types i.e
/// 
/// - [RelativeTime] a relative time to the system's clock.
/// 
/// - [AbsoluteTime] an absolute time to the systmem's clock.
/// 
/// This is an internal trait and should not be exposed to the outside of the crate.
pub trait ModeTimeType: Eq + PartialEq + Ord + PartialOrd + fmt::Display + fmt::Debug + Clone + Copy
{
    
    /// Creates new instance from the two components: seconds and subnanoseconds of the seconds.
    /// 
    /// # Arguments
    /// 
    /// `time_spec` - [timespec] - a time to convert. It is assumed that the values
    ///     are correct.
    /// 
    /// # Returns
    /// 
    /// An instance is returend.
    fn new(time_spec: timespec) -> Self where Self: Sized;

    /// Returns the seconds without the nanoseconds fraction.
    fn get_sec(&self) -> i64;

    /// Returns the nanoseconds fraction from seconds, not a full time in nanoseconds.
    fn get_nsec(&self) -> i64;

    /// Verifies that the timer is not set to zero. For the [RelativeTime] it always returns true.
    fn is_value_valid(&self) -> bool;

    /// Returns the [TimerSetTimeFlags] which are autoinitialized for both types. This flags
    /// should be passed to timer.
    fn get_flags() -> TimerSetTimeFlags;
}

/// A `relative` time i.e time which is not binded to the system's clock.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct RelativeTime
{
    /// Seconds
    time_sec: i64,

    /// A fraction of ns from second
    time_nsec: i64,
}

/// Converts the [Duration] to [RelativeTime] taking the `subsec_nanos`
/// for the `time_nsec`.
impl From<Duration> for RelativeTime
{
    fn from(value: Duration) -> Self 
    {
        return Self
        {
            time_sec: 
                value.as_secs() as i64,
            time_nsec: 
                value.subsec_nanos() as i64,
        };
    }
}

impl From<RelativeTime> for Duration
{
    fn from(value: RelativeTime) -> Self 
    {
        return Duration::new(value.time_sec as u64, value.time_nsec as u32);
    }
}

impl Ord for RelativeTime
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        return 
            self
                .time_sec
                .cmp(&other.time_sec)
                .then(
                    self
                        .time_nsec
                        .cmp(&other.time_nsec)
                );
    }
}

impl PartialOrd for RelativeTime
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> 
    {
        return Some(self.cmp(other));
    }
}

impl fmt::Display for RelativeTime
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "[relative] sec: {}, nsec: {}", self.time_sec, self.time_nsec)
    }
}

impl ModeTimeType for RelativeTime
{
    fn new(time_spec: timespec) -> RelativeTime
    {
        return   
            Self::new_time(time_spec.tv_sec, time_spec.tv_nsec);
    }
    
    fn get_sec(&self) -> i64 
    {
        return self.time_sec;
    }
    
    fn get_nsec(&self) -> i64 {

        return self.time_nsec;
    }

    fn is_value_valid(&self) -> bool 
    {
        return true;    
    }

    fn get_flags() -> TimerSetTimeFlags
    {
        return TimerSetTimeFlags::empty();
    }
}

impl RelativeTime
{
    /// max nanoseconds
    pub const MAX_NS: i64 = 1_000_000_000;

    /// Creates new instance for relative time accepting the user input.
    /// 
    /// Automatically corrects the `time_nsec` value if it is larger than
    /// 999_999_999ns.
    /// 
    /// # Arguments
    /// 
    /// `time_sec` - [i64] a seconds in relative notation.
    /// 
    /// `time_nsec` - [i64] nanoseconds of relative seconds value. Should not be 
    ///     larger than 999_999_999 which is defined by const [Self::MAX_NS]. In
    ///     case if it is larger, the `nsec` will be rounded and an extra secons
    ///     will be added.
    pub 
    fn new_time(time_sec: i64, time_nsec: i64) -> Self
    {
        let extra_sec = time_nsec / Self::MAX_NS;
        let nsec_new = time_nsec % Self::MAX_NS;

        return 
            Self
            { 
                time_nsec: nsec_new, 
                time_sec: time_sec + extra_sec,
            };
    }

    pub 
    fn is_zero(&self) -> bool
    {
        return self.time_nsec == 0 && self.time_sec == 0;
    } 
}

/// An `absolute` time which are binded to the system's clock
/// and never be zero except when timer is reset.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub struct AbsoluteTime
{
    /// A full seconds.
    time_sec: i64,

    /// A fraction (subset) of nanoseconds from the second.
    time_nsec: i64,
}

/// Convers the `chrono` [DateTime<TZ>] into the [AbsoluteTime] using 
/// the `TZ` [TimeZone]  taking the `ns` fraction of a second (subsec_nano) 
/// using `timestamp_subsec_nanos` function.
impl<TZ: TimeZone> From<DateTime<TZ>> for AbsoluteTime
{
    fn from(value: DateTime<TZ>) -> Self 
    {
        return Self
        {
            time_sec: 
                value.timestamp(), 
            time_nsec: 
                value.timestamp_subsec_nanos() as i64,
        };
    }
}

/// Converts the [Duration] to [RelativeTime] taking the `subsec_nanos`
/// for the `time_nsec`.
impl From<Duration> for AbsoluteTime
{
    fn from(value: Duration) -> Self 
    {
        return Self
        {
            time_sec: 
                value.as_secs() as i64,
            time_nsec: 
                value.subsec_nanos() as i64,
        };
    }
}

impl From<AbsoluteTime> for Duration
{
    fn from(value: AbsoluteTime) -> Self 
    {
        return Duration::new(value.time_sec as u64, value.time_nsec as u32);
    }
}

impl Ord for AbsoluteTime
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        return 
            self
                .time_sec
                .cmp(&other.time_sec)
                .then(
                    self
                        .time_nsec
                        .cmp(&other.time_nsec)
                );
    }
}

impl PartialOrd for AbsoluteTime
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> 
    {
        return Some(self.cmp(other));
    }
}

impl ops::AddAssign<Duration> for AbsoluteTime
{
    fn add_assign(&mut self, rhs: Duration) 
    {
        self.time_nsec += rhs.subsec_nanos() as i64;
        let add_sec = self.time_nsec / Self::MAX_NS;

        if add_sec > 0
        {
            self.time_nsec %=  Self::MAX_NS;
        }
        
        self.time_sec += rhs.as_secs() as i64 + add_sec;
    }
}

impl ops::AddAssign<RelativeTime> for AbsoluteTime
{
    fn add_assign(&mut self, rhs: RelativeTime) 
    {
        self.time_nsec += rhs.time_nsec;
        let add_sec = self.time_nsec / Self::MAX_NS;

        if add_sec > 0
        {
            self.time_nsec %=  Self::MAX_NS;
        }
        
        self.time_sec += rhs.time_sec + add_sec;
    }
}

impl ops::Add<Duration> for AbsoluteTime
{
    type Output = AbsoluteTime;

    fn add(mut self, rhs: Duration) -> Self::Output 
    {
        self += rhs;

        return self;
    }
}

impl ops::Add<RelativeTime> for AbsoluteTime
{
    type Output = AbsoluteTime;

    fn add(mut self, rhs: RelativeTime) -> Self::Output 
    {
        self += rhs;

        return self;
    }
}

impl ops::SubAssign<Duration> for AbsoluteTime
{
    fn sub_assign(&mut self, rhs: Duration) 
    {
        let mut sec = rhs.as_secs() as i64;
        let mut nsec = self.time_nsec - rhs.subsec_nanos() as i64;

        if nsec < 0
        {
            sec += 1;

            nsec = Self::MAX_NS + nsec;
        }
        
        self.time_nsec = nsec;
        self.time_sec -= sec;

        return;
    }
}

impl ops::SubAssign<RelativeTime> for AbsoluteTime
{
    fn sub_assign(&mut self, mut rhs: RelativeTime) 
    {

        let mut nsec = self.time_nsec - rhs.time_nsec;

        if nsec < 0
        {
            rhs.time_sec += 1;

            nsec = Self::MAX_NS + nsec;
        }
        
        self.time_nsec = nsec;
        self.time_sec -= rhs.time_sec;

        return;
    }
}

impl ops::Sub<Duration> for AbsoluteTime
{
    type Output = AbsoluteTime;

    fn sub(mut self, rhs: Duration) -> Self::Output 
    {
        self -= rhs;

        return self;
    }
}

impl ops::Sub<RelativeTime> for AbsoluteTime
{
    type Output = AbsoluteTime;

    fn sub(mut self, rhs: RelativeTime) -> Self::Output 
    {
        self -= rhs;

        return self;
    }
}

impl ops::SubAssign for AbsoluteTime
{
    fn sub_assign(&mut self, mut rhs: Self) 
    {

        let mut nsec = self.time_nsec - rhs.time_nsec;

        if nsec < 0
        {
            rhs.time_sec += 1;

            nsec = Self::MAX_NS + nsec;
        }
        
        self.time_nsec = nsec;
        self.time_sec -= rhs.time_sec;

        return;
    }
}

impl ops::Sub for AbsoluteTime
{
    type Output = AbsoluteTime;

    fn sub(mut self, rhs: Self) -> Self::Output 
    {
        self -= rhs;

        return self;
    }
}


impl fmt::Display for AbsoluteTime
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "[absolute] {}.{:09}sec", self.time_sec, self.time_nsec)
    }
}


impl ModeTimeType for AbsoluteTime
{
    fn new(time_spec: timespec) -> Self where Self: Sized 
    {
        return 
            unsafe { Self::new_time_unchecked(time_spec.tv_sec, time_spec.tv_nsec) };
    }

    fn get_sec(&self) -> i64 
    {
        return self.time_sec;
    }
    
    fn get_nsec(&self) -> i64 
    {

        return self.time_nsec;
    }

    fn is_value_valid(&self) -> bool 
    {
        return self.time_nsec != 0 || self.time_sec != 0;
    }

    fn get_flags() -> TimerSetTimeFlags
    {
        return TimerSetTimeFlags::TFD_TIMER_ABSTIME | TimerSetTimeFlags::TFD_TIMER_CANCEL_ON_SET;
    }
}

impl AbsoluteTime
{
    /// max nanoseconds
    pub const MAX_NS: i64 = 1_000_000_000;//999_999_999;
}

impl AbsoluteTime
{
    /// Creates an instance with the current local time.
    pub 
    fn now() -> Self
    {
        let value = common::get_current_timestamp();

        return Self
        {
            time_sec: value.timestamp(), 
            time_nsec: value.timestamp_subsec_nanos() as i64,
        }
    }

    pub 
    fn new_time(time_sec: i64, time_nsec: i64) -> Option<Self>
    {
        let tm = 
            unsafe { Self::new_time_unchecked(time_sec, time_nsec) };

        if tm.is_value_valid() == false
        {
            return None;
        }

        return Some(tm);
    }

    /// Creates new instance for absolute time accepting the user input.
    /// 
    /// Automatically corrects the `time_nsec` value if it is larger than
    /// 999_999_999ns.
    /// 
    /// # Arguments
    /// 
    /// `time_sec` - [i64] a seconds in absolute notation.
    /// 
    /// `time_nsec` - [i64] nanoseconds of absolute seconds value. Should not be 
    ///     larger than 999_999_999 which is defined by const [Self::MAX_NS]. In
    ///     case if it is larger, the `nsec` will be rounded and an extra secons
    ///     will be added.
    /// 
    /// # Returns 
    /// 
    /// An instance is returned. May panic on overflow.
    pub unsafe 
    fn new_time_unchecked(time_sec: i64, time_nsec: i64) -> Self
    {
        let extra_sec = time_nsec / Self::MAX_NS;
        let nsec_new = time_nsec % Self::MAX_NS;

        return 
            Self
            { 
                time_nsec: nsec_new, 
                time_sec: time_sec + extra_sec,
            };
    }

    /// Compares only full seconds without nanoseconds fraction (subnano).
    pub 
    fn seconds_cmp(&self, other: &Self) -> Ordering
    {
        return self.time_sec.cmp(&other.time_sec);
    }

    pub 
    fn add_sec(mut self, seconds: i64) -> Self
    {
        self.time_sec += seconds;

        return self;
    }

    pub 
    fn reset_nsec(mut self) -> Self
    {
        self.time_nsec = 0;

        return self;
    }
}



/// A timer expiry modes. Not every OS supports 
/// every mode. Read comments for the OS specific
/// timer. For the `nanoseconds` param the max value
/// is 999_999_999 for most OSes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TimerExpMode<TIMERTYPE: ModeTimeType>
{
    /// Disarmed
    None, 

    /// A timer which is triggered once.
    OneShot
    {
        timeout: TIMERTYPE
    },
    
    /// Interval with the initial delay.
    IntervalDelayed
    {
        /// First event delay.
        delay_tm: TIMERTYPE,

        /// Interval.
        interv_tm: TIMERTYPE
    },

    /// Interval, with the first timeout event 
    /// equal to interval values.
    Interval
    {
        /// Interval seconds.
        interv_tm: TIMERTYPE
    },
}


impl ops::AddAssign<RelativeTime> for TimerExpMode<AbsoluteTime>
{
    fn add_assign(&mut self, rhs: RelativeTime) 
    {
        match self
        {
            TimerExpMode::None => 
                return,
            TimerExpMode::OneShot { timeout } => 
            {
                *timeout += rhs;
                
            },
            TimerExpMode::IntervalDelayed { interv_tm, .. } => 
            {
                *interv_tm += rhs;
            },
            TimerExpMode::Interval { interv_tm } => 
            {
               *interv_tm += rhs;
            },
        }
    }
}


impl ops::Add<RelativeTime> for TimerExpMode<AbsoluteTime>
{
    type Output = TimerExpMode<AbsoluteTime>;

    fn add(mut self, rhs: RelativeTime) -> Self::Output 
    {
        self += rhs;

        return self;
    }
}


impl<TIMERTYPE: ModeTimeType> Ord for TimerExpMode<TIMERTYPE>
{
    fn cmp(&self, other: &Self) -> Ordering 
    {
        match (self, other)
        {
            (TimerExpMode::None, TimerExpMode::None) => 
                return Ordering::Equal,
            (TimerExpMode::OneShot{ timeout }, TimerExpMode::OneShot { timeout: timeout2 }) => 
            { 
                return timeout.cmp(timeout2);
            },
            (
                TimerExpMode::IntervalDelayed{ delay_tm, interv_tm }, 
                TimerExpMode::IntervalDelayed{ delay_tm: delay_tm2, interv_tm: interv_tm2 }
            ) =>
            {
                return 
                    delay_tm.cmp(delay_tm2)
                        .then(interv_tm.cmp(interv_tm2));
            },
            (TimerExpMode::Interval { interv_tm }, TimerExpMode::Interval { interv_tm: interv_tm2 }) => 
            {
                return interv_tm.cmp(interv_tm2);
            },
            _ => 
                panic!("cannot compare different types {} and {}", self, other)
        }
    }
}

impl<TIMERTYPE: ModeTimeType> PartialOrd for TimerExpMode<TIMERTYPE>
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> 
    {
        return Some(self.cmp(other));
    }
}



/// Implementations of the [TimerExpMode] for [AbsoluteTime].
impl TimerExpMode<AbsoluteTime>
{
    /// Checks value for the `set_time` function. To disarm timer 
    /// use `unset_time`.
    #[inline]
    fn is_valid_inner(&self) -> bool
    {
        match self
        {
            Self::None => 
                return false,
            Self::OneShot{ timeout} => 
                return timeout.is_value_valid(),
            Self::IntervalDelayed{ delay_tm, interv_tm } => 
                return delay_tm.is_value_valid() && interv_tm.is_value_valid(),
            Self::Interval{ interv_tm } => 
                return interv_tm.is_value_valid()
        }
    }

    /// Construct the [TimerExpMode::OneShot] timer. For the `absolute` timer
    /// only this type is available. The [AbsoluteTime] should be provided which
    /// should be ahead of the OS'es timer.
    pub 
    fn new_oneshot(abs_time: AbsoluteTime) -> Self
    {
        return Self::OneShot { timeout: abs_time };
    }
}



/// Implementations of the [TimerExpMode] for [RelativeTime].
impl TimerExpMode<RelativeTime>
{
    /// Construct the [TimerExpMode::OneShot] timer. A [RelativeTime] should 
    /// be provided as argument. This type of timer is triggered only once.
    pub 
    fn new_oneshot(rel_time: RelativeTime) -> Self
    {
        return Self::OneShot { timeout: rel_time };
    }

    /// Constrcut the [TimerExpMode::Interval] timer. A [RelativeTime] should 
    /// be provided as agument which specifies the trigger interval.
    pub 
    fn new_interval(rel_time: RelativeTime) -> Self
    {
        return Self::Interval { interv_tm: rel_time };
    }

    /// Construct the [TimerExpMode::IntervalDelayed] timer. A two [RelativeTime] 
    /// arguments should be provided which would set the initial delay and further
    /// interval. The initial delay happens only once. Then the interval will be used.
    /// If `delay_time` and `intev_time` are same, acts as `new_interval`.
    pub 
    fn new_interval_with_init_delay(delay_time: RelativeTime, intev_time: RelativeTime) -> Self
    {
        return Self::IntervalDelayed { delay_tm: delay_time, interv_tm: intev_time };
    }
}

impl<TIMERTYPE: ModeTimeType> TimerExpMode<TIMERTYPE>
{
    /// Disarms the timer.
    #[inline]
    pub 
    fn reset() -> Self
    {
        return Self::None;
    }
}

impl<TIMERTYPE: ModeTimeType> fmt::Display for TimerExpMode<TIMERTYPE>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::None => 
                write!(f, "disarmed"),
            Self::OneShot{ timeout } => 
                write!(f, "oneshot {}", timeout),
            Self::IntervalDelayed
                { delay_tm, interv_tm } => 
                write!(f, "interval {} with delay {}", interv_tm, delay_tm),
            Self::Interval{ interv_tm } => 
                write!(f, "interval {}", interv_tm),
        }
    }
}



/*
#[cfg(target_os = "macos")]
#[repr(C)]
pub struct timespec 
{
    pub tv_sec: libc::time_t,
    pub tv_nsec: libc::c_long,
}
#[cfg(target_os = "macos")]
#[repr(C)]
pub struct itimerspec 
{
    pub it_interval: timespec,
    pub it_value: timespec,
}
    */

/// A timer FD read operation result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TimerReadRes<T: Sized + fmt::Debug + fmt::Display + Clone + Eq + PartialEq>
{
    /// Read successfull.
    Ok(T),

    /// TFD_TIMER_ABSTIME 
    /// > Marks this timer as cancelable if the real-time clock  under‐
    /// > goes  a  discontinuous change (settimeofday(2), clock_settime(2),
    /// > or similar).  When  such  changes  occur,  a  current  or  future
    /// > read(2)  from  the file descriptor will fail with the error 
    /// > ECANCELED.
    Cancelled,

    /// EAGAIN
    /// If FD is nonblocking then this will be returned.
    WouldBlock,
}

impl TimerReadRes<u64>
{
    pub 
    fn ok() -> Self
    {
        return Self::Ok(1);
    }
}

impl<T: Sized + fmt::Debug + fmt::Display + Clone + Eq + PartialEq> From<io::Error> for TimerReadRes<T>
{
    fn from(value: io::Error) -> Self 
    {
        if let Some(errn) = value.raw_os_error()
        {
            if errn == ECANCELED
            {
                return Self::Cancelled;
            }
            else if errn == EWOULDBLOCK
            {
                return Self::WouldBlock;
            }
        }

        return Self::Cancelled;
    }
}

impl<T: Sized + fmt::Debug + fmt::Display + Clone + Eq + PartialEq> fmt::Display for TimerReadRes<T>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        match self
        {
            Self::Ok(ovfl) => 
                write!(f, "OK(overflows:{})", ovfl),
            Self::Cancelled => 
                write!(f, "CANCELLED"),
            Self::WouldBlock => 
                write!(f, "WOULDBLOCK"),
        }
    }
}

impl<T: Sized + fmt::Debug + fmt::Display + Clone + Eq + PartialEq> TimerReadRes<T>
{
    pub 
    fn unwrap(self) -> T
    {
        let Self::Ok(t) = self
        else { panic!("can not unwrap {:?}", self)};

        return t;
    }
}

pub trait FdTimerRead: AsFd + AsRawFd + fmt::Display + AsRef<str> + PartialEq<str> + PartialEq<RawFd>
{
    /// Attempts to read the timer. The realization is different on different OS. The main purpose 
    /// is to check if timer is ready (ended).
    /// 
    /// # Returns
    /// 
    /// * If FD is configured as non-blocking then returns 
    ///     [TimerReadRes::WouldBlock] otherwise would block.
    /// 
    /// * If daytime modification happened the 
    ///     [TimerReadRes::Cancelled] will be returned, however
    ///     it depends if the [TimerSetTimeFlags::TFD_TIMER_CANCEL_ON_SET]
    ///     is set with [TimerSetTimeFlags::TFD_TIMER_ABSTIME]. Does not
    ///     work on KQueue implementation.
    /// 
    /// * If read was successfull the amount of the overflows before
    ///     read will be returned i.e [TimerReadRes::Ok]. 
    ///     Normally is is `1`. If `0` is returned then probably the
    ///     time or day was modified.
    /// 
    /// * The [Result::Err] is returned if other error occured.
    fn read(&self) -> TimerPortResult<TimerReadRes<u64>>;
}

pub trait FdTimerMarker: FdTimerRead + Eq + PartialEq + PartialEq<RawFd>
{
    fn clone_timer(&self) -> TimerFd;

    fn get_strong_count(&self) -> usize;
}


/// A common trait which is implemented by all timer realizationss for different OSes.
pub trait FdTimerCom: FdTimerRead
{
    /// Creates new isntance of the timer.
    /// 
    /// # Arguments
    /// 
    /// * `label` - a [Cow] string which defines a title of the timer for identification.
    /// 
    /// * `timer_type` - a [TimerType] a clock source
    /// 
    /// * `timer_flags` - a [TimerFlags] configuration of the timer's FD.
    /// 
    /// # Returns
    /// 
    /// A [Result] is retuned with instance on success.
    fn new(label: Cow<'static, str>, timer_type: TimerType, timer_flags: TimerFlags) -> TimerPortResult<Self>
    where Self: Sized;

    /// Sets the timer. The timer starts immidiatly and working depending on the `timer_exp` mode.
    /// 
    /// In case of timer does not support [TimerExpMode::IntervalDelayed] nativly (on OS level), the
    /// crate will store the `interval` part and set interval on first `read()` i.e after the `delay`
    /// and remove the stored `interval` (or may not) from the inner field.
    fn set_time<TIMERTYPE: ModeTimeType>(&self, timer_exp: TimerExpMode<TIMERTYPE>) -> TimerPortResult<()>;

    /// Unsets the timer. The timer stops immidiatly.
    fn unset_time(&self) -> TimerPortResult<()>;

    /// Sets the timer to non-blocking (on case if `flag` is `true`). 
    /// If the timer was inited with
    /// [TimerFlags::TFD_NONBLOCK], then this will not do anything. 
    fn set_nonblocking(&self, flag: bool) -> TimerPortResult<()>;

    /// Reads the FD's flags and check if Fd is in non-blocking mode. 
    /// May return error.
    /// 
    /// # Returns
    /// 
    /// * `true` - FD is non-blocking
    /// 
    /// * `false` - FD is blocking
    fn is_nonblocking(&self) -> TimerPortResult<bool>;
}

#[derive(Debug)]
pub struct TimerFd(Arc<TimerFdInternal>);

impl fmt::Display for TimerFd
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "{}", self.0)
    }
}

impl AsFd for TimerFd
{
    fn as_fd(&self) -> BorrowedFd<'_> 
    {
        return self.0.as_fd();
    }
}

impl AsRawFd for TimerFd
{
    fn as_raw_fd(&self) -> RawFd 
    {
        return self.0.as_raw_fd();
    }
}
impl AsRef<str> for TimerFd
{
    fn as_ref(&self) -> &str 
    {
        return self.0.as_ref().as_ref();
    }
}

impl Eq for TimerFd {}

impl PartialEq for TimerFd
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self.0 == other.0
    }
}

impl PartialEq<RawFd> for TimerFd
{
    fn eq(&self, other: &RawFd) -> bool 
    {
        return self.0.as_raw_fd() == *other;
    }
}

impl PartialEq<str> for TimerFd
{
    fn eq(&self, other: &str) -> bool 
    {
        return self.0.as_ref() == other;
    }
}

impl FdTimerMarker for TimerFd
{
    fn clone_timer(&self) -> TimerFd 
    {
        return Self(self.0.clone());
    }

    fn get_strong_count(&self) -> usize 
    {
        return Arc::strong_count(&self.0);
    }
}

impl TimerFd
{
    pub 
    fn new(label: Cow<'static, str>, timer_type: TimerType, timer_flags: TimerFlags) -> TimerPortResult<Self>
    {
        return Ok(
            Self( Arc::new(TimerFdInternal::new(label, timer_type, timer_flags)?) )
        );
    }

    pub 
    fn get_timer(&self) -> &TimerFdInternal
    {
        return &self.0;
    }
}

impl FdTimerRead for TimerFd
{
    fn read(&self) -> TimerPortResult<TimerReadRes<u64>> 
    {
        return self.0.read();
    }
}

pub use nix::libc::{itimerspec, timespec};

/// Converts from [itimerspec] into [TimerExpMode] of the `TIMERTYPE`.
impl<TIMERTYPE: ModeTimeType> From<itimerspec> for TimerExpMode<TIMERTYPE>
{
    fn from(value: itimerspec) -> Self 
    {
        if value.it_interval.tv_sec == 0 && value.it_interval.tv_nsec == 0 &&
            value.it_value.tv_sec == 0 && value.it_value.tv_nsec == 0
        {
            // unset
            return Self::None;
        }
        else if value.it_interval.tv_sec == 0 && value.it_interval.tv_nsec == 0
        {
            // one shot
            return 
                Self::OneShot
                { 
                    timeout: TIMERTYPE::new(value.it_value) 
                };
        }
        else if value.it_interval.tv_sec == value.it_value.tv_sec &&
            value.it_interval.tv_nsec == value.it_value.tv_nsec
        {
            // interval
            return 
                Self::Interval
                { 
                    interv_tm: TIMERTYPE::new(value.it_interval) 
                };
        }
        else
        {
            // delayed interval
            return 
                Self::IntervalDelayed 
                { 
                    delay_tm: TIMERTYPE::new(value.it_value),
                    interv_tm: TIMERTYPE::new(value.it_interval) 
                };
        }
    }
}


impl<TIMERTYPE: ModeTimeType> From<TimerExpMode<TIMERTYPE>> for itimerspec
{
    fn from(value: TimerExpMode<TIMERTYPE>) -> Self 
    {
        return (&value).into();
    }
}

/// Converts from the reference to [TimerExpMode] of the `TIMERTYPE` into the 
/// [itimerspec].
impl<TIMERTYPE: ModeTimeType> From<&TimerExpMode<TIMERTYPE>> for itimerspec
{
    fn from(value: &TimerExpMode<TIMERTYPE>) -> Self 
    {
        match value
        {
            TimerExpMode::None => 
                return 
                    itimerspec 
                    {
                        it_interval: timespec 
                        {
                            tv_sec: 0,
                            tv_nsec: 0,
                        },
                        it_value: timespec
                        {
                            tv_sec: 0,
                            tv_nsec: 0,
                        },
                    },
            TimerExpMode::OneShot{ timeout} =>
                return 
                    itimerspec 
                    {
                        it_interval: timespec 
                        {
                            tv_sec: 0,
                            tv_nsec: 0,
                        },
                        it_value: timespec
                        {
                            tv_sec: timeout.get_sec(),
                            tv_nsec: timeout.get_nsec(),
                        },
                    },
            TimerExpMode::IntervalDelayed{ delay_tm, interv_tm } => 
                return 
                    itimerspec 
                    {
                        it_interval: timespec 
                        {
                            tv_sec: interv_tm.get_sec(),
                            tv_nsec: interv_tm.get_nsec(),
                        },
                        it_value: timespec
                        {
                            tv_sec: delay_tm.get_sec(),
                            tv_nsec: delay_tm.get_nsec(),
                        },
                    },
            TimerExpMode::Interval{ interv_tm } => 
                return 
                    itimerspec 
                    {
                        it_interval: timespec 
                        {
                            tv_sec: interv_tm.get_sec(),
                            tv_nsec: interv_tm.get_nsec(),
                        },
                        it_value: timespec
                        {
                            tv_sec: interv_tm.get_sec(),
                            tv_nsec: interv_tm.get_nsec(),
                        },
                    }
        }
    }
}


#[cfg(test)]
mod tests
{

    use crate::{common, timer_portable::timer::{AbsoluteTime, ModeTimeType, RelativeTime, TimerExpMode}};

    #[test]
    fn test_0() 
    {
        let ts = common::get_current_timestamp();

        let texp1 = TimerExpMode::<AbsoluteTime>::new_oneshot(AbsoluteTime::from(ts));

        assert_eq!(
            TimerExpMode::OneShot { timeout: AbsoluteTime::from(ts) },
            texp1
        );
        
    }

    #[test]
    fn test_1() 
    {
        let ts = common::get_current_timestamp();

        let texp1 = 
            TimerExpMode::<AbsoluteTime>::new_oneshot(AbsoluteTime::from(ts));

        let texp2 = 
            texp1 + RelativeTime::new_time(1, 0);

        assert_eq!(texp1 < texp2, true);
        assert_eq!(texp2 > texp1, true);
        assert_eq!(texp2 != texp1, true);
        assert_eq!(texp2 < texp1, false);
    }

    #[test]
    fn test_2() 
    {

        let texp1 = 
            TimerExpMode::<AbsoluteTime>::new_oneshot(
                unsafe {AbsoluteTime::new_time_unchecked(100, AbsoluteTime::MAX_NS)}
            );
       
        let texp2 = 
            texp1 + RelativeTime::new_time(0, 1);


        assert_eq!(texp1 < texp2, true);
        assert_eq!(texp2 > texp1, true);
        assert_eq!(texp2 != texp1, true);
        assert_eq!(texp2 < texp1, false);
    }

    #[should_panic]
    #[test]
    fn test_2_fail() 
    {
        let ts = common::get_current_timestamp();

        let texp1 = 
            TimerExpMode::<AbsoluteTime>::new_oneshot(AbsoluteTime::from(ts));

        let texp2 = 
            TimerExpMode::<AbsoluteTime>::Interval { interv_tm:  AbsoluteTime::from(ts)};

        assert_eq!(texp1 == texp2, true);
    }

    #[test]
    fn test_abstime_cmp()
    {
        let abs_time = AbsoluteTime::now();
        let abs_time_future = abs_time + RelativeTime::new_time(10, 1);
        let abs_time_past = abs_time - RelativeTime::new_time(10, 1);

        assert_eq!(abs_time < abs_time_future, true);
        assert_eq!(abs_time_future > abs_time, true);
        assert_eq!(abs_time > abs_time_past, true);
        assert_eq!(abs_time_past < abs_time, true);
        assert_eq!(abs_time_future > abs_time_past, true);
        assert_eq!(abs_time_past < abs_time_future, true);
    }

    #[test]
    fn test_abstime_new()
    {
        let abs = AbsoluteTime::new_time(1, 999_999_999).unwrap();
        assert_eq!(abs.time_nsec, 999_999_999);
        assert_eq!(abs.time_sec, 1);

        let abs = AbsoluteTime::new_time(1, 1_000_000_000).unwrap();
        assert_eq!(abs.time_nsec, 0);
        assert_eq!(abs.time_sec, 2);

        let abs = AbsoluteTime::new_time(1, 1_000_000_001).unwrap();
        assert_eq!(abs.time_nsec, 1);
        assert_eq!(abs.time_sec, 2);

        let abs = AbsoluteTime::new_time(1, 2_000_000_001).unwrap();
        assert_eq!(abs.time_nsec, 1);
        assert_eq!(abs.time_sec, 3);
    }

    #[test]
    fn test_abstime_add()
    {
        let mut abs = AbsoluteTime::new_time(1, 999_999_999).unwrap();

        abs += RelativeTime::new_time(0, 1);

        assert_eq!(abs.time_nsec, 0);
        assert_eq!(abs.time_sec, 2);

        abs += RelativeTime::new_time(1, 1);

        assert_eq!(abs.time_nsec, 1);
        assert_eq!(abs.time_sec, 3);

        abs += RelativeTime::new_time(0, 999_999_999);

        assert_eq!(abs.time_nsec, 0);
        assert_eq!(abs.time_sec, 4);

        abs -= RelativeTime::new_time(0, 999_999_999);

        assert_eq!(abs.time_nsec, 1);
        assert_eq!(abs.time_sec, 3);

        abs -= RelativeTime::new_time(0, 1);

        assert_eq!(abs.time_nsec, 0);
        assert_eq!(abs.time_sec, 3);

        abs -= RelativeTime::new_time(0, 500_000_000);

        assert_eq!(abs.time_nsec, 500_000_000);
        assert_eq!(abs.time_sec, 2);

        abs -= RelativeTime::new_time(0, 400_000_000);

        assert_eq!(abs.time_nsec, 100_000_000);
        assert_eq!(abs.time_sec, 2);

        abs -= RelativeTime::new_time(1, 200_000_000);

        assert_eq!(abs.time_nsec, 900_000_000);
        assert_eq!(abs.time_sec, 0);
    }
}