Skip to main content

capsid_database/
epoch.rs

1use std::{fmt, str::FromStr};
2
3use rusqlite::{
4    ToSql,
5    types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef},
6};
7
8use crate::{Result, StoreError};
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11pub struct AuthorityEpoch(uuid::Uuid);
12
13impl AuthorityEpoch {
14    pub fn generate() -> Self {
15        Self(uuid::Uuid::new_v4())
16    }
17
18    pub fn uuid(&self) -> uuid::Uuid {
19        self.0
20    }
21}
22
23impl fmt::Display for AuthorityEpoch {
24    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
25        self.0.fmt(formatter)
26    }
27}
28
29impl FromStr for AuthorityEpoch {
30    type Err = StoreError;
31
32    fn from_str(value: &str) -> Result<Self> {
33        uuid::Uuid::parse_str(value)
34            .map(Self)
35            .map_err(StoreError::Epoch)
36    }
37}
38
39impl ToSql for AuthorityEpoch {
40    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
41        Ok(ToSqlOutput::from(self.0.to_string()))
42    }
43}
44
45impl FromSql for AuthorityEpoch {
46    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
47        uuid::Uuid::parse_str(value.as_str()?)
48            .map(Self)
49            .map_err(|error| FromSqlError::Other(Box::new(error)))
50    }
51}