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
#![no_std]

extern crate idem;

#[cfg(feature = "libc")]
extern crate libc;

#[cfg(feature = "system-call")]
#[macro_use]
extern crate syscall;

use core::ops::*;
use idem::Zero;

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Span(i128);

impl Span {
    #[inline]
    pub fn from_ns(ns: i128) -> Self { Span(ns) }
    #[inline]
    pub fn to_ns(self) -> i128 { self.0 }

    #[cfg(feature = "libc")]
    #[inline]
    pub fn to_c_timespec(self) -> Option<::libc::timespec> {
        let b = 1_000_000_000;
        let s = (self.0 / b) as ::libc::time_t;
        if self.0 / b == s as i128 {
            Some(::libc::timespec { tv_sec: s, tv_nsec: (self.0 % b) as _ })
        } else { None }
    }
}

impl Zero for Span {
    const zero: Self = Span(0);
}

impl Add for Span {
    type Output = Self;
    #[inline]
    fn add(self, other: Self) -> Self { Span(self.0 + other.0) }
}

impl Sub for Span {
    type Output = Self;
    #[inline]
    fn sub(self, other: Self) -> Self { Span(self.0 - other.0) }
}

impl AddAssign for Span {
    #[inline]
    fn add_assign(&mut self, other: Self) { self.0 += other.0 }
}

impl SubAssign for Span {
    #[inline]
    fn sub_assign(&mut self, other: Self) { self.0 -= other.0 }
}

#[cfg(feature = "libc")]
impl From<::libc::timespec> for Span {
    #[inline]
    fn from(ts: ::libc::timespec) -> Self {
        Span(1_000_000_000*(ts.tv_sec as i128) + (ts.tv_nsec as i128))
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Point(i128);

#[cfg(feature = "posix")]
impl Point {
    #[inline]
    pub fn now() -> Self { unsafe {
        let mut ts: ::libc::timespec = ::core::mem::MaybeUninit::uninit().assume_init();
        syscall!(CLOCK_GETTIME, ::libc::CLOCK_MONOTONIC, &mut ts as *mut _);
        Point(Span::from(ts).0)
    } }

    #[inline]
    pub fn elapsed(self) -> Span { Self::now() - self }
}

impl Add<Span> for Point {
    type Output = Self;
    #[inline]
    fn add(self, other: Span) -> Self { Point(self.0 + other.0) }
}

impl Sub<Span> for Point {
    type Output = Self;
    #[inline]
    fn sub(self, other: Span) -> Self { Point(self.0 - other.0) }
}

impl Sub for Point {
    type Output = Span;
    #[inline]
    fn sub(self, other: Self) -> Span { Span(self.0 - other.0) }
}

impl AddAssign<Span> for Point {
    #[inline]
    fn add_assign(&mut self, other: Span) { self.0 += other.0 }
}

impl SubAssign<Span> for Point {
    #[inline]
    fn sub_assign(&mut self, other: Span) { self.0 -= other.0 }
}