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
// Copyright (c) 2023 Contributors to the Eclipse Foundation
//
// See the NOTICE file(s) distributed with this work for additional
// information regarding copyright ownership.
//
// This program and the accompanying materials are made available under the
// terms of the Apache Software License 2.0 which is available at
// https://www.apache.org/licenses/LICENSE-2.0, or the MIT license
// which is available at https://opensource.org/licenses/MIT.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! Contains POSIX timing related abstractions.
//!
//! * [`Time`] - acquires the current system time and measures the elapsed time
//! * [`ClockType`] - describes certain types of clocks
//! * [`nanosleep()`] & [`nanosleep_with_clock()`] - wait a defined amount of time on a custom
//!                           clock
//! * [`AsTimeval`] - trait for easy [`posix::timeval`] conversion, required for low level posix
//!                     calls
//! * [`AsTimespec`] - trait for easy [`posix::timespec`] conversion, required for low level posix
//!                     calls

use crate::system_configuration::Feature;
use crate::{config::DEFAULT_CLOCK_MODE, handle_errno};
use iceoryx2_bb_elementary::enum_gen;
use iceoryx2_bb_log::fail;
use iceoryx2_pal_posix::posix::errno::Errno;
use iceoryx2_pal_posix::*;
use std::time::Duration;

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum TimeError {
    ClockTypeIsNotSupported,
    UnknownError(i32),
}

#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
pub enum NanosleepError {
    InterruptedBySignal(Duration),
    DurationOutOfRange,
    ClockTypeIsNotSupported,
    UnknownError(i32),
}

enum_gen! {
/// Use this more generic error enum when you do not require the fine grained error handling.
/// Every error enum is convertable into this one and on a higher level this is convertable into
/// [`crate::Error`].
    ClockError
  generalization:
    TimeError <= TimeError,
    NanosleepError <= NanosleepError
}

impl From<TimeError> for NanosleepError {
    fn from(t: TimeError) -> Self {
        match t {
            TimeError::ClockTypeIsNotSupported => NanosleepError::ClockTypeIsNotSupported,
            TimeError::UnknownError(v) => NanosleepError::UnknownError(v),
        }
    }
}

/// Represents different low level clocks.
#[derive(Debug, Clone, Copy, Eq, Hash, PartialEq)]
#[repr(i32)]
pub enum ClockType {
    /// represents a steady clock which does not change when the system time
    /// is adjusted
    Monotonic = posix::CLOCK_MONOTONIC as _,
    /// Clock which represents the current system time. Can change when the  system time is
    /// adjusted.
    Realtime = posix::CLOCK_REALTIME as _,
}

impl Default for ClockType {
    fn default() -> Self {
        match DEFAULT_CLOCK_MODE {
            crate::config::ClockMode::Safety => {
                if Feature::MonotonicClock.is_available() {
                    ClockType::Monotonic
                } else {
                    ClockType::Realtime
                }
            }
            crate::config::ClockMode::Performance => ClockType::Realtime,
        }
    }
}

/// Trait to convert constructs which represent time into the c pendant [`posix::timespec`]
pub trait AsTimespec {
    fn as_timespec(&self) -> posix::timespec;
}

impl AsTimespec for Duration {
    fn as_timespec(&self) -> posix::timespec {
        posix::timespec {
            tv_sec: self.as_secs() as posix::time_t,
            tv_nsec: self.subsec_nanos() as posix::long,
        }
    }
}

/// Trait to convert constructs which represent time into the c pendant [`posix::timeval`]
pub trait AsTimeval {
    fn as_timeval(&self) -> posix::timeval;
}

impl AsTimeval for Duration {
    fn as_timeval(&self) -> posix::timeval {
        posix::timeval {
            tv_sec: self.as_secs() as _,
            tv_usec: self.subsec_micros() as _,
        }
    }
}

/// Builder for [`Time`].
///
/// # Examples
/// ```
/// use iceoryx2_bb_posix::clock::*;
/// let my_time = TimeBuilder::new().clock_type(ClockType::Realtime)
///                                 .seconds(123)
///                                 .nanoseconds(456).create();
/// ```
pub struct TimeBuilder {
    time: Time,
}

impl Default for TimeBuilder {
    fn default() -> Self {
        TimeBuilder {
            time: Time {
                clock_type: ClockType::default(),
                seconds: 0,
                nanoseconds: 0,
            },
        }
    }
}

impl TimeBuilder {
    pub fn new() -> TimeBuilder {
        Self::default()
    }

    pub fn clock_type(mut self, value: ClockType) -> Self {
        self.time.clock_type = value;
        self
    }

    pub fn seconds(mut self, value: u64) -> Self {
        self.time.seconds = value;
        self
    }

    pub fn nanoseconds(mut self, value: u32) -> Self {
        self.time.nanoseconds = value;
        self
    }

    pub fn create(self) -> Time {
        self.time
    }
}

/// Represents time under a specified [`ClockType`]
#[derive(Default, Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub struct Time {
    pub(crate) clock_type: ClockType,
    pub(crate) seconds: u64,
    pub(crate) nanoseconds: u32,
}

