comparison enigma/machine.cpp @ 4:2792ca4ffa84

Created enigma_machine class and tests.
author Brian Neal <bgneal@gmail.com>
date Sun, 24 Jun 2012 18:39:05 -0500
parents
children b90a41f0cd94
comparison
equal deleted inserted replaced
3:f4e25e6b76c3 4:2792ca4ffa84
1 // Copyright (C) 2012 by Brian Neal.
2 // This file is part of Cpp-Enigma, the Enigma Machine simulation.
3 // Cpp-Enigma is released under the MIT License (see License.txt).
4 //
5 // machine.cpp - The implementation file for the main Enigma machine class.
6
7 #include <cstddef>
8 #include "machine.h"
9 #include "rotor.h"
10 #include "rotor_factory.h"
11
12 using namespace enigma;
13
14 ////////////////////////////////////////////////////////////////////////////////
15
16 enigma_machine::enigma_machine(
17 rotor_vector rv,
18 std::unique_ptr<rotor> reflector,
19 const plugboard& pb)
20 : rotors(std::move(rv)),
21 reflector(std::move(reflector)),
22 pb(pb),
23 r_rotor(0),
24 m_rotor(0),
25 l_rotor(0)
26 {
27 rotor_count_check();
28 }
29
30 ////////////////////////////////////////////////////////////////////////////////
31
32 enigma_machine::enigma_machine(
33 rotor_vector rv,
34 std::unique_ptr<rotor> reflector)
35 : rotors(std::move(rv)),
36 reflector(std::move(reflector)),
37 pb(),
38 r_rotor(0),
39 m_rotor(0),
40 l_rotor(0)
41 {
42 rotor_count_check();
43 }
44
45 ////////////////////////////////////////////////////////////////////////////////
46
47 enigma_machine::enigma_machine(
48 const std::vector<std::string>& rotor_types,
49 const std::vector<int>& ring_settings,
50 const std::string& reflector_name,
51 const std::string& plugboard_settings)
52 : rotors(),
53 reflector(create_reflector(reflector_name.c_str())),
54 pb(plugboard_settings),
55 r_rotor(0),
56 m_rotor(0),
57 l_rotor(0)
58 {
59 for (const auto& name : rotor_types)
60 {
61 rotors.push_back(create_rotor(name.c_str()));
62 }
63 rotor_count_check();
64
65 // if ring settings are supplied, there has to be one for each rotor
66 if (!ring_settings.empty())
67 {
68 if (rotors.size() != ring_settings.size())
69 {
70 throw enigma_machine_error("rotor/ring setting count mismatch");
71 }
72
73 for (std::size_t i = 0; i < rotors.size(); ++i)
74 {
75 rotors[i]->set_ring_setting(ring_settings[i]);
76 }
77 }
78 }
79
80 ////////////////////////////////////////////////////////////////////////////////
81
82 void enigma_machine::rotor_count_check()
83 {
84 if (rotors.size() != 3 && rotors.size() != 4)
85 {
86 throw enigma_machine_error("rotor count");
87 }
88
89 if (rotors.size() == 3)
90 {
91 r_rotor = rotors[2].get();
92 m_rotor = rotors[1].get();
93 l_rotor = rotors[0].get();
94 }
95 else
96 {
97 r_rotor = rotors[3].get();
98 m_rotor = rotors[2].get();
99 l_rotor = rotors[1].get();
100 }
101 }