Преглед изворни кода

Move parser wrapper into die.cxx

Sam Jaffe пре 7 година
родитељ
комит
efccaeb07d
3 измењених фајлова са 21 додато и 18 уклоњено
  1. 12 0
      include/die.h
  2. 8 0
      src/die.cxx
  3. 1 18
      src/main.cxx

+ 12 - 0
include/die.h

@@ -37,6 +37,18 @@ namespace dice {
     std::vector<die> of{};
     std::vector<mod> modifier{+0};
   };
+  
+  /**
+   * @brief A generator function to turn a string representation of a dice roll into a C++ object
+   * @param strdice A string representation of a dice roll, represented as one of the
+   * following expression classes:
+   * Die = [1-9]?\d*d[1-9]\d*
+   * SingleRoll: ($Die|\d+)((+|-)($Die|\d+))*
+   * RepeatRoll: [1-9]\d*\{$SingleRoll\}
+   * @return a dice object representing the roll
+   * @throws dice::unexpected_token if a parse failure occurs
+   */
+  dice from_string(std::string const & strdice);
 
   std::ostream & operator<<(std::ostream & out, dice const & d);
   std::istream & operator>>(std::istream & out, dice & d);

+ 8 - 0
src/die.cxx

@@ -11,6 +11,7 @@
 
 #include <cmath>
 #include <iostream>
+#include <sstream>
 
 static void advance_over_whitespace(std::istream & in, char const * also = "") {
   if (strchr(also, in.peek())) { in.get(); }
@@ -182,4 +183,11 @@ namespace dice {
     }
     return in;
   }
+  
+  dice from_string(std::string const & str) {
+    std::stringstream ss(str);
+    dice d;
+    ss >> d;
+    return d;
+  }
 }

+ 1 - 18
src/main.cxx

@@ -29,29 +29,12 @@ void print(std::vector<dice::dice_roll> const & rs) {
   }
 }
 
-/**
- *
- * @param str A string representation of a dice roll, represented as one of the
- * following expression classes:
- * Die = [1-9]?\d*d[1-9]\d*
- * SingleRoll: ($Die|\d+)((+|-)($Die|\d+))*
- * RepeatRoll: [1-9]\d*\{$SingleRoll\}
- * @return a dice object representing the roll
- * @throws dice::unexpected_token if a parse failure occurs
- */
-dice::dice make_dice(std::string const & str) {
-  std::stringstream ss(str);
-  dice::dice d;
-  ss >> d;
-  return d;
-}
-
 /**
  * @param str {@see make_dice(std::string const &)}
  */
 void eval(std::string const & str) {
   try {
-    auto d = make_dice(str);
+    auto d = dice::from_string(str);
     auto rs = dice::roll(d);
     std::cout << "Result of '" << d << "': ";
     print(rs);