comparison enigma/rotor.cpp @ 0:74ebb2150658

Initial commit. Working on the rotor class.
author Brian Neal <bgneal@gmail.com>
date Thu, 21 Jun 2012 21:05:26 -0500
parents
children 1459e74fda3f
comparison
equal deleted inserted replaced
-1:000000000000 0:74ebb2150658
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 // rotor.cpp - Implementation file for the rotor class.
6
7 #include <set>
8 #include <array>
9 #include <algorithm>
10 #include "rotor.h"
11
12 using namespace enigma;
13
14 namespace
15 {
16 const char* const ucase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
17 const std::set<char> ucase_set(ucase, ucase + 26);
18 }
19
20 rotor::rotor(const char* name, const char* wiring, int ring_setting, const char* stepping)
21 : rotor_name(name),
22 wiring_str(wiring),
23 ring_setting(ring_setting),
24 pos(0),
25 rotations(0)
26 {
27 // check wiring length
28 if (wiring_str.size() != 26)
29 {
30 throw rotor_error("invalid wiring length");
31 }
32
33 // ensure wiring contains only uppercase letters & every char must appear
34 // exactly once:
35
36 std::array<int, 26> letter_counts {{ 0 }};
37 for (int i = 0; i < 26; ++i)
38 {
39 const char c(wiring_str[i]);
40
41 if (ucase_set.find(c) == ucase_set.end())
42 {
43 throw rotor_error("invalid wiring");
44 }
45 ++letter_counts[c - 'A'];
46 }
47
48 if (std::find_if(letter_counts.begin(),
49 letter_counts.end(),
50 [](int n) { return n != 1; }) != letter_counts.end())
51 {
52 throw rotor_error("invalid wiring; duplicate letter");
53 }
54 }