Skip to content

Commit e9d569f

Browse files
jyn514Joshua Nelson
authored and
Joshua Nelson
committed
Use macro-based enum for extensibility
1 parent 9923dea commit e9d569f

File tree

1 file changed

+33
-24
lines changed

1 file changed

+33
-24
lines changed

src/storage/mod.rs

Lines changed: 33 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -17,37 +17,46 @@ const MAX_CONCURRENT_UPLOADS: usize = 1000;
1717

1818
pub type CompressionAlgorithms = HashSet<CompressionAlgorithm>;
1919

20-
// NOTE: the `TryFrom` impl must be updated whenever a new variant is added.
21-
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
22-
pub enum CompressionAlgorithm {
23-
Zstd = 0,
24-
}
20+
macro_rules! enum_id {
21+
($vis:vis enum $name:ident { $($variant:ident = $discriminant:expr,)* }) => {
22+
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
23+
$vis enum $name {
24+
$($variant = $discriminant,)*
25+
}
2526

26-
impl fmt::Display for CompressionAlgorithm {
27-
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28-
match self {
29-
CompressionAlgorithm::Zstd => write!(f, "zstd"),
27+
impl fmt::Display for CompressionAlgorithm {
28+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29+
match self {
30+
$(Self::$variant => write!(f, stringify!($variant)),)*
31+
}
32+
}
3033
}
31-
}
32-
}
3334

34-
impl std::str::FromStr for CompressionAlgorithm {
35-
type Err = ();
36-
fn from_str(s: &str) -> Result<Self, Self::Err> {
37-
match s {
38-
"zstd" => Ok(CompressionAlgorithm::Zstd),
39-
_ => Err(()),
35+
impl std::str::FromStr for CompressionAlgorithm {
36+
type Err = ();
37+
fn from_str(s: &str) -> Result<Self, Self::Err> {
38+
match s {
39+
$(stringify!($variant) => Ok(Self::$variant),)*
40+
_ => Err(()),
41+
}
42+
}
43+
}
44+
45+
impl std::convert::TryFrom<i32> for CompressionAlgorithm {
46+
type Error = i32;
47+
fn try_from(i: i32) -> Result<Self, Self::Error> {
48+
match i {
49+
$($discriminant => Ok(Self::$variant),)*
50+
_ => Err(i),
51+
}
52+
}
4053
}
4154
}
4255
}
4356

44-
impl std::convert::TryFrom<i32> for CompressionAlgorithm {
45-
type Error = i32;
46-
fn try_from(i: i32) -> Result<Self, Self::Error> {
47-
match i {
48-
0 => Ok(Self::Zstd),
49-
_ => Err(i),
50-
}
57+
enum_id! {
58+
pub enum CompressionAlgorithm {
59+
Zstd = 0,
5160
}
5261
}
5362

0 commit comments

Comments
 (0)