timer_deque_rs/
common.rs

1/*-
2 * timer-deque-rs - a Rust crate which provides timer and timer queues based on target OS
3 *  functionality.
4 * 
5 * Copyright (C) 2025 Aleksandr Morozov alex@nixd.org
6 *  4neko.org alex@4neko.org
7 * 
8 * The timer-rs crate can be redistributed and/or modified
9 * under the terms of either of the following licenses:
10 *
11 *   1. the Mozilla Public License Version 2.0 (the “MPL”) OR
12 *                     
13 *   2. EUROPEAN UNION PUBLIC LICENCE v. 1.2 EUPL © the European Union 2007, 2016
14 */
15
16use std::fmt;
17
18use chrono::{DateTime, Local};
19use rand::RngCore;
20
21
22/// Returns the current [DateTime].
23pub 
24fn get_current_timestamp() -> DateTime<Local>
25{
26    return chrono::offset::Local::now();
27}
28
29/// A default struct which is provided when the timer queue does not
30/// require any input.
31#[derive(Debug, Clone, Copy, Eq, PartialEq)]
32pub struct NoTarget;
33
34impl fmt::Display for NoTarget
35{
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
37    {
38        write!(f, "no_target")
39    }
40}
41
42/// A default struct which is returned when the timer queue does
43/// issue any identification of the instance in queue.
44#[derive(Debug, Clone, Copy, Eq, PartialEq)]
45pub struct NoTicket;
46
47impl fmt::Display for NoTicket
48{
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
50    {
51        write!(f, "no_ticket")
52    }
53}
54
55
56/// A uniq ID which is generated for every ticket. It is a 128bit
57/// value which consists from timestamp sec and ns and random number.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
59pub struct TimerDequeueId
60{
61    /// seconds
62    pub(crate) timestamp: i64,
63
64    /// nanoseconds
65    pub(crate) timestamp_ns: u32,
66
67    /// random number
68    pub(crate) ran_id: u32,
69}
70
71impl fmt::Display for TimerDequeueId
72{
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result 
74    {
75        write!(f, "{:X}/{:X}/{:X}", self.timestamp, self.timestamp_ns, self.ran_id)
76    }
77}
78
79impl TimerDequeueId
80{
81    pub(crate) 
82    fn new() -> Self
83    {
84        let mut rng = rand::rng();
85
86        let ts = get_current_timestamp();
87
88        return 
89            Self
90            { 
91                timestamp: ts.timestamp(), 
92                timestamp_ns: ts.timestamp_subsec_nanos(), 
93                ran_id: rng.next_u32(), 
94            }; 
95    }
96}
97