| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
macro_rules! impl_str_enum { |
| 11 |
($enum_name:ident { $($variant:ident => $str:literal),+ $(,)? }) => { |
| 12 |
impl std::fmt::Display for $enum_name { |
| 13 |
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 14 |
let s = match self { |
| 15 |
$( Self::$variant => $str, )+ |
| 16 |
}; |
| 17 |
f.write_str(s) |
| 18 |
} |
| 19 |
} |
| 20 |
|
| 21 |
impl std::str::FromStr for $enum_name { |
| 22 |
type Err = String; |
| 23 |
|
| 24 |
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> { |
| 25 |
match s { |
| 26 |
$( $str => Ok(Self::$variant), )+ |
| 27 |
other => Err(format!("invalid {}: {other}", stringify!($enum_name))), |
| 28 |
} |
| 29 |
} |
| 30 |
} |
| 31 |
|
| 32 |
|
| 33 |
impl sqlx::Type<sqlx::Postgres> for $enum_name { |
| 34 |
fn type_info() -> sqlx::postgres::PgTypeInfo { |
| 35 |
<String as sqlx::Type<sqlx::Postgres>>::type_info() |
| 36 |
} |
| 37 |
|
| 38 |
fn compatible(ty: &sqlx::postgres::PgTypeInfo) -> bool { |
| 39 |
<String as sqlx::Type<sqlx::Postgres>>::compatible(ty) |
| 40 |
} |
| 41 |
} |
| 42 |
|
| 43 |
|
| 44 |
impl sqlx::Encode<'_, sqlx::Postgres> for $enum_name { |
| 45 |
fn encode_by_ref( |
| 46 |
&self, |
| 47 |
buf: &mut sqlx::postgres::PgArgumentBuffer, |
| 48 |
) -> Result<sqlx::encode::IsNull, Box<dyn std::error::Error + Send + Sync>> { |
| 49 |
<String as sqlx::Encode<'_, sqlx::Postgres>>::encode(self.to_string(), buf) |
| 50 |
} |
| 51 |
} |
| 52 |
|
| 53 |
|
| 54 |
impl sqlx::Decode<'_, sqlx::Postgres> for $enum_name { |
| 55 |
fn decode( |
| 56 |
value: sqlx::postgres::PgValueRef<'_>, |
| 57 |
) -> std::result::Result<Self, Box<dyn std::error::Error + Send + Sync>> { |
| 58 |
let s = <String as sqlx::Decode<'_, sqlx::Postgres>>::decode(value)?; |
| 59 |
Ok(s.parse::<Self>()?) |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
|
| 64 |
impl PartialEq<&str> for $enum_name { |
| 65 |
fn eq(&self, other: &&str) -> bool { |
| 66 |
let s: &str = match self { |
| 67 |
$( Self::$variant => $str, )+ |
| 68 |
}; |
| 69 |
s == *other |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
impl PartialEq<str> for $enum_name { |
| 74 |
fn eq(&self, other: &str) -> bool { |
| 75 |
let s: &str = match self { |
| 76 |
$( Self::$variant => $str, )+ |
| 77 |
}; |
| 78 |
s == other |
| 79 |
} |
| 80 |
} |
| 81 |
|
| 82 |
impl $enum_name { |
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
pub const VARIANTS: &'static [&'static str] = &[$($str),+]; |
| 93 |
} |
| 94 |
}; |
| 95 |
} |
| 96 |
|
| 97 |
pub(super) use impl_str_enum; |
| 98 |
|