impl Time {
    /// Returns the current time.
    ///
    /// # Examples
    /// ```ignore
    /// use iceoryx2_bb_posix::clock::*;
    ///
    /// let now: Time = Time::now_with_clock(ClockType::Monotonic).unwrap();
    /// ```
    pub fn now_with_clock(clock_type: ClockType) -> Result<Self, TimeError> {
        let mut current_time = posix::timespec {
            tv_sec: 0,
            tv_nsec: 0,
        };

        handle_errno!(TimeError, from "Time::now",
            errno_source unsafe { posix::clock_gettime(clock_type as _, &mut current_time).into() },
            success Errno::ESUCCES => Time { clock_type,
                                             seconds: current_time.tv_sec as u64,
                                             nanoseconds: current_time.tv_nsec as u32},
            Errno::ENOSYS => (ClockTypeIsNotSupported, "Failed to get time {{ clock_type: {:?} }} since the clock is not supported.", clock_type),
            v => (UnknownError(v as i32), "Failed to get time {{ clock_type: {:?} }} since an unknown error occurred ({}).", clock_type, v)
        );
    }

    /// Returns the current time with [`ClockType::default()`]
    pub fn now() -> Result<Self, TimeError> {
        Self::now_with_clock(ClockType::default())
    }

    /// Returns the elapsed time which has passed between Time and now as [`Duration`].
    ///
    /// # Examples
    /// ```
    /// use iceoryx2_bb_posix::clock::*;
    /// use std::time::Duration;
    ///
    /// let now: Time = Time::now().unwrap();
    /// // do something
    /// let elapsed_time: Duration = now.elapsed().unwrap();
    /// ```
    pub fn elapsed(&self) -> Result<Duration, TimeError> {
        let now =
            fail!(from self, when Time::now_with_clock(self.clock_type), "Failed to acquire elapsed time")
                .as_duration();

        Ok(now - self.as_duration())
    }

    /// Returns the number of seconds
    pub fn seconds(&self) -> u64 {
        self.seconds
    }

    /// Returns the fractional part in nanoseconds
    pub fn nanoseconds(&self) -> u32 {
        self.nanoseconds
    }

    pub fn clock_type(&self) -> ClockType {
        self.clock_type
    }

    /// Converts Time into duration
    pub fn as_duration(&self) -> Duration {
        Duration::from_secs(self.seconds) + Duration::from_nanos(self.nanoseconds as u64)
    }
}

impl AsTimespec for Time {
    fn as_timespec(&self) -> posix::timespec {
        posix::timespec {
            tv_sec: self.seconds as _,
            tv_nsec: self.nanoseconds as _,
        }
    }
}

/// Suspends the current thread for a provided duration.
///
/// # Examples
/// ```
/// use iceoryx2_bb_posix::clock::*;
/// use std::time::Duration;
///
/// // sleep for 100 milliseconds
/// nanosleep(Duration::from_millis(100)).unwrap();
/// ```
pub fn nanosleep(duration: Duration) -> Result<(), NanosleepError> {
    nanosleep_with_clock(duration, ClockType::default())
}

/// Suspends the current thread for a provided duration in a user provided [`ClockType`].
///
/// # Attention
///
/// Be aware
/// that the sleep can be extended or non existing when using [`ClockType::Realtime`] and the
/// system time changes.
/// Assume you would like to wait 1 second and while being in the function the system time is
///  * moved one hour into the future, then you will not wait at all.
///  * moved one hour into the past, then you will wait for 3601 seconds
///
/// # Examples
/// ```
/// use iceoryx2_bb_posix::clock::*;
/// use std::time::Duration;
///
/// // sleep for 100 milliseconds
/// nanosleep_with_clock(Duration::from_millis(100), ClockType::Realtime).unwrap();
/// ```
pub fn nanosleep_with_clock(
    duration: Duration,
    clock_type: ClockType,
) -> Result<(), NanosleepError> {
    let wait_time = Time::now_with_clock(clock_type)?.as_duration() + duration;

    let timeout = posix::timespec {
        tv_sec: wait_time.as_secs() as posix::time_t,
        tv_nsec: wait_time.subsec_nanos() as posix::long,
    };

    let mut time_left = posix::timespec {
        tv_sec: 0,
        tv_nsec: 0,
    };

    let mut remaining_sleeping_time = Duration::ZERO;
    handle_errno!(NanosleepError, from "nanosleep_with_clock",
        errno_source unsafe {
            let e = posix::clock_nanosleep(
                clock_type as _,
                posix::CLOCK_TIMER_ABSTIME,
                &timeout,
                &mut time_left,
            ).into();

            if e == Errno::EINTR {
                remaining_sleeping_time = Duration::from_secs(time_left.tv_sec as u64)
                    + Duration::from_nanos(time_left.tv_nsec as u64);
            }
            e
        },
        success Errno::ESUCCES => (),
        Errno::EINTR => (InterruptedBySignal(remaining_sleeping_time),
            "Interrupted \"nanosleep\": {{ duration: {:?}, clock_type: {:?} }}, remaining sleeping time: {:?}", duration, clock_type, remaining_sleeping_time),
        Errno::EINVAL => (DurationOutOfRange, "Invalid argument in \"nanosleep\". Either the duration: {:?} is out of range or the clock type {:?} is invalid.", duration, clock_type),
        Errno::ENOTSUP => (ClockTypeIsNotSupported, "Clock not supported in \"nanosleep\": {{ duration: {:?}, clock_type: {:?} }}", duration, clock_type),
        v => (UnknownError(v as i32), "Unknown error occurred in \"nanosleep\": {{ duration: {:?}, clock_type: {:?} }}, ({})", duration, clock_type, v)
    );
}