Example #1
0
int Server::LookupCommand(const std::string& uri, const std::string& http_verb, std::wstring* session_id, std::wstring* locator) {
	int value = NoCommand;
	UrlMap::const_iterator it = this->commands_.begin();
	for (; it != this->commands_.end(); ++it) {
		std::vector<std::string> locator_param_names;
		std::string url_candidate = it->first;
		size_t param_start_pos = url_candidate.find_first_of(":");
		while (param_start_pos != std::string::npos) {
			size_t param_len = std::string::npos;
			size_t param_end_pos = url_candidate.find_first_of("/", param_start_pos);
			if (param_end_pos != std::string::npos) {
				param_len = param_end_pos - param_start_pos;
			}

			// Skip the colon
			std::string param_name = url_candidate.substr(param_start_pos + 1, param_len - 1);
			locator_param_names.push_back(param_name);
			if (param_name == "sessionid" || param_name == "id") {
				url_candidate.replace(param_start_pos, param_len, "([0-9a-fA-F-]+)");
			} else {
				url_candidate.replace(param_start_pos, param_len, "([^/]+)");
			}
			param_start_pos = url_candidate.find_first_of(":");
		}

		std::string::const_iterator uri_start = uri.begin();
		std::string::const_iterator uri_end = uri.end(); 
		std::tr1::regex matcher("^" + url_candidate + "$");
		std::tr1::match_results<std::string::const_iterator> matches;
		if (std::tr1::regex_search(uri_start, uri_end, matches, matcher)) {
			VerbMap::const_iterator verb_iterator = it->second.find(http_verb);
			if (verb_iterator != it->second.end()) {
				value = verb_iterator->second;
				std::string param = "{";
				size_t param_count = locator_param_names.size();
				for (unsigned int i = 0; i < param_count; i++) {
					if (i != 0) {
						param += ",";
					}

					std::string locator_param_value(matches[i + 1].first, matches[i + 1].second);
					param += " \"" + locator_param_names[i] + "\" : \"" + locator_param_value + "\"";
					if (locator_param_names[i] == "sessionid") {
						session_id->append(CA2W(locator_param_value.c_str(), CP_UTF8));
					}
				}

				param += " }";
				std::wstring wide_param(param.begin(), param.end());
				locator->append(wide_param);
				break;
			} else {
				verb_iterator = it->second.begin();
				for (; verb_iterator != it->second.end(); ++verb_iterator) {
					if (locator->size() != 0) {
						locator->append(L",");
					}
					locator->append(CA2W(verb_iterator->first.c_str(), CP_UTF8));
				}
			}
		}
	}

	return value;
}
Example #2
0
bool is_number(const std::string& s)
{
	std::string::const_iterator it = s.begin();
	while (it != s.end() && (isdigit(*it) || (*it == '.') || (*it == '-') || (*it == ' ') || (*it == 0x00))) ++it;
	return !s.empty() && it == s.end();
}
Example #3
0
void copy_call_graph( std::string const & input, std::string & output )
{
#if defined(_MSC_VER) && 0
    output.reserve( input.size() );

    unsigned int pos    (     0 );
    unsigned int counter(     0 );
    bool         matched( false );

    std::string buffer;

    std::string::const_iterator       p_ch     ( input.begin() );
    std::string::const_iterator const input_end( input.end  () );

    while ( p_ch != input_end )
    {
        char const ch( *p_ch++ );
        buffer.push_back( ch );
        if ( ch == '\n' )
        {
            if ( matched )
            {
                output.append( buffer );
                if ( ++counter % 200 == 0 ) std::fprintf( stderr, "On Instantiation %d\n", counter/2 );
                buffer.clear();
                matched = false;
                // process instantiation back-trace
                pos = 0;
                while ( p_ch != input_end )
                {
                    char const ch( *p_ch++ );
                    if ( ch == ' ' )
                    {
                        buffer.push_back( ch );
                        while ( p_ch != input_end )
                        {
                            char const ch( *p_ch++ );
                            buffer.push_back( ch );
                            if ( ch == '\n' )
                            {
                                if ( matched )
                                {
                                    output.append( buffer );
                                }
                                buffer.clear();
                                matched = false;
                                pos = 0;
                                break;
                            }
                            if ( ch == back_trace_search[ pos ] )
                            {
                                ++pos;
                                if ( back_trace_search[ pos ] == '\0' )
                                {
                                    matched = true;
                                }
                            }
                            else
                            {
                                pos = 0;
                            }
                        }
                    }
                    else
                    {
                        --p_ch;
                        break;
                    }
                }
            }
            buffer.clear();
            matched = false;
            pos = 0;
        }
        if ( ch == search[ pos ] )
        {
            ++pos;
            if ( search[ pos ] == '\0' )
            {
                matched = true;
            }
        }
        else
        {
            pos = 0;
        }
    }
#elif defined(__GNUC__) || 1
    // trying to figure out what we should copy is too hard.
    output = input;
#else
    #error Unknown compiler
#endif
}
void Signature::setQuirksSignature( std::string fp )
{
    quirks_ = 0;
    /*
     * Quirks section is usually an empty list ('.') of oddities or bugs of this
     * particular stack. List items are not separated in any way. Possible values:
     *
     * P     - options past EOL,
     * Z - zero IP ID,
     * I - IP options specified,
     * U - urg pointer non-zero,
     * X     - unused (x2) field non-zero,
     * A - ACK number non-zero,
     * T     - non-zero second timestamp,
     * F     - unusual flags (PUSH, URG, etc),
     * D     - data payload,
     * !     - broken options segment.
     */

    std::string::iterator itr;
    for( itr = fp.begin(); itr != fp.end(); ++itr )
    {
        switch( tolower(*itr) )
        {
        case 'p':
            quirks_ |= QUIRK_PAST;
            break;
        case 'z':
            quirks_ |= QUIRK_ZEROID;
            break;
        case 'i':
            quirks_ |= QUIRK_IPOPT;
            break;
        case 'u':
            quirks_ |= QUIRK_URG;
            break;
        case 'x':
            quirks_ |= QUIRK_X2;
            break;
        case 'a':
            quirks_ |= QUIRK_ACK;
            break;
        case 't':
            quirks_ |= QUIRK_T2;
            break;
        case 'f':
            quirks_ |= QUIRK_FLAGS;
            break;
        case 'd':
            quirks_ |= QUIRK_DATA;
            break;
        case '!':
            quirks_ |= QUIRK_BROKEN;
            break;
        case 'k':
            quirks_ |= QUIRK_RSTACK;
            break;
        case 'q':
            quirks_ |= QUIRK_SEQEQ;
            break;
        case '0':
            quirks_ |= QUIRK_SEQ0;
            break;
        }
    }
}
Example #5
0
void ByteBuffer::SerializeString(const std::string &str) {
  for (std::string::const_iterator i = str.begin();
       i != str.end(); ++i)
    buffer.push_back(*i);
  buffer.push_back('\0');
}
void RequestHandler::handle_request(const http::Request &req, http::Reply &reply)
{
    // parse command
    try
    {
        std::string request;
        URIDecode(req.uri, request);

        // deactivated as GCC apparently does not implement that, not even in 4.9
        // std::time_t t = std::time(nullptr);
        // SimpleLogger().Write() << std::put_time(std::localtime(&t), "%m-%d-%Y %H:%M:%S") <<
        //     " " << req.endpoint.to_string() << " " <<
        //     req.referrer << ( 0 == req.referrer.length() ? "- " :" ") <<
        //     req.agent << ( 0 == req.agent.length() ? "- " :" ") << request;

        time_t ltime;
        struct tm *Tm;

        ltime = time(nullptr);
        Tm = localtime(&ltime);

        // log timestamp
        SimpleLogger().Write() << (Tm->tm_mday < 10 ? "0" : "") << Tm->tm_mday << "-"
                               << (Tm->tm_mon + 1 < 10 ? "0" : "") << (Tm->tm_mon + 1) << "-"
                               << 1900 + Tm->tm_year << " " << (Tm->tm_hour < 10 ? "0" : "")
                               << Tm->tm_hour << ":" << (Tm->tm_min < 10 ? "0" : "") << Tm->tm_min
                               << ":" << (Tm->tm_sec < 10 ? "0" : "") << Tm->tm_sec << " "
                               << req.endpoint.to_string() << " " << req.referrer
                               << (0 == req.referrer.length() ? "- " : " ") << req.agent
                               << (0 == req.agent.length() ? "- " : " ") << request;

        RouteParameters route_parameters;
        APIGrammarParser api_parser(&route_parameters);

        auto iter = request.begin();
        const bool result = boost::spirit::qi::parse(iter, request.end(), api_parser);

        // check if the was an error with the request
        if (!result || (iter != request.end()))
        {
            reply = http::Reply::StockReply(http::Reply::badRequest);
            reply.content.clear();
            const unsigned position = static_cast<unsigned>(std::distance(request.begin(), iter));
            JSON::Object json_result;
            json_result.values["status"] = 400;
            std::string message = "Query string malformed close to position ";
            message += UintToString(position);
            json_result.values["status_message"] = message;
            JSON::render(reply.content, json_result);
            return;
        }

        // parsing done, lets call the right plugin to handle the request
        BOOST_ASSERT_MSG(routing_machine != nullptr, "pointer not init'ed");

        if (!route_parameters.jsonp_parameter.empty())
        { // prepend response with jsonp parameter
            const std::string json_p = (route_parameters.jsonp_parameter + "(");
            reply.content.insert(reply.content.end(), json_p.begin(), json_p.end());
        }
        routing_machine->RunQuery(route_parameters, reply);
        if (!route_parameters.jsonp_parameter.empty())
        { // append brace to jsonp response
            reply.content.push_back(')');
        }

        reply.headers.emplace_back("Access-Control-Allow-Origin", "*");
        reply.headers.emplace_back("Access-Control-Allow-Methods", "GET");
        reply.headers.emplace_back("Access-Control-Allow-Headers", "X-Requested-With, Content-Type");

        // set headers
        reply.headers.emplace_back("Content-Length",
                                   UintToString(static_cast<unsigned>(reply.content.size())));
        if ("gpx" == route_parameters.output_format)
        { // gpx file
            reply.headers.emplace_back("Content-Type", "application/gpx+xml; charset=UTF-8");
            reply.headers.emplace_back("Content-Disposition", "attachment; filename=\"route.gpx\"");
        }
        else if (route_parameters.jsonp_parameter.empty())
        { // json file
            reply.headers.emplace_back("Content-Type", "application/json; charset=UTF-8");
            reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.json\"");
        }
        else
        { // jsonp
            reply.headers.emplace_back("Content-Type", "text/javascript; charset=UTF-8");
            reply.headers.emplace_back("Content-Disposition", "inline; filename=\"response.js\"");
        }
    }
    catch (const std::exception &e)
    {
        reply = http::Reply::StockReply(http::Reply::internalServerError);
        SimpleLogger().Write(logWARNING) << "[server error] code: " << e.what()
                                         << ", uri: " << req.uri;
        return;
    }
}
Example #7
0
	void Parser_XML::erase_all_characters(std::string& str, char character) 
	{  
		str.erase(std::remove(str.begin(), str.end(), character), str.end());  
	}
