timer-deque-rs 0.8.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
/*-
 * 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
 */

/// A `consumer` type of the timer which consumes the intance and returns it when
/// timer triggers. The `consumed` instance normally whould be [Send] because it will
/// be moved into the timer which may be processed in other thread.
pub mod timer_consumer;

/// A `ticket` issuer. Issues a ticket which should be assigned to the instance whcih was added
/// to the timer's queue. The `ticket` can be used to remove the item from queue before the 
/// timeout event. If ticket is dropped i.e connection closed, the ticket will be
/// in timer's queue until timeout where it will be ignored on timeout event.
pub mod timer_tickets;

#[cfg(test)]
mod tests;

#[cfg(target_family = "unix")]
pub use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};

use std::
{
    borrow::Cow, 
    collections::VecDeque, 
    fmt, 
    marker::PhantomData, 
};


use crate::
{
    TimerDequeConsumer, 
    TimerDequeTicket, 
    TimerDequeTicketIssuer, 
    error::{TimerErrorType, TimerResult}, 
    map_timer_err, 
    timer_err, 
    timer_portable::
    {
        AsTimerId, FdTimerMarker, PollEventType, TimerFd, TimerFlags, TimerId, TimerType, UnixFd, portable_error::TimerPortResult, timer::
        {
            AbsoluteTime, FdTimerCom, FdTimerRead, RelativeTime, TimerExpMode, 
            TimerReadRes
        }
    }
};


/// A trait which is implemented by the structs which define the operation mode of the deque.
/// 
/// At the moment for: [DequeOnce] and [DequePeriodic].
pub trait OrderedTimerDequeMode: fmt::Debug + fmt::Display + Ord + PartialOrd + Eq + PartialEq
{
    /// A type of operation. If the item deques once, then this value should be
    /// `true`. Otherwise, it is periodic.
    const IS_ONCE: bool;

    /// Checks the current instance against the provided `cmp` [AbsoluteTime].
    /// It is expected that the current instance's timeout value is actual and 
    /// haven't outlive the `cmp` already. if it does the error:
    /// [TimerErrorType::Expired] should be returned. Or any other error
    /// if it is required.
    fn validate_time(&self, cmp: AbsoluteTime) -> TimerResult<()>;
    
    /// Returns the `absolute` timeout for the instance of the deque.
    fn get_absolut_timeout(&self) -> AbsoluteTime;

    /// Postpones the time by the relative offset `post_time`. May return error
    /// (if required) if the absolut timeout value overflows.
    /// 
    /// May return [TimerErrorType::TicketInstanceGone] if ticket was invalidated.
    fn postpone(&mut self, posp_time: RelativeTime) -> TimerResult<()>;

    /// Updates the timeout when the deque works in periodic mode. By fedault
    /// it does nothing.
    fn advance_timeout(&mut self)
    {
        return;
    }
}

/// This queue mode removes all entries from the queue that have timed out.
/// 
/// The further behaviour is defined by the type of the deque.
#[derive(Debug, Clone, Copy)]
pub struct DequeOnce 
{
    /// A timeout for the item in the queue.
    absolute_timeout: AbsoluteTime,
}

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

impl Ord for DequeOnce
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering 
    {
        return self.absolute_timeout.cmp(&other.absolute_timeout);
    }
}

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

impl Eq for DequeOnce {}

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


impl OrderedTimerDequeMode for DequeOnce
{
    const IS_ONCE: bool = true;

    fn get_absolut_timeout(&self) -> AbsoluteTime
    {
        return self.absolute_timeout;
    }
    
    fn validate_time(&self, cmp: AbsoluteTime) -> TimerResult<()> 
    {
        if cmp > self.absolute_timeout
        {
            timer_err!(TimerErrorType::Expired, 
                "deque once time already expired, now: {}, req: {}", cmp, self);
        }

        return Ok(());
    }
    
    fn postpone(&mut self, posp_time: RelativeTime) -> TimerResult<()> 
    {
        self.absolute_timeout = self.absolute_timeout + posp_time;

        return Ok(());
    }
}


impl DequeOnce
{
    /// Creates new instacne.
    #[inline]
    pub
    fn new(absolute_timeout: impl Into<AbsoluteTime>) -> Self
    {
        return Self{ absolute_timeout: absolute_timeout.into() };
    }
}

