summaryrefslogtreecommitdiffstats
path: root/store/src/backend/support.rs
blob: 5cd44ad5c368efffc7a3dae1466556434e9b9778 (plain)
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
//! Data types for working with `rusqlite`.

use rusqlite;
use rusqlite::types::{ToSql, ToSqlOutput, FromSql, FromSqlResult, ValueRef};
use std::fmt;
use std::ops::Add;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use crate::{
    Result,
};

/// Represents a row id.
///
/// This is used to represent handles to stored objects.
#[derive(Copy, Clone, PartialEq)]
pub struct ID(i64);

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

impl ID {
    /// Returns ID(0).
    ///
    /// This is smaller than all valid ids.
    pub fn null() -> Self {
        ID(0)
    }

    /// Returns the largest id.
    pub fn max() -> Self {
        ID(::std::i64::MAX)
    }
}

impl From<i64> for ID {
    fn from(id: i64) -> Self {
        ID(id)
    }
}

impl ToSql for ID {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
        Ok(ToSqlOutput::from(self.0))
    }
}

impl FromSql for ID {
    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
        value.as_i64().map(|id| id.into())
    }
}


/// A serializable system time.
///
/// XXX: Drop this.  Instead, use chrono::DateTime which implements
/// ToSql and FromSql.
#[derive(Clone, Copy, PartialEq, PartialOrd)]
pub struct Timestamp(SystemTime);

impl Timestamp {
    pub fn now() -> Self {
        Timestamp(SystemTime::now())
    }

    /// Converts to unix time.
    pub fn unix(&self) -> i64 {
        match self.0.duration_since(UNIX_EPOCH) {
            Ok(d) if d.as_secs() < std::i64::MAX as u64 =>
                d.as_secs() as i64,
            _ => 0, // Not representable.
        }
    }

    pub fn duration_since(&self, earlier: Timestamp) -> Result<Duration> {
        Ok(self.0.duration_since(earlier.0)?)
    }
}

impl ToSql for Timestamp {
    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
        Ok(ToSqlOutput::from(self.unix()))
    }
}

impl FromSql for Timestamp {
    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
        value.as_i64()
            .map(|t| Timestamp(UNIX_EPOCH + Duration::new(t as u64, 0)))
    }
}

impl Add<Duration> for Timestamp {
    type Output = Timestamp;

    fn add(self, other: Duration) -> Timestamp {
        Timestamp(self.0 + other)
    }
}