|
| 1 | +use diesel::deserialize::{self, FromSql}; |
| 2 | +use diesel::pg::Pg; |
| 3 | +use diesel::serialize::{self, IsNull, Output, ToSql}; |
| 4 | +use diesel::sql_types::Text; |
| 5 | +use std::io::Write; |
| 6 | + |
| 7 | +#[derive(Clone, Copy, Debug, PartialEq, Eq, AsExpression)] |
| 8 | +#[sql_type = "Text"] |
| 9 | +pub enum EndpointScope { |
| 10 | + PublishNew, |
| 11 | + PublishUpdate, |
| 12 | + Yank, |
| 13 | + ChangeOwners, |
| 14 | +} |
| 15 | + |
| 16 | +impl From<&EndpointScope> for &[u8] { |
| 17 | + fn from(scope: &EndpointScope) -> Self { |
| 18 | + match scope { |
| 19 | + EndpointScope::PublishNew => b"publish-new", |
| 20 | + EndpointScope::PublishUpdate => b"publish-update", |
| 21 | + EndpointScope::Yank => b"yank", |
| 22 | + EndpointScope::ChangeOwners => b"change-owners", |
| 23 | + } |
| 24 | + } |
| 25 | +} |
| 26 | + |
| 27 | +impl ToSql<Text, Pg> for EndpointScope { |
| 28 | + fn to_sql<W: Write>(&self, out: &mut Output<'_, W, Pg>) -> serialize::Result { |
| 29 | + out.write_all(self.into())?; |
| 30 | + Ok(IsNull::No) |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl TryFrom<&[u8]> for EndpointScope { |
| 35 | + type Error = String; |
| 36 | + |
| 37 | + fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> { |
| 38 | + match bytes { |
| 39 | + b"publish-new" => Ok(EndpointScope::PublishNew), |
| 40 | + b"publish-update" => Ok(EndpointScope::PublishUpdate), |
| 41 | + b"yank" => Ok(EndpointScope::Yank), |
| 42 | + b"change-owners" => Ok(EndpointScope::ChangeOwners), |
| 43 | + _ => Err("Unrecognized enum variant".to_string()), |
| 44 | + } |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +impl FromSql<Text, Pg> for EndpointScope { |
| 49 | + fn from_sql(bytes: Option<&[u8]>) -> deserialize::Result<Self> { |
| 50 | + Ok(EndpointScope::try_from(not_none!(bytes))?) |
| 51 | + } |
| 52 | +} |
0 commit comments