/// This queue mode does not remove an element that has timed out (by `absolute_timeout`), 
/// but extends (by `relative_period`) the timeout and returns the element back to the queue.
#[derive(Debug, Clone, Copy)]
pub struct DequePeriodic 
{
    /// Extends the timer until the next timeout. This is `relative`
    /// not absolute.
    relative_period: RelativeTime,

    /// A timeout value.
    absolute_timeout: AbsoluteTime,
}

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

impl Ord for DequePeriodic
{
    fn cmp(&self, other: &Self) -> std::cmp::Ordering 
    {
        return self.absolute_timeout.cmp(&other.absolute_timeout);
    }
}

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

impl Eq for DequePeriodic {}

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


impl OrderedTimerDequeMode for DequePeriodic
{
    const IS_ONCE: bool = false;

    fn get_absolut_timeout(&self) -> AbsoluteTime
    {
        return self.absolute_timeout;
    }

    fn advance_timeout(&mut self)
    {
        self.absolute_timeout += self.relative_period;
    }

    fn validate_time(&self, cmp: AbsoluteTime) -> TimerResult<()> 
    {
        if cmp > self.absolute_timeout
        {
            timer_err!(TimerErrorType::Expired, 
                "deque periodic absolute time already expired, now: {}, req: {}", cmp, self.absolute_timeout);
        }
        else if self.relative_period.is_zero() == false
        {
            timer_err!(TimerErrorType::ZeroRelativeTime, 
                "deque periodic relative time is 0, rel_time: {}", self.relative_period);
        }

        return Ok(());
    }
    
    fn postpone(&mut self, posp_time: RelativeTime) -> TimerResult<()> 
    {
        self.absolute_timeout = self.absolute_timeout - self.relative_period + posp_time;

        self.relative_period = posp_time;

        return Ok(());
    }
}

impl DequePeriodic
{
    /// Creates new instance. The `relative_time` is not added to
    /// `absolute_time` until timeout. The values are unchecked at this
    /// point and will be checked during placement in queue.
    pub
    fn new_from_now(rel_time: impl Into<RelativeTime>) -> Self
    {
        let inst = 
            Self
            {
                relative_period:
                    rel_time.into(),
                absolute_timeout: 
                    AbsoluteTime::now(),
            };

        return inst;
    }

    /// Creates new instance with the initial timeout `abs_time` and
    /// period `rel_time` which is added to the `abs_time` each time
    /// the timeout occures. The values are unchecked at this
    /// point and will be checked during placement in queue.
    pub
    fn new(abs_time: impl Into<AbsoluteTime>, rel_time: impl Into<RelativeTime>) -> Self
    {
        let inst = 
            Self
            {
                relative_period:
                    rel_time.into(),
                absolute_timeout: 
                    abs_time.into(),
            };

        return inst;
    }
}

/// A trait for the generalization of the collection type which is used to 
/// collect the timeout values i.e ticket IDs.
pub trait TimerTimeoutCollection<ITEM: PartialEq + Eq + fmt::Display + fmt::Debug>
{
    /// Initializes the instance.
    fn new() -> Self;

    /// Store the `ITEM` in the collection.
    fn push(&mut self, item: ITEM);

    /// Wraps the instance into [Option]. If collection is `empty` a
    /// [Option::None] should be returned.
    fn into_option(self) -> Option<Self> where Self: Sized;
}

/// An implementation for the Vec.
impl<ITEM: PartialEq + Eq + fmt::Display + fmt::Debug> TimerTimeoutCollection<ITEM> 
for Vec<ITEM>
{
    fn new() -> Self
    {
        return Vec::new();
    }

    fn push(&mut self, item: ITEM) 
    {
        self.push(item);
    }

    fn into_option(self) -> Option<Self>
    {
        if self.is_empty() == false
        {
            return Some(self);
        }
        else
        {
            return None;
        }
    }
}

/// A dummy implementation when nothing is returned. Unused at the moment.
impl <ITEM: PartialEq + Eq + fmt::Display + fmt::Debug> TimerTimeoutCollection<ITEM> 
for ()
{
    fn new() -> Self
    {
        return ();
    }

    fn push(&mut self, _item: ITEM) 
    {
        return;    
    }

    fn into_option(self) -> Option<Self>
    {
        return None;
    }
}

