aboutsummaryrefslogtreecommitdiff
path: root/src/server/blobref.rs
blob: 7d9fa66e81de962c9643d34a6fc77203812010a2 (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
use crate::common::hash::{self, Hasher};
use rusqlite::types::{FromSql, FromSqlError};
use rusqlite::{
    types::{FromSqlResult, ToSqlOutput},
    ToSql,
};
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::path::PathBuf;
use std::str::FromStr;

#[derive(Debug)]
pub enum Error {
    InvalidHash(hash::Error),
}

type Result<T> = std::result::Result<T, Error>;

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Hash, Eq)]
pub struct BlobRef(String);

impl BlobRef {
    pub fn from_str(s: &str) -> Result<Self> {
        hash::Hash::from_str(s).map_err(Error::InvalidHash)?;
        Ok(Self(s.to_string()))
    }

    pub fn for_bytes(bytes: &[u8]) -> Self {
        let mut hasher = Hasher::default();
        hasher.update(bytes);
        BlobRef(hasher.finish().to_base32())
    }

    pub(super) fn path(&self) -> PathBuf {
        let mut buf = PathBuf::new();
        buf.push(&self.0[0..4]);
        buf.push(&self.0[4..]);

        buf
    }
}

impl Display for BlobRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "blobref:{}", self.0)
    }
}

impl ToSql for BlobRef {
    fn to_sql(&self) -> rusqlite::Result<rusqlite::types::ToSqlOutput<'_>> {
        Ok(ToSqlOutput::Borrowed(rusqlite::types::ValueRef::Text(
            self.0.as_bytes(),
        )))
    }
}

impl FromSql for BlobRef {
    fn column_result(value: rusqlite::types::ValueRef<'_>) -> FromSqlResult<Self> {
        let v: String = FromSql::column_result(value)?;
        BlobRef::from_str(&v).map_err(|_| FromSqlError::InvalidType)
    }
}