1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
//! Enigma Finite State Machine

use super::{
    components::{Plugboard, Reflector, Rotor, Wheel, ROTOR_NUM},
    utils::Letter,
};

/// ZST representing an unset, but required, setting in the enigma machine FSM
pub struct Unset;

#[derive(Debug)]
/// Settings for the Enigma machine. Equivalent to a modern day IV (Initialisation Vector)
pub struct EnigmaSettings {
    /// Rotors and their ordering
    pub rotors: [Rotor; ROTOR_NUM],
    /// Plugboard cabling
    pub plugboard: Plugboard,
    /// Selected reflector
    pub reflector: Reflector,
    /// Ring settings for each rotor
    pub ringstellung: [u8; ROTOR_NUM],
    /// Starting position for each rotor
    pub grundstellung: [Letter; ROTOR_NUM],
}

#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Hash, Debug)]
/// Enigma Finite State Machine
///
/// An incomplete instance (e.g. from `Enigma::default`) can be initialised later
/// semi-dynamically with the compiler checking correct initialisation before use.
///
/// # Examples
///
/// ```
/// # use mini_enigma::state_machine::Enigma;
/// # use mini_enigma::utils::Letter;
/// # use mini_enigma::components::{Wheel, ROTOR_I, ROTOR_II, ROTOR_III, Plugboard, REFLECTOR_A};
/// let enigma = Enigma::default()
///     .set_rotors(Wheel::new([ROTOR_I, ROTOR_II, ROTOR_III]))
///     .set_plugboard(Plugboard::new(&[]));
///
/// let mut enigma = enigma.set_reflector(REFLECTOR_A);
///
/// enigma.encrypt_letter(Letter::A);
///
/// ```
///
/// The compiler can detect if one of the required initialisation steps is missing:
/// ```compile_fail,E0599
/// # use mini_enigma::state_machine::Enigma;
/// # use mini_enigma::utils::Letter;
/// # use mini_enigma::components::{Wheel, ROTOR_I, ROTOR_II, ROTOR_III, Plugboard, REFLECTOR_A};
/// let mut enigma = Enigma::default()
///     .set_rotors(Wheel::new([ROTOR_I, ROTOR_II, ROTOR_III]))
///     .set_plugboard(Plugboard::new(&[]));
///
/// enigma.encrypt_letter(Letter::A); // encrypt can't be called until a reflector is set
///
/// ```
pub struct Enigma<R, P, O> {
    rotors: R,
    plugboard: P,
    reflector: O,
}

impl Default for Enigma<Unset, Unset, Unset> {
    fn default() -> Self {
        Enigma {
            rotors: Unset,
            plugboard: Unset,
            reflector: Unset,
        }
    }
}

impl Enigma<Unset, Unset, Unset> {
    /// Create a fully setup Enigma FSM from the provided settings
    ///
    /// # Examples
    /// ```
    /// # use mini_enigma::state_machine::{Enigma, EnigmaSettings};
    /// # use mini_enigma::utils::Letter;
    /// # use mini_enigma::components::{Wheel, ROTOR_II, ROTOR_IV, ROTOR_V, Plugboard, REFLECTOR_B};
    /// # use core::str::FromStr;
    /// let mut enigma = Enigma::new(&EnigmaSettings {
    ///     rotors: [ROTOR_II, ROTOR_IV, ROTOR_V],
    ///     plugboard: Plugboard::from_str(
    ///         "AV,BS,CG,DL,FU,HZ,IN,KM,OW,RX",
    ///     ).unwrap(),
    ///     reflector: REFLECTOR_B,
    ///     ringstellung: [2, 21, 12],
    ///     grundstellung: [Letter::B, Letter::L, Letter::A],
    /// });
    /// enigma.encrypt_letter(Letter::A);
    /// ```
    #[must_use]
    pub fn new(config: &EnigmaSettings) -> Enigma<Wheel, Plugboard, Reflector> {
        let mut enigma = Enigma {
            rotors: Wheel::new(config.rotors),
            plugboard: config.plugboard,
            reflector: config.reflector,
        };
        enigma.set_grundstellung(config.grundstellung);
        enigma.set_ringstellung(config.ringstellung);
        enigma
    }
}

impl<AnyRotor, AnyPlugboard, AnyReflector> Enigma<AnyRotor, AnyPlugboard, AnyReflector> {
    /// Set the Enigma rotors
    pub fn set_rotors(self, rotors: Wheel) -> Enigma<Wheel, AnyPlugboard, AnyReflector> {
        Enigma {
            rotors,
            plugboard: self.plugboard,
            reflector: self.reflector,
        }
    }

    /// Set the Enigma plguboard
    pub fn set_plugboard(self, plugboard: Plugboard) -> Enigma<AnyRotor, Plugboard, AnyReflector> {
        Enigma {
            rotors: self.rotors,
            plugboard,
            reflector: self.reflector,
        }
    }

