algods/sort/merge_sort/
algorithm.rs

1#[cfg(test)]
2mod unit_test;
3use std::error::Error;
4use std::fmt;
5use std::str::FromStr;
6
7/// Enumerating the different types of merge sort algorithm
8#[derive(Copy, Clone, Debug, PartialEq)]
9pub enum MergeSortAlgorithm {
10    /// The recursive algorithm
11    Recursive,
12    /// The iterative algorithm
13    BottomUp,
14}
15
16const ALGORITHMS: &str = "[Recursive, BottonUp]";
17
18impl Default for MergeSortAlgorithm {
19    fn default() -> Self {
20        Self::Recursive
21    }
22}
23
24// Formatting an Algorithm type (for printing purpose for e.g.)
25impl fmt::Display for MergeSortAlgorithm {
26    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
27        match self {
28            MergeSortAlgorithm::Recursive => write!(f, "Recursive"),
29            MergeSortAlgorithm::BottomUp => write!(f, "BottomUp"),
30        }
31    }
32}
33
34// Parsing a string slice (&str) to Algorithm
35impl FromStr for MergeSortAlgorithm {
36    type Err = ParseMergeSortAlgorithmError;
37
38    fn from_str(s: &str) -> std::result::Result<Self, ParseMergeSortAlgorithmError> {
39        match s {
40            "Recursive" => Ok(MergeSortAlgorithm::Recursive),
41            "BottomUp" => Ok(MergeSortAlgorithm::BottomUp),
42            _ => Err(ParseMergeSortAlgorithmError),
43        }
44    }
45}
46
47#[derive(Debug, Clone, PartialEq)]
48pub struct ParseMergeSortAlgorithmError;
49
50impl fmt::Display for ParseMergeSortAlgorithmError {
51    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52        let desc_init0: &str = "algorithm spelling incorrect, only available are";
53        let desc_init1 = format!("{desc_init0} {ALGORITHMS}");
54        let description = desc_init1.as_str();
55        f.write_str(description)
56    }
57}
58
59impl Error for ParseMergeSortAlgorithmError {}