/// A standart interface for each deque type. Every deque type must implement this 
/// trait.
pub trait OrderedTimerDequeHandle<MODE: OrderedTimerDequeMode>
    : Ord + PartialOrd + PartialEq + PartialEq<Self::TimerId> + Eq + fmt::Debug + 
        fmt::Display + OrderedTimerDequeInterf<MODE>
{
    /// A timer ID. Normally this is a uniq identificator of the item in the queue. 
    /// i.e `TimerDequeId`.
    type TimerId: PartialEq + Eq + fmt::Display + fmt::Debug;

    /// A collection which is used to collect the items which are removed from
    /// the queue due to timeout.
    type HandleRes: TimerTimeoutCollection<Self::TimerId>;

    /// Postpones the timeout of the current instance. The `postp_time` is a [RelativeTime] 
    /// i.e inroduces the offset.
    fn postpone(&mut self, postp_time: RelativeTime) -> TimerResult<()>;

    /// Reschedules the current instance. This is different from the `postpone` as the
    /// instance is assagned with a new time. The `MODE` cannot be changed, only time.
    fn resched(&mut self, time: MODE) -> TimerResult<()>;

    /// A spefic code which is called during timeout routine handling. Normally is should 
    /// store the result into the `collection` and reschedule the item if it is repeated.
    fn handle(self, timer_self: &mut OrderTimerDeque<MODE, Self>, 
        timer_ids: &mut Self::HandleRes) -> TimerResult<()>
    where Self: Sized;

    /// Matches the current instance with provided `other` instances 
    /// [OrderedTimerDequeHandle::TimerId]. But, the `PartialEq<Self::TimerId>` is 
    /// implemented, so the `==` can be used to compare.
    fn is_same(&self, other: &Self::TimerId) -> bool;

    /// Attempts to acquire the [OrderedTimerDequeHandle::TimerId] by consuming the instance.
    fn into_timer_id(self) -> Option<Self::TimerId>;
}

/// A trait which is used by the base [OrderTimerDeque]. 
/// This is an interface which provides access to the timeout value of the instance.
pub trait OrderedTimerDequeInterf<MODE: OrderedTimerDequeMode>
{
    /// Returns the absolute time and the timer mode.
    fn get_timeout_absolute(&self) -> AbsoluteTime;
}


/// A [VecDeque] based queue which is sorted (in ascending order) by the timeout 
/// which is `absolute` time.
/// 
/// The queue automatically manages the `timer` i.e setting, unsetting.
/// 
/// Also for each type of the deque, a event procesing function is providided.
/// 
/// There are two types of queue:
/// 
/// * [OrderdTimerDequeOnce] - after timeout the element is removed from the queue.
/// 
/// * [OrderdTimerDequePeriodic] - after timeout the element timeout is extended
///     until the item is not removed from the queue manually.
/// 
/// And there are 3 types of queue models:
/// 
/// * [`crate::TimerDequeConsumer`] - consumes the item which is stored in the 
///     timeout queue.
/// 
/// * [`crate::TimerDequeTicketIssuer`] - issues a ticket which is referenced 
///     to the item in the queue.
/// 
/// * [`crate::TimerDequeSignalTicket`] - send signal on timeout using `MPSC`
/// 
/// # Implementations
/// 
/// If `feature = enable_mio_compat` is enabled a [mio::event::Source] is 
/// implemented on the current struct.
/// 
/// ## Multithread
/// 
/// Not MT-safe. The external mutex should be used to protect the instance. 
/// The internal `timer` [TimerFd] is MT-safe.
/// 
/// ## Poll
/// 
/// - A built-in [crate::TimerPoll] can be used.
/// 
/// - An external crate MIO [crate::TimerFdMioCompat] if `feature = enable_mio_compat` is
/// enabled.
/// 
/// - User implemented poll. The FD can be aquired via [AsRawFd] [AsFd].
/// 
/// ## Async
/// 
/// A [Future] is implemented.
/// # Generics
/// 
/// * `DQI` - a deque type. There are three types are available:
///     * - [crate::TimerDequeueTicketIssuer] issues a ticket for the instance for which the timer was set.
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeTicketIssuer<OrderdTimerDequeOnce>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ```  
///     or
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeTicketIssuer<OrderdTimerDequePeriodic>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ```     
///     * - [crate::TimerDequeueConsumer] consumes the instance for which the timer is set.
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeConsumer<TestItem, OrderdTimerDequeOnce>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ```  
///     or
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeConsumer<TestItem, OrderdTimerDequePeriodic>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ``` 
///     * - [crate::TimerDequeueSignalTicket] sends a signal to destination.
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeSignalTicket<TestSigStruct, OrderdTimerDequeOnce>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ```
///     or
///     ```ignore
///         let mut time_list = 
///             OrderedTimerDeque
///                 ::<TimerDequeSignalTicket<TestSigStruct, OrderdTimerDequePeriodic>>
///                 ::new("test_label".into(), 4, false).unwrap();
///     ```
#[derive(Debug, Eq)]
pub struct OrderTimerDeque<MODE: OrderedTimerDequeMode, INTF: OrderedTimerDequeHandle<MODE>>
{
    /// A [VecDeque] list which is sorted by time in ascending order -
    /// lower first, largest last
    pub(crate) deque_timeout_list: VecDeque<INTF>,

