siteslib/enums/
content_type.rs

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
use diesel::backend::Backend;
use diesel::deserialize::FromSql;
use diesel::pg::Pg;
use diesel::serialize::{IsNull, Output, ToSql};
use diesel::sql_types::Varchar;
use diesel::{deserialize, not_none, serialize};
use serde::Deserialize;
use serde::Serialize;
use std::io::Write;

#[derive(Debug, PartialEq, FromSqlRow, AsExpression, Clone, Serialize, Deserialize)]
#[sql_type = "Varchar"]
pub enum ContentType {
    Video,
    Image,
    Text,
    HTML,
}

impl ToSql<Varchar, Pg> for ContentType {
    fn to_sql<W: Write>(&self, out: &mut Output<W, Pg>) -> serialize::Result {
        match *self {
            ContentType::Video => out.write_all(b"Video")?,
            ContentType::Image => out.write_all(b"Image")?,
            ContentType::Text => out.write_all(b"Text")?,
            ContentType::HTML => out.write_all(b"HTML")?,
        }
        Ok(IsNull::No)
    }
}

impl FromSql<Varchar, Pg> for ContentType {
    fn from_sql(bytes: Option<&<Pg as Backend>::RawValue>) -> deserialize::Result<Self> {
        match not_none!(bytes) {
            b"Video" => Ok(ContentType::Video),
            b"Image" => Ok(ContentType::Image),
            b"Text" => Ok(ContentType::Text),
            b"HTML" => Ok(ContentType::HTML),
            _ => Err("Unrecognized enum variant".into()),
        }
    }
}