Example #8
0
void leftTrimString(std::string & str) noexcept {
    auto begin(str.begin());
    str.erase(begin, std::find_if_not(begin, str.end(), charIsSpace));
}
Example #9
0
void rightTrimString(std::string & str) noexcept {
    str.erase(std::find_if_not(str.rbegin(), str.rend(), charIsSpace).base(),
              str.end());
}
Example #10
0
/** Test equality between two strings without regard to case. */
inline UTILITIES_API bool istringEqual(const std::string& x, const std::string& y){
  return x.size() == y.size() &&
         std::equal(x.begin(), x.end(), y.begin(), IcharCompare());
};
node parser::parseline(std::string linha){
	linha.append(" "); // <--- super gambiarra, colocando espaço no final pro algoritmo funcionar
	int flag_label = 0; //se ja tiver setado como 1, ou é o comando ou é parametro
	int flag_comando = 0; //se ja tiver setado, primeiro parametro foi armazenado
	int flag_parametro = 0; //para indicar se o primeiro parametro ja existe
	std::string::iterator itr;
	std::string buffer;
	node r_node;
	if(linha == "") //retorna nó vazio se a linha for vazia
		return r_node;
	//itera toda a linha
	for(itr = linha.begin() ; itr != linha.end() ; itr++){
		//se caractere nao for espaço, armazena na palavra
		if((*itr) != ' ' && (*itr) != ',')
			buffer.push_back((*itr));
		/*
		 * se for espaço (final de palavra), verifica se é palavra chave.
		 * se for, armazena no atributo comando e seta flag comando para 1
		 * se nao for, armazena no atributo label, e seta label para 1
		 * se comando ja tiver setado em um, só pode ser parametro. seta parametro para 1
		 * se parametro ja tiver setado, só pode ser segundo parametro
		 */
		else{
			std::cout << "WORD = " << buffer << std::endl;
			//buffer.clear();
			//caso seja palavra chave
			if(iskeyword(buffer) && !(buffer.empty())){
				flag_comando = 1;
				r_node.comando = buffer;
				buffer.clear();
			}
			//caso nao seja palavra chave e comando nao tenha sido encontrado ainda
			if(flag_comando == 0 && !(buffer.empty())){
				flag_label = 1;
				r_node.label = buffer;
				buffer.clear();
			}
			//caso comando ja tenha sido armazenado, prox palavra tem que ser parametro
			if(flag_comando == 1 && flag_parametro == 0 && !(buffer.empty())){
				flag_parametro = 1;
				r_node.parametro1 = buffer;
				buffer.clear();
			}
			//caso primeiro parametro ja exista
			if(flag_parametro == 1 && !(buffer.empty())){
				r_node.parametro2 = buffer;
				buffer.clear();
			}
			/*        ----------------------------       COMEÇO DO CODIGO ZUADO
			if(iskeyword(buffer)){
				flag_comando = 1;
				return_node.comando = buffer;
				buffer.clear();
			}
			else{
				//se nao for keyword e label for zero, entao é label
				if(flag_label == 0){
					flag_label = 1;
					return_node.label = buffer;
					buffer.clear();
				}
				else{
					//se comando e label ja existirem, entao é o primeiro parametro
					if(flag_parametro == 0){
						flag_parametro = 1;
						return_node.parametro1 = buffer;
						buffer.clear();
					}
					//se comando, label e o primeiro parametro ja existirem,
					//entao é o segundo parametro
					else{
						return_node.parametro2 = buffer;
						buffer.clear();
					}
				}
			}
			        -------------------------------      FIM DO CODIGO ZUADO   */
		}
			
	}
	return r_node;
}
Example #12
0
File: main.cpp Project: CCJY/coliru
void TickerInfoManager::put(std::string const& id, int total, int active) {
    SharedString shid(id.begin(), id.end(), pimpl_->m_alloc);

    lock_guard lock(pimpl_->mutex());
    pimpl_->map()[shid] = { total, active };
}
Example #13
0
static std::string unquote(std::string s)
{
	if(s.empty() || s[0] != '"' || s.size() <= 2)
		return s;
	return std::string(++s.begin(), --s.end());
}
Example #14
0
 void reverse()
 {
         std::reverse(spattern.begin(),spattern.end());
         pattern = spattern.c_str();
 }