    /// An instance of the FFI (Kernel Supported Timer)
    pub(crate) timer: TimerFd,

    p: PhantomData<MODE>
}

#[cfg(all(target_family = "unix", feature = "enable_mio_compat"))]
pub mod mio_compat
{
    use std::{io, os::fd::{AsRawFd, RawFd}};

    use mio::{Token, unix::SourceFd};

    use crate::{TimerFdMioCompat, deque_timeout::{OrderTimerDeque, OrderedTimerDequeHandle, OrderedTimerDequeMode}};

    impl<MODE, INTF> mio::event::Source for OrderTimerDeque<MODE, INTF>
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn register(
            &mut self,
            registry: &mio::Registry,
            token: mio::Token,
            interests: mio::Interest,
        ) -> io::Result<()> 
        {
            return 
                SourceFd(&self.as_raw_fd()).register(registry, token, interests);
        }

        fn reregister(
            &mut self,
            registry: &mio::Registry,
            token: mio::Token,
            interests: mio::Interest,
        ) -> io::Result<()> 
        {
            return 
                SourceFd(&self.as_raw_fd()).reregister(registry, token, interests);
        }

        fn deregister(&mut self, registry: &mio::Registry) -> io::Result<()> 
        {
            return 
                SourceFd(&self.as_raw_fd()).deregister(registry)
        }
    }

    impl<MODE, INTF> PartialEq<Token> for OrderTimerDeque<MODE, INTF>
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn eq(&self, other: &Token) -> bool 
        {
            return self.as_raw_fd() == other.0 as RawFd;
        }
    }

    impl<MODE, INTF> TimerFdMioCompat for OrderTimerDeque<MODE, INTF>
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn get_token(&self) -> Token
        {
            return Token(self.as_raw_fd() as usize);
        }
    }
}

impl<MODE, INTF> UnixFd for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{

}

impl<MODE, INTF> AsTimerId for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn as_timer_id(&self) -> TimerId 
    {
        return self.timer.as_timer_id();
    }
}

impl<MODE, INTF> FdTimerRead for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn read(&self) -> TimerPortResult<TimerReadRes<u64>> 
    {
        return self.timer.read();
    }
}

impl<MODE, INTF> PartialEq<str> for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn eq(&self, other: &str) -> bool 
    {
        return self.timer.as_ref() == other;
    }
}


impl<MODE, INTF> FdTimerMarker for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn clone_timer(&self) -> TimerFd 
    {
        return self.timer.clone_timer();
    }

    fn get_strong_count(&self) -> usize 
    {
        return self.timer.get_strong_count();
    }
}

impl<MODE, INTF> Drop for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn drop(&mut self) 
    {
        let _ = self.clean_up_timer();
    }
}

impl<MODE, INTF> AsRef<str> for OrderTimerDeque<MODE, INTF>
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn as_ref(&self) -> &str 
    {
        return self.timer.as_ref();
    }
}

#[cfg(target_family = "unix")]
pub mod deque_timeout_os
{
    use super::*;

    impl<MODE, INTF> AsFd for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn as_fd(&self) -> BorrowedFd<'_> 
        {
            return self.timer.as_fd();
        }
    }

    impl<MODE, INTF> AsRawFd for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn as_raw_fd(&self) -> RawFd 
        {
            return self.timer.as_raw_fd();
        }
    }

    impl<MODE, INTF> PartialEq<RawFd> for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn eq(&self, other: &RawFd) -> bool 
        {
            return self.timer == *other;
        }
    }
}

#[cfg(target_family = "windows")]
pub mod deque_timeout_os
{
    use std::os::windows::io::{AsHandle, AsRawHandle, BorrowedHandle, RawHandle};

    use super::*;
    