    /// Set the Enigma reflector
    pub fn set_reflector(self, reflector: Reflector) -> Enigma<AnyRotor, AnyPlugboard, Reflector> {
        Enigma {
            rotors: self.rotors,
            plugboard: self.plugboard,
            reflector,
        }
    }
}

impl<AnyPlugboard, AnyReflector> Enigma<Wheel, AnyPlugboard, AnyReflector> {
    /// Set the starting position for the rotors
    pub fn set_grundstellung(
        &mut self,
        positions: [Letter; ROTOR_NUM],
    ) -> &mut Enigma<Wheel, AnyPlugboard, AnyReflector> {
        self.rotors.set_positions(positions);
        self
    }

    /// Set the ring settings for the rotors
    pub fn set_ringstellung(
        &mut self,
        positions: [u8; ROTOR_NUM],
    ) -> &mut Enigma<Wheel, AnyPlugboard, AnyReflector> {
        self.rotors.set_ring_wiring_offset(positions);
        self
    }

    /// Get `Rotor` positions
    pub fn get_grundstellung(&self) -> [Letter; ROTOR_NUM] {
        self.rotors.get_positions()
    }
}

impl Enigma<Wheel, Plugboard, Reflector> {
    /// Encrypt/decrypt a `Letter` and advance the state
    pub fn encrypt_letter(&mut self, letter: Letter) -> Letter {
        self.rotors.step();
        let left = self.rotors.forward(self.plugboard[letter]);
        self.plugboard[self.rotors.backward(self.reflector[left])]
    }

    /// Encrypt/decrypt a `char` and advance the state
    pub fn encrypt_char(&mut self, letter: char) -> char {
        match Letter::try_from(letter) {
            Ok(a) => self.encrypt_letter(a).into(),
            Err(_) => letter,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::super::components::{
        REFLECTOR_A, REFLECTOR_B, ROTOR_I, ROTOR_II, ROTOR_III, ROTOR_IV, ROTOR_V,
    };
    use super::*;
    use core::str::FromStr;

    #[test]
    #[cfg(not(feature = "M4"))]
    fn test_machine() {
        let enigma = Enigma::default();
        let enigma = enigma.set_rotors(Wheel::new([ROTOR_I, ROTOR_II, ROTOR_III]));
        let enigma = enigma.set_plugboard(Plugboard::new(&[]));
        let enigma = enigma.set_reflector(REFLECTOR_A);
        let mut enigma = enigma.set_rotors(Wheel::new([ROTOR_III, ROTOR_II, ROTOR_I]));
        enigma.encrypt_letter(Letter::A);
    }

    #[test]
    #[cfg(not(feature = "M4"))]
    fn test_letter() {
        let mut enigma = Enigma::default()
            .set_rotors(Wheel::new([ROTOR_II, ROTOR_IV, ROTOR_V]))
            .set_reflector(REFLECTOR_B)
            .set_plugboard(Plugboard::from_str("AV,BS,CG,DL,FU,HZ,IN,KM,OW,RX").unwrap());
        enigma
            .set_grundstellung([Letter::B, Letter::L, Letter::A])
            .set_ringstellung([2, 21, 12]);
        assert_eq!(Letter::A, enigma.encrypt_letter(Letter::E));
        assert_eq!(Letter::U, enigma.encrypt_letter(Letter::D));
        assert_eq!(Letter::F, enigma.encrypt_letter(Letter::P));
        assert_eq!(Letter::K, enigma.encrypt_letter(Letter::U));
        assert_eq!(Letter::L, enigma.encrypt_letter(Letter::D));
        assert_eq!(Letter::X, enigma.encrypt_letter(Letter::N));
        assert_eq!(Letter::A, enigma.encrypt_letter(Letter::R));
        assert_eq!(Letter::B, enigma.encrypt_letter(Letter::G));
        assert_eq!(Letter::T, enigma.encrypt_letter(Letter::Y));
        assert_eq!(Letter::E, enigma.encrypt_letter(Letter::S));
    }

    #[test]
    #[cfg(not(feature = "M4"))]
    fn test_string() {
        let mut enigma = Enigma::new(&EnigmaSettings {
            rotors: [ROTOR_II, ROTOR_IV, ROTOR_V],
            plugboard: Plugboard::from_str("AV,BS,CG,DL,FU,HZ,IN,KM,OW,RX").unwrap(),
            reflector: REFLECTOR_B,
            ringstellung: [2, 21, 12],
            grundstellung: [Letter::B, Letter::L, Letter::A],
        });
        let input = "AUFKLXABTE";
        let expected = "EDPUDNRGYS".as_bytes();
        for (i, ch) in input.chars().enumerate() {
            assert_eq!(expected[i] as char, enigma.encrypt_char(ch));
        }
    }
}