int skill_string_to_enum(std::string skillname)
{
   std::transform(skillname.begin(), skillname.end(), skillname.begin(), ::tolower);
   if (skillname == "handtohand")
      return SKILL_HANDTOHAND;
   else if (skillname == "knife")
      return SKILL_KNIFE;
   else if (skillname == "sword")
      return SKILL_SWORD;
   else if (skillname == "club")
      return SKILL_CLUB;
   else if (skillname == "axe")
      return SKILL_AXE;
   else if (skillname == "throwing")
      return SKILL_THROWING;
   else if (skillname == "pistol")
      return SKILL_PISTOL;
   else if (skillname == "rifle")
      return SKILL_RIFLE;
   else if (skillname == "smg")
      return SKILL_SMG;
   else if (skillname == "shotgun")
      return SKILL_SHOTGUN;
   else if (skillname == "persuasion")
      return SKILL_PERSUASION;
   else if (skillname == "psychology")
      return SKILL_PSYCHOLOGY;
   else if (skillname == "law")
      return SKILL_LAW;
   else if (skillname == "security")
      return SKILL_SECURITY;
   else if (skillname == "disguise")
      return SKILL_DISGUISE;
   else if (skillname == "computers")
      return SKILL_COMPUTERS;
   else if (skillname == "tailoring")
      return SKILL_TAILORING;
   else if (skillname == "driving")
      return SKILL_DRIVING;
   else if (skillname == "writing")
      return SKILL_WRITING;
   else if (skillname == "music")
      return SKILL_MUSIC;
   else if (skillname == "art")
      return SKILL_ART;
   else if (skillname == "religion")
      return SKILL_RELIGION;
   else if (skillname == "science")
      return SKILL_SCIENCE;
   else if (skillname == "business")
      return SKILL_BUSINESS;
   else if (skillname == "stealth")
      return SKILL_STEALTH;
   else if (skillname == "teaching")
      return SKILL_TEACHING;
   else if (skillname == "streetsense")
      return SKILL_STREETSENSE;
   else if (skillname == "seduction")
      return SKILL_SEDUCTION;
   else if (skillname == "firstaid")
      return SKILL_FIRSTAID;
   else if (skillname == "dodge")
      return SKILL_DODGE;
   else if (skillname == "heavyweapons")
      return SKILL_HEAVYWEAPONS;
   else
      return -1;
}
Example #16
0
tstring OemToTChar(const std::string& text)
{
  tstring result(text.begin(), text.end());
  ::OemToChar(text.c_str(), &(result[0]));
  return result;
}
Example #17
0
class TestBase : public section::Base {

public:

