Skip to main content

bc_mur/
correction.rs

1/// QR error correction level.
2#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3pub enum CorrectionLevel {
4    Low,
5    Medium,
6    Quartile,
7    High,
8}
9
10impl CorrectionLevel {
11    pub(crate) fn to_qrcode(self) -> qrcode::EcLevel {
12        match self {
13            Self::Low => qrcode::EcLevel::L,
14            Self::Medium => qrcode::EcLevel::M,
15            Self::Quartile => qrcode::EcLevel::Q,
16            Self::High => qrcode::EcLevel::H,
17        }
18    }
19}
20
21impl std::fmt::Display for CorrectionLevel {
22    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
23        match self {
24            Self::Low => write!(f, "low"),
25            Self::Medium => write!(f, "medium"),
26            Self::Quartile => write!(f, "quartile"),
27            Self::High => write!(f, "high"),
28        }
29    }
30}
31
32impl std::str::FromStr for CorrectionLevel {
33    type Err = String;
34
35    fn from_str(s: &str) -> std::result::Result<Self, String> {
36        match s.to_ascii_lowercase().as_str() {
37            "low" | "l" => Ok(Self::Low),
38            "medium" | "m" => Ok(Self::Medium),
39            "quartile" | "q" => Ok(Self::Quartile),
40            "high" | "h" => Ok(Self::High),
41            _ => Err(format!(
42                "unknown correction level: {s} (expected low, medium, quartile, or high)"
43            )),
44        }
45    }
46}