Skip to content

Commit b942327

Browse files
authored
Merge pull request #78 from valarauca/named-variable
Add method of convert the long name back to an enum.
2 parents 0f3372c + c6dbd51 commit b942327

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

src/macros.rs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,31 @@ macro_rules! formats {
144144
)*
145145
}
146146
}
147+
148+
/// Converts the full name of a file format into the enum representation
149+
///
150+
/// # Examples
151+
///
152+
/// Basic usage:
153+
///
154+
/// ```
155+
/// use file_format::{FileFormat, Kind};
156+
///
157+
/// let fmt = FileFormat::Mpeg12AudioLayer3;
158+
/// let name = fmt.name();
159+
/// assert_eq!(name, "MPEG-1/2 Audio Layer 3");
160+
/// assert_eq!(FileFormat::from_name(name), Some(fmt));
161+
/// ```
162+
pub fn from_name(name: &str) -> Option<crate::FileFormat> {
163+
static NAME: std::sync::OnceLock<std::collections::HashMap<&'static str,crate::FileFormat>> = std::sync::OnceLock::new();
164+
NAME.get_or_init(|| -> std::collections::HashMap<&'static str,crate::FileFormat> {
165+
let mut map = std::collections::HashMap::new();
166+
$(
167+
map.insert($name, Self::$format);
168+
)*
169+
map
170+
}).get(name).cloned()
171+
}
147172
}
148173
};
149174
}

0 commit comments

Comments
 (0)