  TestBase( double ZA, double AWR, int MT ) : Base( ZA, AWR, MT ) {};
  TestBase( const HEAD& head, int MAT, int MF ) : Base( head, MAT, MF ) {};
};

SCENARIO( "section::Base tests") {

  GIVEN( "a string representing the Section" ) {

    std::string line = chunk();
    auto begin = line.begin();
    auto end = line.end();
    long lineNumber = 2;
    auto head = StructureDivision( begin, end, lineNumber );

    std::unique_ptr<TestBase> base;
    WHEN( "given good MAT, MF numbers"){

      int MAT = 125;
      int MF = 3;
      THEN( "the base can be constructed without throwing" ) {

        REQUIRE_NOTHROW(
            base = std::make_unique<TestBase>( asHead(head), MAT, MF) );

        AND_THEN( "we can get the ZA, MT, and atomicWeightRatio" ) {
Example #18
0
tstring C2T(const std::string& text)
{
  return tstring(text.begin(), text.end());
}
Example #19
0
void postgresql_statement_backend::prepare(std::string const & query,
    statement_type stType)
{
#ifdef SOCI_POSTGRESQL_NOBINDBYNAME
    query_ = query;
#else
    // rewrite the query by transforming all named parameters into
    // the postgresql_ numbers ones (:abc -> $1, etc.)

    enum { normal, in_quotes, in_name } state = normal;

    std::string name;
    int position = 1;

    for (std::string::const_iterator it = query.begin(), end = query.end();
         it != end; ++it)
    {
        switch (state)
        {
        case normal:
            if (*it == '\'')
            {
                query_ += *it;
                state = in_quotes;
            }
            else if (*it == ':')
            {
                // Check whether this is a cast operator (e.g. 23::float)
                // and treat it as a special case, not as a named binding
                const std::string::const_iterator next_it = it + 1;
                if ((next_it != end) && (*next_it == ':'))
                {
                    query_ += "::";
                    ++it;
                }
                else
                {
                    state = in_name;
                }
            }
            else // regular character, stay in the same state
            {
                query_ += *it;
            }
            break;
        case in_quotes:
            if (*it == '\'')
            {
                query_ += *it;
                state = normal;
            }
            else // regular quoted character
            {
                query_ += *it;
            }
            break;
        case in_name:
            if (std::isalnum(*it) || *it == '_')
            {
                name += *it;
            }
            else // end of name
            {
                names_.push_back(name);
                name.clear();
                std::ostringstream ss;
                ss << '$' << position++;
                query_ += ss.str();
                query_ += *it;
                state = normal;

                // Check whether the named parameter is immediatelly
                // followed by a cast operator (e.g. :name::float)
                // and handle the additional colon immediately to avoid
                // its misinterpretation later on.
                if (*it == ':')
                {
                    const std::string::const_iterator next_it = it + 1;
                    if ((next_it != end) && (*next_it == ':'))
                    {
                        query_ += ':';
                        ++it;
                    }
                }
            }
            break;
        }
    }

    if (state == in_name)
    {
        names_.push_back(name);
        std::ostringstream ss;
        ss << '$' << position++;
        query_ += ss.str();
    }

#endif // SOCI_POSTGRESQL_NOBINDBYNAME

#ifndef SOCI_POSTGRESQL_NOPREPARE

    if (stType == st_repeatable_query)
    {
        statementName_ = session_.get_next_statement_name();

        PGresult * res = PQprepare(session_.conn_, statementName_.c_str(),
            query_.c_str(), static_cast<int>(names_.size()), NULL);
        if (res == NULL)
        {
            throw soci_error("Cannot prepare statement.");
        }
        ExecStatusType status = PQresultStatus(res);
        if (status != PGRES_COMMAND_OK)
        {
            throw_postgresql_soci_error(res);
        }
        PQclear(res);
    }

    stType_ = stType;

#endif // SOCI_POSTGRESQL_NOPREPARE
}
Example #20
0
    uint128::uint128(const std::string &sz) 
    :hi(0), lo(0) 
    {
      // do we have at least one character?
      if(!sz.empty()) {
        // make some reasonable assumptions
        int radix = 10;
        bool minus = false;

        std::string::const_iterator i = sz.begin();

        // check for minus sign, i suppose technically this should only apply
        // to base 10, but who says that -0x1 should be invalid?
        if(*i == '-') {
          ++i;
          minus = true;
        }

        // check if there is radix changing prefix (0 or 0x)
        if(i != sz.end()) {
          if(*i == '0') {
            radix = 8;
            ++i;
            if(i != sz.end()) {
              if(*i == 'x') {
                radix = 16;
                ++i;
              }
            }
          }

          while(i != sz.end()) {
            unsigned int n = 0;
            const char ch = *i;

            if(ch >= 'A' && ch <= 'Z') {
              if(((ch - 'A') + 10) < radix) {
                n = (ch - 'A') + 10;
              } else {
                break;
              }
            } else if(ch >= 'a' && ch <= 'z') {
              if(((ch - 'a') + 10) < radix) {
                n = (ch - 'a') + 10;
              } else {
                break;
              }
            } else if(ch >= '0' && ch <= '9') {
              if((ch - '0') < radix) {
                n = (ch - '0');
              } else {
                break;
              }
            } else {
              /* completely invalid character */
              break;
            }

            (*this) *= radix;
            (*this) += n;

            ++i;
          }
        }

        // if this was a negative number, do that two's compliment madness :-P
        if(minus) {
          *this = -*this;
        }
      }
    }
void Signature::setOptionsSignature( std::string fp )
{
    zeroStamp_ = true; //only matters if timestamp option is set
    std::string::iterator itr;
    for( itr = fp.begin(); itr != fp.end(); ++itr )
    {
        switch( tolower(*itr) )
        {

        case 'n': //NOOP
            tcpOptions_.push_back( TCPOption::NO_OPERATION );
            break;

        case 'e': //EOL
            tcpOptions_.push_back( TCPOption::END_OF_LIST );
            //TODO: might want to check if we are really at the end of list?
            break;

        case 's': //SACKOK
            tcpOptions_.push_back( TCPOption::SACK_PERMITTED );
            break;

        case 't': //TIMESTAMP
            tcpOptions_.push_back( TCPOption::TIME_STAMP_OPTION );
            if( *(itr + 1) != '0' )
                zeroStamp_ = false;
            break;

        case 'w': //window Scale
            tcpOptions_.push_back( TCPOption::WINDOW_SCALE );
            if( *(itr + 1) == '*' ) //Wildcard
            {
                wsc_ = 1;
                wscMod_ = MOD_CONST;
            }
            else if ( *(itr + 1) == '%' )
            {
                wscMod_ = MOD_CONST;
                wsc_ = ss_atoi<uint32_t>( fp.substr( itr+2 - fp.begin() ) );
            }
            else
            {
                wsc_ = ss_atoi<uint32_t>( fp.substr( itr+2 - fp.begin() ) );
            }
            break;

        case 'm': //Max Segment Size
            tcpOptions_.push_back( TCPOption::MAXIMUM_SEGMENT_SIZE );
            if( *(itr + 1) == '*' ) //Wildcard
            {
                mss_ = 1;
                mssMod_ = MOD_CONST;
            }
            else if ( *(itr + 1) == '%' )
            {
                mssMod_ = MOD_CONST;
                mss_ = ss_atoi<uint32_t>( fp.substr( itr+2 - fp.begin() ) );
            }
            else
            {
                mss_ = ss_atoi<uint32_t>( fp.substr( itr+2 - fp.begin() ) );
            }
            break;

        case '?': //Unknown (not really just not one of the ones we look at
            tcpOptions_.push_back( static_cast<uint8_t>( ss_atoi<uint16_t>( fp.substr( itr+1 - fp.begin() ) ) ) );
            break;

        default:
            throw std::runtime_error( "Unknown TCP option in config" );
        };
    }
}
Example #22
0
/// Make a string lowercase
std::string ToLower(std::string str) {
    std::transform(str.begin(), str.end(), str.begin(), ::tolower);
    return str;
}
Example #23
0
void StringExtend::ToLower (std::string& source)
{
    std::transform (source.begin (), source.end (), source.begin (), ::toupper);
}
Example #24
0
/// Make a string uppercase
std::string ToUpper(std::string str) {
    std::transform(str.begin(), str.end(), str.begin(), ::toupper);
    return str;
}
Example #25
0
inline void SaveHttpLogToFile(const std::string& url, const std::string& errMsg)
{
	SaveHttpLogToFile(url, std::vector<char>(errMsg.begin(), errMsg.end()));
}
Example #26
0
bool persist_file_context::clear_var(const std::string &global, bool immediate)
{
	config bak;
	config bactive;
	if (immediate) {
		bak = cfg_;
		config *node = get_node(bak, namespace_);
		if (node)
			bactive = node->child_or_add("variables");
		load();
	}
	config *active = get_node(cfg_, namespace_);
	if (active == NULL)
		return false;

	bool ret = active->has_child("variables");
	if (ret) {
		config &cfg = active->child("variables");
		bool exists = cfg.has_attribute(global);
		if (!exists) {
			if (cfg.has_child(global)) {
				exists = true;
				std::string::const_iterator index_start = std::find(global.begin(),global.end(),'[');
				if (index_start != global.end())
				{
					const std::string::const_iterator index_end = std::find(global.begin(),global.end(),']');
					const std::string index_str(index_start+1,index_end);
					size_t index = static_cast<size_t>(lexical_cast_default<int>(index_str));
					cfg.remove_child(global,index);
					if (immediate) bactive.remove_child(global,index);
				} else {
					cfg.clear_children(global);
					if (immediate) bactive.clear_children(global);
				}
			}
		}
		if (exists) {
			cfg.remove_attribute(global);
			if (immediate) bactive.remove_attribute(global);
			if (cfg.empty()) {
				active->clear_children("variables");
				active->remove_attribute("variables");
				name_space working = namespace_;
				while ((active->empty()) && (!working.lineage_.empty())) {
					name_space prev = working.prev();
					active = get_node(cfg_, prev);
					active->clear_children(working.node_);
					if (active->has_child("variables") && active->child("variables").empty()) {
						active->clear_children("variables");
						active->remove_attribute("variables");
					}
					working = prev;
				}
			}

			if (!in_transaction_)
				ret = save_context();
			else if (immediate) {
				ret = save_context();
				cfg_ = bak;
				active = get_node(cfg_, namespace_);
				if (active != NULL) {
					active->clear_children("variables");
					active->remove_attribute("variables");
					if (!bactive.empty())
						active->add_child("variables",bactive);
				}
			} else {
				ret = true;
			}
		} else {
			if (immediate) {
				cfg_ = bak;
				config *active = get_node(cfg_, namespace_);
				if (active != NULL) {
					active->clear_children("variables");
					active->remove_attribute("variables");
					if (!bactive.empty())
						active->add_child("variables",bactive);
				}
			}
			ret = exists;
		}
	}

	// TODO: figure out when this is the case and adjust the next loop
	//       condition accordingly. -- shadowm
	assert(active);

	while (active && active->empty() && !namespace_.lineage_.empty()) {
		name_space prev = namespace_.prev();
		active = get_node(cfg_, prev);
		if (active == NULL) {
			break;
		}
		active->clear_children(namespace_.node_);
		if (active->has_child("variables") && active->child("variables").empty()) {
			active->clear_children("variables");
			active->remove_attribute("variables");
		}
		namespace_ = prev;
	}
	return ret;
}