    impl<MODE, INTF> AsHandle for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn as_handle(&self) -> BorrowedHandle<'_> 
        {
            return self.timer.as_handle();
        }
    }

    impl<MODE, INTF> AsRawHandle for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn as_raw_handle(&self) -> RawHandle 
        {
            return self.timer.as_raw_handle();
        }
    }

    impl<MODE, INTF> PartialEq<RawHandle> for OrderTimerDeque<MODE, INTF> 
    where 
        MODE: OrderedTimerDequeMode, 
        INTF: OrderedTimerDequeHandle<MODE>
    {
        fn eq(&self, other: &RawHandle) -> bool 
        {
            return self.timer == *other;
        }
}
}

impl<MODE, INTF> fmt::Display for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
    {
        write!(f, "timer: '{}', fd: '{}', queue_len: '{}'", 
            self.timer, self.timer.as_timer_id(), self.deque_timeout_list.len())
    }
}

impl<MODE, INTF> PartialEq for OrderTimerDeque<MODE, INTF> 
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    fn eq(&self, other: &Self) -> bool 
    {
        return self.timer == other.timer;
    }
}



impl<MODE, R> OrderTimerDeque<MODE, TimerDequeConsumer<R, MODE>> 
where 
    MODE: OrderedTimerDequeMode,
    R: PartialEq + Eq + fmt::Debug + fmt::Display + Send + Clone
{
    /// Adds the new absolute timeout to the timer deque instance.
    /// 
    /// The `entity` is an item which should be stored in the deque
    /// amd on timeout - returned.
    /// 
    /// # Generics
    /// 
    /// * `MODE` - is any type which implements the [OrderedTimerDequeMode].
    ///   There are two options: [DequeOnce] and [DequePeriodic].
    /// 
    /// # Arguemnts
    /// 
    /// * `item` - `R` which is an item to store in the deque.
    /// 
    /// * `mode` - `MODE` a timeout value which also defines the
    ///  behaviour of the deque logic. 
    /// 
    /// # Returns
    /// 
    /// A [Result] as alias [TimerResult] is returned with:
    /// 
    /// * [Result::Ok] with the [common::NoTicket] ticket which is dummy value.
    /// 
    /// * [Result::Err] with error description.
    /// 
    /// Possible errors: 
    ///     
    /// * [TimerErrorType::Expired] - `mode` contains time which have alrealy expired.
    /// 
    /// * [TimerErrorType::ZeroRelativeTime] - `mode` [DequePeriodic] relative time 
    ///     should never be zero.
    /// 
    /// * [TimerErrorType::TimerError] - a error with the OS timer. Contains subcode
    ///     `errno`.
    pub 
    fn add(&mut self, item: R, mode: MODE) -> TimerResult<()>
    {
        let inst = 
            TimerDequeConsumer::<R, MODE>::new(item, mode)?;

        //return self.queue_item(inst)
        let res = self.queue_item(inst);
        return res;
    }
}


impl<MODE> OrderTimerDeque<MODE, TimerDequeTicketIssuer<MODE>> 
where 
    MODE: OrderedTimerDequeMode
{
    /// Adds the new absolute timeout to the timer deque instance.
    /// 
    /// This deque assigns the `ticket` for each timeout which is
    /// used for identification and invalidation.
    /// 
    /// # Generics
    /// 
    /// * `MODE` - is any type which implements the [OrderedTimerDequeMode].
    ///   There are two options: [DequeOnce] and [DequePeriodic].
    /// 
    /// # Arguemnts
    /// 
    /// * `mode` - `MODE` a timeout value which also defines the
    ///  behaviour of the deque logic. 
    /// 
    /// # Returns
    /// 
    /// A [Result] as alias [TimerResult] is returned with:
    /// 
    /// * [Result::Ok] with the [common::NoTicket] ticket which is dummy value.
    /// 
    /// * [Result::Err] with error description.
    /// 
    /// Possible errors: 
    ///     
    /// * [TimerErrorType::Expired] - `mode` contains time which have alrealy expired.
    /// 
    /// * [TimerErrorType::ZeroRelativeTime] - `mode` [DequePeriodic] relative time 
    ///     should never be zero.
    /// 
    /// * [TimerErrorType::TimerError] - a error with the OS timer. Contains subcode
    ///     `errno`.
    pub 
    fn add(&mut self, mode: MODE) -> TimerResult<TimerDequeTicket>
    {
        let (inst, ticket) = 
            TimerDequeTicketIssuer::<MODE>::new(mode)?;

        self.queue_item(inst)?;

        return Ok(ticket);
    }
}

