changeset 8:b90a41f0cd94

Created enigma_machine::army_str() & navy_str() functions for logging.
author Brian Neal <bgneal@gmail.com>
date Fri, 29 Jun 2012 20:29:41 -0500
parents db1216d380b3
children 7362965f53b1
files enigma/machine.cpp enigma/machine.h enigma/tests/test_machine.t.h
diffstat 3 files changed, 46 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/enigma/machine.cpp	Fri Jun 29 20:08:10 2012 -0500
+++ b/enigma/machine.cpp	Fri Jun 29 20:29:41 2012 -0500
@@ -5,6 +5,7 @@
 // machine.cpp - The implementation file for the main Enigma machine class.
 
 #include <cstddef>
+#include <sstream>
 #include "machine.h"
 #include "rotor.h"
 #include "rotor_factory.h"
@@ -99,3 +100,22 @@
       l_rotor = rotors[1].get();
    }
 }
+
+////////////////////////////////////////////////////////////////////////////////
+
+std::string enigma_machine::str(bool army) const
+{
+   std::ostringstream os;
+
+   os << reflector->name() << ' ';
+
+   for (const auto& r : rotors)
+   {
+      os << r->name() << '/' << r->get_ring_setting() << ' ';
+   }
+
+   os << get_display() << ' ' << (army ? pb.army_str() : pb.navy_str());
+
+   return os.str();
+}
+
--- a/enigma/machine.h	Fri Jun 29 20:08:10 2012 -0500
+++ b/enigma/machine.h	Fri Jun 29 20:29:41 2012 -0500
@@ -126,6 +126,12 @@
       // for access to the plugboard for hill-climbing, etc
       plugboard& get_plugboard() { return pb; }
 
+      // Returns a string representation of the enigma machine's state. Useful
+      // for logging, etc:
+      //
+      std::string army_str() const { return str(true); }
+      std::string navy_str() const { return str(false); }
+
    private:
       rotor_vector rotors;
       std::unique_ptr<rotor> reflector;
@@ -188,6 +194,8 @@
 
          return pb.signal(pos);
       }
+
+      std::string str(bool army) const;
    };
 }
 
--- a/enigma/tests/test_machine.t.h	Fri Jun 29 20:08:10 2012 -0500
+++ b/enigma/tests/test_machine.t.h	Fri Jun 29 20:29:41 2012 -0500
@@ -31,6 +31,24 @@
       TS_ASSERT_THROWS(m.set_display("BCD"), enigma_machine_error);
       TS_ASSERT_THROWS_NOTHING(m.set_display("ABCD"));
    }
+
+   void test_navy_str()
+   {
+      const std::string stecker = "1/20 2/12 4/6 7/10 8/13 14/23 15/16 17/25 18/26 22/24";
+      enigma_machine machine({"Beta", "II", "IV", "I"}, {0, 0, 0, 21}, "B-Thin", stecker);
+
+      TS_ASSERT_EQUALS(machine.navy_str(), "B-Thin Beta/0 II/0 IV/0 I/21 AAAA "
+               "1/20 2/12 4/6 7/10 8/13 14/23 15/16 17/25 18/26 22/24");
+   }
+
+   void test_army_str()
+   {
+      enigma_machine machine({"II", "IV", "V"}, {1, 20, 11}, "B",
+               "AV BS CG DL FU HZ IN KM OW RX");
+
+      TS_ASSERT_EQUALS(machine.army_str(), "B II/1 IV/20 V/11 AAA "
+               "AV BS CG DL FU HZ IN KM OW RX");
+   }
 };
 
 class stepping_test_suite : public CxxTest::TestSuite