src/Common/String/FormatterImpl.h

Go to the documentation of this file.
00001 #pragma once
00002 
00003 template<class T>
00004 class FormatterImpl
00005 {
00006 public:
00007 
00008     // \todo add flags to change behavior of mapping variables that don't exist, currently they are left untouched
00009     static int FormatTemplate(std::basic_string<T>& s, const std::map<std::basic_string<T>, std::basic_string<T>>& variables, const std::basic_string<T>& left, const std::basic_string<T>& right) 
00010         {
00011         if (left.empty() || right.empty())
00012         {
00013             throw std::exception("Missing l/r delimiter(s)");
00014         }
00015 
00016         if (s.empty())
00017         {
00018             return 0;
00019         }
00020 
00021                 int ii = 0;
00022                 int result = 0;
00023                 
00024                 while ((ii = s.find(left, ii)) != s.npos) 
00025                 {
00026             int jj = s.find(right, ii + left.length());
00027             if (jj == s.npos)
00028                 break;
00029 
00030             int replace_length = jj - ii + right.length();
00031             int variable_length = jj - ii - left.length();
00032 
00033             std::basic_string<T> variable = s.substr(ii + left.length(), variable_length);
00034             std::map<std::basic_string<T>, std::basic_string<T>>::const_iterator iter = variables.find(variable);
00035             if (iter != variables.end())
00036             {
00037                 std::basic_string<T> variable_value = iter->second;
00038                             s.replace(ii, replace_length, variable_value);
00039                             ii += variable_value.length();
00040             }
00041             else
00042             {
00043                 ii += replace_length;
00044             }
00045 
00046                         result ++;
00047                 }
00048 
00049                 return result;
00050         }
00051 };


© Application Security Inc. - All Rights Reserved http://msiext.codeplex.com