impl<MODE, INTF> OrderTimerDeque<MODE, INTF>  
where 
    MODE: OrderedTimerDequeMode, 
    INTF: OrderedTimerDequeHandle<MODE>
{
    /// Creates new deque instance with the provided parameters.
    /// 
    /// # Argument
    /// 
    /// * `timer_label` - a label which helps to identify the timer.
    /// 
    /// * `deq_len` - a minimal, pre-allocated deque length.
    /// 
    /// * `cloexec` - when set to `true` sets the `CLOEXEC` flag on FD.
    /// 
    /// * `non_blocking` - when set to `true` sets the `TFD_NONBLOCK` flag on FD.
    /// 
    /// # Returns
    /// 
    /// A [Result] as alias [TimerResult] is returned with
    /// 
    /// * [Result::Ok] with the instance.
    /// 
    /// * [Result::Err] with the error description.
    /// 
    /// The following errors may be returned:
    ///     
    /// * [TimerErrorType::TimerError] - error in the OS timer. A `errno` subcode is provided.
    pub 
    fn new(timer_label: Cow<'static, str>, deq_len: usize, cloexec: bool, non_blocking: bool) -> TimerResult<OrderTimerDeque<MODE, INTF>>
    {
        let deq_len = 
            if deq_len == 0
            {
                10
            }
            else
            {
                deq_len
            };

        let mut tf = TimerFlags::empty();

        tf.set(TimerFlags::TFD_CLOEXEC, cloexec);
        tf.set(TimerFlags::TFD_NONBLOCK, non_blocking);

        // init timer
        let timer = 
            TimerFd::new(timer_label, TimerType::CLOCK_REALTIME, tf)
                .map_err(|e|
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                )?;

        return Ok( 
            Self
            { 
                deque_timeout_list: VecDeque::with_capacity(deq_len), 
                timer: timer,
                p: PhantomData,
            } 
        );
    }

    /// internal function which is called from the `add()` functions.
    pub(super)  
    fn queue_item(&mut self, inst: INTF) -> TimerResult<()>
    {
        if self.deque_timeout_list.len() == 0
        {
            let timer_stamp = 
                TimerExpMode::<AbsoluteTime>::new_oneshot(inst.get_timeout_absolute());

            // setup timer
            self
                .timer
                .get_timer()
                .set_time(timer_stamp)
                .map_err(|e|
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                )?;

            self.deque_timeout_list.push_front(inst);      
        }
        else
        {
            // list can not be empty from this point
            let front_timeout = 
                self.deque_timeout_list.front().unwrap().get_timeout_absolute();

            // intances timeout
            let inst_timeout = inst.get_timeout_absolute();

            if front_timeout >= inst_timeout
            {
                // push to front
                self.deque_timeout_list.push_front(inst);

                self.reschedule_timer()?;
            }
            else 
            {
                let back_banuntil = 
                    self
                        .deque_timeout_list
                        .back()
                        .unwrap()
                        .get_timeout_absolute();

                if back_banuntil <= inst_timeout
                {
                    // push to the back
                    self.deque_timeout_list.push_back(inst);
                }
                else
                {
                    let pos = 
                        self
                            .deque_timeout_list
                            .binary_search_by( |se| 
                                se.get_timeout_absolute().cmp(&inst.get_timeout_absolute())
                            )
                            .map_or_else(|e| e, |r| r);

                    self.deque_timeout_list.insert(pos, inst);
                }
            }
        }

        return Ok(());
    }

    /// Removes the instance from the queue by the identification depending on the
    /// deque type.
    /// 
    /// # Arguments
    /// 
    /// `item` - identification of the item which should be removed from the queue.
    /// 
    /// # Returns
    /// 
    /// A [Result] as alias [TimerResult] is returned with:
    /// 
    /// * [Result::Ok] with the inner type [Option] where
    ///     * [Option::Some] is returned with the consumed `item`.
    ///     * [Option::None] is returned when item was not found.
    /// 
    /// * [Result::Err] with error description.
    /// 
    /// The following errors may be returned:
    ///     
    /// * [TimerErrorType::TimerError] - error in the OS timer. A `errno` subcode is provided.
    pub 
    fn remove_from_queue(&mut self, item: &INTF::TimerId) -> TimerResult<Option<INTF::TimerId>>
    {
        return 
            self
                .remove_from_queue_int(item)
                .map(|opt_intf|
                    {
                        let Some(intf) = opt_intf
                        else { return None };

                        return intf.into_timer_id();
                    }
                );
                
    }
    
    pub(super)  
    fn remove_from_queue_int(&mut self, item: &INTF::TimerId) -> TimerResult<Option<INTF>>
    {
        if self.deque_timeout_list.len() == 0
        {
            timer_err!(TimerErrorType::QueueEmpty, "queue list is empty!");
        }
        else
        {
            // search for the item in list
            if self.deque_timeout_list.len() == 1
            {
                // just pop the from the front
                let ret_ent = self.deque_timeout_list.pop_front().unwrap();

                if &ret_ent != item
                {
                    self.deque_timeout_list.push_front(ret_ent);

                    return Ok(None);
                }

                // stop timer
                self.stop_timer()?;

                return Ok(Some(ret_ent));
            }
            else
            {
                // in theory the `ticket` is a reference to ARC, so the weak should be upgraded 
                // succesfully for temoved instance.

                for (pos, q_item) 
                in self.deque_timeout_list.iter().enumerate()
                {
                    if q_item == item
                    {
                        // remove by the index
                        let ret_ent = 
                            self.deque_timeout_list.remove(pos).unwrap();

                        // call timer reset if index is 0 (front)
                        if pos == 0 
                        {
                            self.reschedule_timer()?;
                        }

                        return Ok(Some(ret_ent));
                    }
                }

                return Ok(None);
            }
        }
    }

    /// Reads the timer's FD to retrive the event type and then calling 
    /// the event handler. Then the result is returned. The result may 
    /// contain the `items` which were removed from the queue or copied.
    /// 
    /// This function behaves differently when the timer is initialized as
    /// a `non-blocking` i.e with [TimerFlags::TFD_NONBLOCK].
    /// 
    /// When [TimerFlags::TFD_NONBLOCK] is not set, this function will block reading the FD.
    /// In case of 'EINTR', the read attempt will be repeated. 
    /// 
    /// When [TimerFlags::TFD_NONBLOCK] is set, the function will return with some result 
    /// immidiatly.
    /// 
    /// # Return
    /// 
    /// * In case of `EAGAIN`, the [TimerReadRes::WouldBlock] will be returned. 
    /// 
    /// * In case of `ECANCELLD`, the [TimerReadRes::Cancelled] will be returned.
    /// 
    /// * In case of any other error the [Result::Err] is returned.
    /// 
    /// When a timer fires an event the [Result::Ok] is returned with the amount of
    /// timer overrun. Normally it is 1.
    pub 
    fn wait_for_event_and_process(&mut self) -> TimerResult<Option<INTF::HandleRes>>
    {
        let res = 
            self
                .timer
                .read()
                .map_err(|e|
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                )?;


        // ignore wouldblock
        if let TimerReadRes::WouldBlock = res
        {
            return Ok(None);
        }

        return Ok(self.internal_handle_timer_event()?);
    }

    /// Handles the single event received from the `poll` and
    /// returns the result. The result may 
    /// contain the `items` which were removed from the queue or copied.  
    /// 
    /// # Arguments
    /// 
    /// `pet` - [PollEventType] an event from the timer to handle.
    /// 
    /// A [Result] as alias [TimerResult] is returned with:
    /// 
    /// * [Result::Ok] witout any innder data.
    /// 
    /// * [Result::Err] with error description.
    pub 
    fn handle_timer_event(&mut self, pet: PollEventType) -> TimerResult<Option<INTF::HandleRes>>
    {
        match pet
        {
            PollEventType::TimerRes(_, res) => 
            {
                // ignore wouldblock
                if let TimerReadRes::WouldBlock = res
                {
                    return Ok(None);
                }

                return self.internal_handle_timer_event();
            },
            PollEventType::SubError(_, err) => 
            {
                timer_err!(TimerErrorType::TimerError(err.get_errno()), "{}", err)
            }
        }
        
    }

    fn internal_handle_timer_event(&mut self) -> TimerResult<Option<INTF::HandleRes>>
    {
        let cur_timestamp = AbsoluteTime::now();
        let mut timer_ids: INTF::HandleRes = INTF::HandleRes::new();

        loop 
        {
            // get from front of the queue
            let Some(front_entity) = self.deque_timeout_list.front() 
                else { break };

            let time_until = front_entity.get_timeout_absolute();

            if time_until <= cur_timestamp
            {
                let deq = self.deque_timeout_list.pop_front().unwrap();

                deq.handle(self, &mut timer_ids)?;
            }
            else
            {
                break;
            }
        }

        // call timer reschedule
        self.reschedule_timer()?;

        return Ok(timer_ids.into_option());
    }

    /// Asynchronious polling. The timer's FD is set to nonblocking,
    /// so each time it will return `pending` and load CPU. If you are using
    /// `tokio` or `smol` or other crate, the corresponding helpers like 
    /// tokio's `AsyncFd` can be used to wrap the instance. The timer is read-only
    /// so use `read-only interest` to avoid errors.
    /// 
    /// If [TimerReadRes::WouldBlock] is received then returns immidiatly.
    pub async
    fn async_poll_for_event_and_process(&mut self) -> TimerResult<Option<INTF::HandleRes>>
    {
        let res =  
            self
                .timer
                .get_timer()
                .await
                .map_err(|e|
                    map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                )?;

        // ignore wouldblock
        if let TimerReadRes::WouldBlock = res
        {
            return Ok(None);
        }

        return Ok(self.internal_handle_timer_event()?);
    }

    /// Returns the queue length.
    pub 
    fn timer_queue_len(&self) -> usize
    {
        return self.deque_timeout_list.len();
    }
    
    /// Postpones the instace `target` by the relative time `rel_time_off`.
    /// 
    /// # Errors
    /// 
    /// * [TimerErrorType::NotFound] - if instance `target` was not found.
    /// 
    /// * [TimerErrorType::TicketInstanceGone] - if ticket was invalidated.
    /// 
    /// * [TimerErrorType::TimerError] - with the suberror code.
    pub 
    fn postpone(&mut self, target: &INTF::TimerId, rel_time_off: RelativeTime) -> TimerResult<()>
    {
        let mut item = 
            self
                .remove_from_queue_int(target)?
                .ok_or(map_timer_err!(TimerErrorType::NotFound, "ticket: {} not found", target))?;

        
        item.postpone(rel_time_off)?;

        self.queue_item(item)?;

        return Ok(()); 
    }

    /// Reschedules the instace `target` by assigning new time `time` 
    /// which is of type `MODE`.
    /// 
    /// # Errors
    /// 
    /// * [TimerErrorType::NotFound] - if instance `target` was not found.
    /// 
    /// * [TimerErrorType::TicketInstanceGone] - if ticket was invalidated.
    /// 
    /// * [TimerErrorType::TimerError] - with the suberror code.
    /// 
    /// * [TimerErrorType::Expired] - if provided `time` have passed.
    pub 
    fn reschedule(&mut self, target: &INTF::TimerId, time: MODE) -> TimerResult<()>
    {
        let mut item = 
            self.remove_from_queue_int(target)?
                .ok_or(map_timer_err!(TimerErrorType::NotFound, "{} not found", target))?;

        
        item.resched(time)?;

        self.queue_item(item)?;

        return Ok(()); 
    }

    /// Starts the `timer` instance by setting timeout or stops the `timer` if the
    /// instnce's `queue` is empty.
    pub(super)   
    fn reschedule_timer(&mut self) -> TimerResult<()>
    {
        if let Some(front_entity) = self.deque_timeout_list.front()
        {
            let timer_exp = 
                TimerExpMode::<AbsoluteTime>::new_oneshot(front_entity.get_timeout_absolute());

            return
                self
                    .timer
                    .get_timer()
                    .set_time(timer_exp)
                    .map_err(|e|
                        map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                    );
        }
        else
        {
            // queue is empty, force timer to stop

            return 
                self
                    .timer
                    .get_timer()
                    .unset_time()
                    .map_err(|e|
                        map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e)
                    );
        }
    }

    /// Unarms timer and clears the queue.
    pub 
    fn clean_up_timer(&mut self) -> TimerResult<()>
    {
        self
            .timer
            .get_timer()
            .unset_time()
            .map_err(|e| map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e))?;

        self.deque_timeout_list.clear();

        return Ok(());
    }

    /// Unarms timer only.
    pub 
    fn stop_timer(&mut self) -> TimerResult<()>
    {
        return 
            self
                .timer
                .get_timer()
                .unset_time()
                .map_err(|e| map_timer_err!(TimerErrorType::TimerError(e.get_errno()), "{}", e));
    }

}