Browse Source

[4091] Implemented, need tests

Francis Dupont 9 years ago
parent
commit
4e42ee425f
2 changed files with 50 additions and 0 deletions
  1. 24 0
      src/lib/eval/token.cc
  2. 26 0
      src/lib/eval/token.h

+ 24 - 0
src/lib/eval/token.cc

@@ -14,6 +14,7 @@
 
 #include <eval/token.h>
 #include <eval/eval_log.h>
+#include <util/encode/hex.h>
 #include <boost/lexical_cast.hpp>
 #include <string>
 
@@ -27,6 +28,29 @@ TokenString::evaluate(const Pkt& /*pkt*/, ValueStack& values) {
 }
 
 void
+TokenString::evaluate(const Pkt& /*pkt*/, ValueStack& values) {
+    // Transform string of hexadecimal digits into binary format
+    std::vector<uint8_t> binary;
+    try {
+        // The decodeHex function expects that the string contains an
+        // even number of digits. If we don't meet this requirement,
+        // we have to insert a leading 0.
+        if (!repr_.empty() && repr_.length() % 2) {
+            repr_ = repr_.insert(0, "0");
+        }
+        util::encode::decodeHex(repr_, binary);
+    } catch (...) {
+        values.push("");
+        return;
+    }
+    // Convert to a string
+    std::string chars(binary.size(), '\0');
+    std::memmove(&chars[0], &binary[0], binary.size());
+    // Literals only push, nothing to pop
+    values.push(chars_);
+}
+
+void
 TokenOption::evaluate(const Pkt& pkt, ValueStack& values) {
     OptionPtr opt = pkt.getOption(option_code_);
     if (opt) {

+ 26 - 0
src/lib/eval/token.h

@@ -101,6 +101,32 @@ protected:
     std::string value_; ///< Constant value
 };
 
+/// @brief Token representing a constant string in hexadecimal format
+///
+/// This token holds value of a constant string giving in an hexadecimal
+/// format, for instance 0x666f6f is "foo"
+class TokenHexString : public Token {
+public:
+    /// Value is set during token construction.
+    ///
+    /// @param str constant string to be represented
+    /// (must be a string of hexadecimal digits or decoding will fail)
+    TokenHexString(const std::string& str)
+        :repr_(str){
+    }
+
+    /// @brief Token evaluation (puts value of the constant string on
+    /// the stack after decoding or an empty string if decoding fails
+    /// (note it should not if the parser is correct)
+    ///
+    /// @param pkt (ignored)
+    /// @param values (represented string will be pushed here)
+    void evaluate(const Pkt& pkt, ValueStack& values);
+
+protected:
+    std::string repr_; ///< Constant value
+};
+
 /// @brief Token that represents a value of an option
 ///
 /// This represents a reference to a given option, e.g. in the expression