text:
#include <pcl/io/pcd_io.h>  //PCD相关头文件
#include <pcl/point_types.h>
#include <pcl/search/search.h>
#include <pcl/search/kdtree.h>
#include <pcl/features/normal_3d.h>
#include <pcl/filters/filter.h>
#include <pcl/filters/voxel_grid.h>
#include <pcl/registration/icp_nl.h>

#include <boost/program_options.hpp>
#include <iostream>
#include <string>
#include <filesystem>
#include <vector>
#include <algorithm>

namespace bpo = ::boost::program_options;
namespace fs = std::filesystem;
using PointT = pcl::PointXYZ;                 // x,y,z点
using PointCloudT = pcl::PointCloud<PointT>;  //点云　申明pcl::PointXYZ数据
using PointWithNormalT = pcl::PointNormal;

int main(int argc, char** argv) {
    // prase command line options
    std::string filepath_in;
    std::string filename_out;
    {
        bpo::options_description desc("Allowed options");
        desc.add_options()
            ("in,i", bpo::value<std::string>(&filepath_in), "input pcd file path !!! NOT FILE NAME !!!")
            ("out,o", bpo::value<std::string>(&filename_out), "output file name")
            ("help,h", "icp -i <input-filepath> -o <output-filename>");
        bpo::variables_map vm;

        try
        {
            bpo::store(bpo::parse_command_line(argc, argv, desc), vm);
        } catch (const std::exception& e) {
            std::cerr << e.what() << std::endl;
            std::cerr << desc << std::endl;
            return -1;
        }
        bpo::notify(vm);

        if(!(vm.count("in") && vm.count("out")))
        {
            std::cerr << desc << std::endl;
            return -1;
        }
    }

    // sort file name in right order
    std::vector<std::string> filenames_in;
    {
        if(!fs::exists(filepath_in))
        {
            std::cerr << "Cannot open dir " << filepath_in << std::endl;
            return -1;
        }
        for(const auto& entry : fs::directory_iterator(filepath_in))
        {
            filenames_in.push_back(entry.path());
        }
        std::sort(filenames_in.begin(), filenames_in.end());
    }

    // load file
    std::vector<PointCloudT::Ptr> clouds_in;
    {
        std::cout << "Loading pcd files" << std::endl;
        pcl::Indices indices_nan;
        for(const auto& name : filenames_in)
        {
            clouds_in.emplace_back(new PointCloudT);
            if(pcl::io::loadPCDFile(name, *clouds_in.back()) == -1)
            {
                std::cerr << "PCD File load error " << name << std::endl;
                return -1;
            }
            pcl::removeNaNFromPointCloud<PointT>(
                *clouds_in.back(), *clouds_in.back(), indices_nan);

            std::cout << name << " points num:" << clouds_in.back()->size() << std::endl;
        }

        std::cout << "\nSuccess load " << clouds_in.size() << " cloud" << std::endl;
    }

    // do icp
    PointCloudT::Ptr cloud_all(new PointCloudT);
    {
        // search method kdtree
        pcl::search::Search<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);

        // down sample
        pcl::VoxelGrid<PointT> vg;
        vg.setLeafSize(0.1, 0.1, 0.1);
        vg.setDownsampleAllData(true);

        // cal Normal
        pcl::NormalEstimation<PointT, PointWithNormalT> ne;
        ne.setKSearch(30);
        ne.setSearchMethod(tree);

        // icp
        pcl::IterativeClosestPointNonLinear<PointWithNormalT, PointWithNormalT> icp_nl;
        icp_nl.setTransformationEpsilon(1e-6);
        icp_nl.setMaxCorrespondenceDistance(0.05);
        icp_nl.setMaximumIterations(2);

        pcl::PointCloud<PointWithNormalT>::Ptr cloud_src(new pcl::PointCloud<PointWithNormalT>);
        pcl::PointCloud<PointWithNormalT>::Ptr cloud_tgt(new pcl::PointCloud<PointWithNormalT>);
        Eigen::Matrix4f T_cur, T_prv, T_all;
        for (auto& cloud_in : clouds_in) {
            vg.setInputCloud(cloud_in);
            vg.filter(*cloud_in);

            ne.setInputCloud(cloud_in);
            ne.compute(*cloud_src);
            pcl::copyPointCloud(*cloud_in, *cloud_src);

            if(!cloud_all->empty())
            {
                T_all = T_all.Identity();
                icp_nl.setInputTarget(cloud_tgt);
                for (int i = 0; i < 30; i++)
                {
                    icp_nl.setInputSource(cloud_src);
                    icp_nl.align(*cloud_src);
                    T_all = icp_nl.getFinalTransformation() * T_all;
                    T_cur = icp_nl.getLastIncrementalTransformation();
                    if(fabs((T_cur-T_prv).sum()) < icp_nl.getTransformationEpsilon())
                        icp_nl.setMaxCorrespondenceDistance(icp_nl.getMaxCorrespondenceDistance() - 0.001);
                    else
                        break;
                    T_prv = T_cur;
                }
                pcl::transformPointCloud(*cloud_in, *cloud_in, T_all);
            }

            *cloud_all += *cloud_in;
            // make this loop's tgt's space to get next loop's data
            // and save this loop's src's data to tgt without copying any data
            std::swap(cloud_tgt, cloud_src);
        }

        // down samle cloud_all, because too many duplicate points
        vg.setInputCloud(cloud_all);
        vg.filter(*cloud_all);
    }

    pcl::io::savePCDFile(filename_out, *cloud_all);

    return 0;
}

max_stars_repo_name: HopeCollector/SLAMResearch

max_issues_repo_name: HopeCollector/SLAMResearch

max_forks_repo_name: HopeCollector/SLAMResearch


text:
/**
 *  @file
 *  @copyright defined in eos/LICENSE.txt
 */

#include <eosio/testing/tester.hpp>
#include <eosio/chain/global_property_object.hpp>
#include <fc/crypto/digest.hpp>
#include <boost/container/flat_set.hpp>
#include <eosio/chain/types.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/algorithm/string.hpp>

#ifdef NON_VALIDATING_TEST
#define TESTER tester
#else
#define TESTER validating_tester
#endif

using namespace eosio::chain;
using namespace eosio::testing;
namespace bfs = boost::filesystem;

BOOST_AUTO_TEST_SUITE(database_gmr_blklst_tests)

vector<name> parse_list_string(string items)
{
   vector<name> item_list;
   vector<string> itemlist;
   boost::split(itemlist, items, boost::is_any_of(","));
   for (string item : itemlist)
   {
      item_list.push_back(string_to_name(item.c_str()));
   }

   return item_list;
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(list_config_parse_test)
{
   try
   {
      TESTER test;

      string str = "alice,bob,tom";
      vector<name> list = parse_list_string(str);
      BOOST_TEST(list.size() > 0);
      account_name n = N(a);
      if (list.size() > 0)
      {
         n = *(list.begin());
      }

      BOOST_TEST(n != N(a));
      BOOST_TEST(n == N(alice));
   }
   FC_LOG_AND_RETHROW()
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(set_name_list_test)
{
   try
   {
      TESTER test;
      // Bypass read-only restriction on state DB access for this unit test which really needs to mutate the DB to properly conduct its test.
      chainbase::database &db = const_cast<chainbase::database &>(test.control->db());

      auto ses = db.start_undo_session(true);

      string str = "alice,bob,tom";
      vector<name> list = parse_list_string(str);

      flat_set<account_name> nameset(list.begin(), list.end());
         // Create an account
         db.create<account_object>([](account_object &a) {
            a.name = "alice";
         });

      test.control->add_resource_greylist(N(alice));

      // Make sure we can retrieve that account by name
      const global_property2_object &ptr = db.get<global_property2_object>();

      // Create an account
      db.modify(ptr, [&](global_property2_object &a) {
         // a.cfg.actor_blacklist = {N(a)};
         // a.cfg.contract_blacklist = {N(a)};
         // a.cfg.resource_greylist = {N(a)};
      });

      int64_t lt = static_cast<int64_t>(list_type::resource_greylist_type);
      int64_t lat = static_cast<int64_t>(list_action_type::insert_type);
      test.control->set_name_list(lt, lat, list);

       const flat_set<account_name>&  ab =  test.control->get_actor_blacklist();
       const flat_set<account_name>&  cb =  test.control->get_contract_blacklist();
       const flat_set<account_name>&  rg =  test.control->get_resource_greylist();

      auto convert_names = [&](const shared_vector<name>& namevec, flat_set<account_name>& nameset) -> void {
        for(const auto& a :namevec)
        {
           nameset.insert(uint64_t(a));
        }
      };

      flat_set<account_name> aab;
      flat_set<account_name> acb;
      flat_set<account_name> arg;

      const global_property2_object &ptr1 = db.get<global_property2_object>();
      chain_config2 c = ptr1.cfg;

      BOOST_TEST(c.resource_greylist.size() == 3);
      BOOST_TEST(rg.size() == 3);

      convert_names(c.actor_blacklist, aab);
      convert_names(c.contract_blacklist, acb);
      convert_names(c.resource_greylist, arg);

      if (c.resource_greylist.size() == 1)
      {

         // bool b = (aab.find(N(a)) != aab.end());
         // BOOST_TEST(b);
      }

      // bool d = ab.find(N(a)) != ab.end();
      // BOOST_TEST(d);
      bool m = arg.find(N(alice)) != arg.end();
      BOOST_TEST(m);

      // Undo creation of the account
      ses.undo();

   }
   FC_LOG_AND_RETHROW()
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(actor_blacklist_config_test)
{
   try
   {
      TESTER test;
      // Bypass read-only restriction on state DB access for this unit test which really needs to mutate the DB to properly conduct its test.
      chainbase::database &db = const_cast<chainbase::database &>(test.control->db());

      auto ses = db.start_undo_session(true);

      //   string str= "alice,bob,tom";
      //   vector<name> list = parse_list_string(str);

      // Make sure we can retrieve that account by name
      const global_property2_object &ptr = db.get<global_property2_object>();

      // Create an account
      db.modify(ptr, [&](global_property2_object &a) {
         a.cfg.actor_blacklist = {N(a)};
      });

      chain_config2 a = ptr.cfg;

      account_name v;
      if (a.actor_blacklist.size() > 0)
      {
         v = *(a.actor_blacklist.begin());
      }

      std::size_t s = a.actor_blacklist.size();

      BOOST_TEST(1 == s);

      BOOST_TEST(v == N(a));

      // Undo creation of the account
      ses.undo();

   }
   FC_LOG_AND_RETHROW()
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(contract_blacklist_config_test)
{
   try
   {
      TESTER test;
      // Bypass read-only restriction on state DB access for this unit test which really needs to mutate the DB to properly conduct its test.
      chainbase::database &db = const_cast<chainbase::database &>(test.control->db());

      auto ses = db.start_undo_session(true);

      //   string str= "alice,bob,tom";
      //   vector<name> list = parse_list_string(str);

      // Make sure we can retrieve that account by name
      const global_property2_object &ptr = db.get<global_property2_object>();

      // Create an account
      db.modify(ptr, [&](global_property2_object &a) {
         a.cfg.contract_blacklist = {N(a)};
      });

      chain_config2 a = ptr.cfg;

       account_name v ;
      if (a.contract_blacklist.size() > 0)
      {
         v = *(a.contract_blacklist.begin());
      }

      std::size_t s = a.contract_blacklist.size();

      BOOST_TEST(1 == s);

      BOOST_TEST(v == N(a));

      // Undo creation of the account
      ses.undo();

   }
   FC_LOG_AND_RETHROW()
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(resource_greylist_config_test)
{
   try
   {
      TESTER test;
      // Bypass read-only restriction on state DB access for this unit test which really needs to mutate the DB to properly conduct its test.
      chainbase::database &db = const_cast<chainbase::database &>(test.control->db());

      auto ses = db.start_undo_session(true);

      //   string str= "alice,bob,tom";
      //   vector<name> list = parse_list_string(str);

      // Make sure we can retrieve that account by name
      const global_property2_object &ptr = db.get<global_property2_object>();

      // Create an account
      db.modify(ptr, [&](global_property2_object &a) {
         a.cfg.resource_greylist = {N(a)};
      });

      chain_config2 a = ptr.cfg;

      account_name v ;
      if (a.resource_greylist.size() > 0)
      {
         v = *(a.resource_greylist.begin());
      }

    std::size_t s = a.resource_greylist.size();

      BOOST_TEST(1 == s);

      BOOST_TEST(v == N(a));

      // Undo creation of the account
      ses.undo();

   }
   FC_LOG_AND_RETHROW()
}

// Simple tests of undo infrastructure
BOOST_AUTO_TEST_CASE(gmrource_limit_config_test)
{
   try
   {
      TESTER test;
      // Bypass read-only restriction on state DB access for this unit test which really needs to mutate the DB to properly conduct its test.
      chainbase::database &db = const_cast<chainbase::database &>(test.control->db());

      auto ses = db.start_undo_session(true);

      // Make sure we can retrieve that account by name
      const global_property2_object &ptr = db.get<global_property2_object>();

      // Create an account
      db.modify(ptr, [&](global_property2_object &a) {
         a.gmr.cpu_us = 100;
         a.gmr.net_byte = 1024;
         a.gmr.ram_byte = 1;
      });

      BOOST_TEST(ptr.gmr.cpu_us == 100);
      BOOST_TEST(ptr.gmr.net_byte == 1024);
      BOOST_TEST(ptr.gmr.ram_byte == 1);

      // Undo creation of the account
      ses.undo();

   }
   FC_LOG_AND_RETHROW()
}

BOOST_AUTO_TEST_SUITE_END()

ext: cpp

max_stars_repo_name: vlbos/bos

max_issues_repo_name: vlbos/bos

max_forks_repo_name: vlbos/bos


text:
// Copyright 2021
// Author: Ayvar Aleksiev

#include "endpoint/NotesEndpoint.h"
#include "endpoint/MainEndpoint.h"
#include "endpoint/UserEndpoint.h"
#include "endpoint/InvalidEndpoint.h"
#include "utils/Logger.h"

#include <boost/program_options.hpp>
#include <restinio/all.hpp>
#include <restinio/sync_chain/growable_size.hpp>
#include <restinio/tls.hpp>

#include <iostream>

using namespace boost::program_options;

int main(int argc, char* argv[])
{
	try
	{
		/*
		 * Program options.
		 */
		std::string certDir;
		options_description desc{ "Options" };
		desc.add_options()
			(",h", "Help screen.")
			("certDir", value<std::string>(&certDir), "[Required] Absolute path to certificate directory.");

		variables_map varMap;
		store(parse_command_line(argc, argv, desc), varMap);
		notify(varMap);
		if ((argc < 2) || (varMap.count("help")) || (varMap.count("certDir") < 0)) {
			std::cout << desc << '\n';
			return 0;
		}

		/*
       * Server configuration.
       */
		using traits_t =
			restinio::single_thread_tls_traits_t<
			restinio::asio_timer_manager_t,
			Notes::Utils::Logger,
			restinio::sync_chain::growable_size_chain_t<>>;

		restinio::sync_chain::growable_size_chain_t<>::builder_t chain_builder;
		chain_builder.add(Notes::NotesEndpoint::getInstance()->createNoteEndpointRequestHandler());
		chain_builder.add(Notes::MainEndpoint::getInstance()->createMainEndpointRequestHandler());
		chain_builder.add(Notes::UserEndpoint::getInstance()->createUserEndpointRequestHandler());
		// The invalid endpoint handler should be added last, otherwise all handlers are returning bad request.
		chain_builder.add(Notes::InvalidEndpoint::getInstance()->createInvalidEndpointRequestHandler());

		auto asyncServer =
		   restinio::run_async(
		      restinio::own_io_context(),
		      restinio::server_settings_t< traits_t >{}
	              .port(9066)
	              .address("localhost")
	              .logger(Notes::Utils::createLogger("restinio"))
	              .request_handler(chain_builder.release())
	              .tls_context(std::move(Notes::Utils::createTlsContext(std::move(certDir)))),
		      // Threadpool size for the HTTP server.
		      std::thread::hardware_concurrency());

		while (true) {
			// Keep program alive.
		}
	}
	catch (const std::exception& ex)
	{
		std::cerr << "Failed to start server. Error: " << ex.what() << std::endl;
	}

	return 0;
}


text:
/*
 * Distributed under the Boost Software License, Version 1.0.
 * (See accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * Copyright (c) 2009 Helge Bahmann
 * Copyright (c) 2012 Tim Blechmann
 * Copyright (c) 2013 - 2014 Andrey Semashev
 */
/*!
 * \file   atomic/detail/bitwise_cast.hpp
 *
 * This header defines \c bitwise_cast used to convert between storage and value types
 */

#ifndef BOOST_ATOMIC_DETAIL_BITWISE_CAST_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_BITWISE_CAST_HPP_INCLUDED_

#include <boost/atomic/detail/config.hpp>
#if !defined(BOOST_ATOMIC_DETAIL_HAS_BUILTIN_MEMCPY)
#include <cstring>
#endif

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

namespace boost {
namespace atomics {
namespace detail {

template< typename T >
BOOST_FORCEINLINE T* addressof(T& value) BOOST_NOEXCEPT
{
    // Note: The point of using a local struct as the intermediate type instead of char is to avoid gcc warnings
    // if T is a const volatile char*:
    // warning: casting ‘const volatile char* const’ to ‘const volatile char&’ does not dereference pointer
    // The local struct makes sure T is not related to the cast target type.
    struct opaque_type;
    return reinterpret_cast< T* >(&const_cast< opaque_type& >(reinterpret_cast< const volatile opaque_type& >(value)));
}

template< typename To, typename From >
BOOST_FORCEINLINE To bitwise_cast(From const& from) BOOST_NOEXCEPT
{
    struct
    {
        To to;
    }
    value = {};
    BOOST_ATOMIC_DETAIL_MEMCPY
    (
        atomics::detail::addressof(value.to),
        atomics::detail::addressof(from),
        (sizeof(From) < sizeof(To) ? sizeof(From) : sizeof(To))
    );
    return value.to;
}

} // namespace detail
} // namespace atomics
} // namespace boost

#endif // BOOST_ATOMIC_DETAIL_BITWISE_CAST_HPP_INCLUDED_

ext: hpp


text:
/*
 *
 * Copyright (c) 1998-2002
 * Dr John Maddock
 *
 * Use, modification and distribution are subject to the
 * Boost Software License, Version 1.0. (See accompanying file
 * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
 *
 */

 /*
  *   LOCATION:    see http://www.boost.org for most recent version.
  *   FILE         regex_traits.hpp
  *   VERSION      see <boost/version.hpp>
  *   DESCRIPTION: Declares regular expression traits classes.
  */

#ifndef BOOST_REGEX_TRAITS_HPP_INCLUDED
#define BOOST_REGEX_TRAITS_HPP_INCLUDED

#ifndef BOOST_RE_CREGEX_HPP
#include <boost/cregex.hpp>
#endif
#ifndef BOOST_REGEX_CSTRING_HPP
#include <boost/regex/v4/regex_cstring.hpp>
#endif

namespace boost{

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_PREFIX
#endif

template <class charT>
class c_regex_traits;

namespace re_detail{

struct mss
{
   unsigned int id;
   const char* what;
};

BOOST_REGEX_DECL bool BOOST_REGEX_CALL re_lookup_def_collate_name(std::string& buf, const char* name);
BOOST_REGEX_DECL std::size_t BOOST_REGEX_CALL re_get_default_message(char* buf, std::size_t len, std::size_t id);
extern BOOST_REGEX_DECL const char *re_default_error_messages[];

#ifndef BOOST_NO_WREGEX
extern BOOST_REGEX_DECL regex_wchar_type wide_lower_case_map[];
extern BOOST_REGEX_DECL unsigned short wide_unicode_classes[];
BOOST_REGEX_DECL bool BOOST_REGEX_CALL is_combining(regex_wchar_type c);
#endif

struct BOOST_REGEX_DECL regex_traits_base
{
   enum char_syntax_type
   {
      syntax_char = 0,
      syntax_open_bracket = 1,                  // (
      syntax_close_bracket = 2,                 // )
      syntax_dollar = 3,                        // $
      syntax_caret = 4,                         // ^
      syntax_dot = 5,                           // .
      syntax_star = 6,                          // *
      syntax_plus = 7,                          // +
      syntax_question = 8,                      // ?
      syntax_open_set = 9,                      // [
      syntax_close_set = 10,                    // ]
      syntax_or = 11,                           // |
      syntax_slash = 12,                        //
      syntax_hash = 13,                         // #
      syntax_dash = 14,                         // -
      syntax_open_brace = 15,                   // {
      syntax_close_brace = 16,                  // }
      syntax_digit = 17,                        // 0-9
      syntax_b = 18,                            // for \b
      syntax_B = 19,                            // for \B
      syntax_left_word = 20,                    // for \<
      syntax_right_word = 21,                   // for \>
      syntax_w = 22,                            // for \w
      syntax_W = 23,                            // for \W
      syntax_start_buffer = 24,                 // for \`
      syntax_end_buffer = 25,                   // for \'
      syntax_newline = 26,                      // for newline alt
      syntax_comma = 27,                        // for {x,y}

      syntax_a = 28,                            // for \a
      syntax_f = 29,                            // for \f
      syntax_n = 30,                            // for \n
      syntax_r = 31,                            // for \r
      syntax_t = 32,                            // for \t
      syntax_v = 33,                            // for \v
      syntax_x = 34,                            // for \xdd
      syntax_c = 35,                            // for \cx
      syntax_colon = 36,                        // for [:...:]
      syntax_equal = 37,                        // for [=...=]

      // perl ops:
      syntax_e = 38,                            // for \e
      syntax_l = 39,                            // for \l
      syntax_L = 40,                            // for \L
      syntax_u = 41,                            // for \u
      syntax_U = 42,                            // for \U
      syntax_s = 43,                            // for \s
      syntax_S = 44,                            // for \S
      syntax_d = 45,                            // for \d
      syntax_D = 46,                            // for \D
      syntax_E = 47,                            // for \Q\E
      syntax_Q = 48,                            // for \Q\E
      syntax_X = 49,                            // for \X
      syntax_C = 50,                            // for \C
      syntax_Z = 51,                            // for \Z
      syntax_G = 52,                            // for \G

      // new extentions:
      syntax_not = 53,                          // for (?!...)

      syntax_max = 54
   };
#ifdef __BORLANDC__
private:
   char dummy_member;
#endif
};

struct BOOST_REGEX_DECL c_traits_base : public regex_traits_base
{
public:
   enum{
      char_class_none = 0,
      char_class_alpha = 0x0001,
      char_class_cntrl = 0x0002,
      char_class_digit = 0x0004,
      char_class_lower = 0x0008,
      char_class_punct = 0x0010,
      char_class_space = 0x0020,
      char_class_upper = 0x0040,
      char_class_xdigit = 0x0080,
      char_class_blank = 0x0100,
      char_class_underscore = 0x4000,
      char_class_unicode = 0x8000,

      char_class_alnum = char_class_alpha | char_class_digit,
      char_class_graph = char_class_alpha | char_class_digit | char_class_punct | char_class_underscore,
      char_class_print = char_class_alpha | char_class_digit | char_class_punct | char_class_underscore | char_class_blank,
      char_class_word = char_class_alpha | char_class_digit | char_class_underscore
   };
   static std::string BOOST_REGEX_CALL set_message_catalogue(const std::string& s);
protected:
#if defined(__MWERKS__) && __MWERKS__ <= 0x6000
   friend class c_regex_traits<char>;
   friend class c_regex_traits<regex_wchar_type>;
#endif

   static char regex_message_catalogue[BOOST_REGEX_MAX_PATH];
   enum syntax_map_size
   {
      map_size = UCHAR_MAX + 1
   };

   static unsigned char syntax_map[map_size];
   static unsigned short class_map[map_size];
   static char lower_case_map[map_size];

   static boost::uint_fast32_t BOOST_REGEX_CALL do_lookup_class(const char* p);
   static bool BOOST_REGEX_CALL do_lookup_collate(std::string& buf, const char* p);
   static void BOOST_REGEX_CALL do_update_ctype();
   static void BOOST_REGEX_CALL do_update_collate();
public:
   static std::string BOOST_REGEX_CALL error_string(unsigned id);
   static char* BOOST_REGEX_CALL get_catalogue() { return regex_message_catalogue; }
};

} // namespace re_detail

template<>
class BOOST_REGEX_DECL c_regex_traits<char> : public re_detail::c_traits_base
{
   typedef re_detail::c_traits_base base_type;
public:
   typedef char char_type;
   typedef unsigned char uchar_type;
   typedef unsigned int size_type;
   typedef std::string string_type;
   typedef int locale_type;

   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::strlen(p);
   }
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c)
   {
      return syntax_map[c];
   }
   static char BOOST_REGEX_CALL translate(char c, bool icase)
   {
      return icase ? lower_case_map[(size_type)(uchar_type)c] : c;
   }
   static void BOOST_REGEX_CALL transform(std::string& out, const std::string& in);

   static void BOOST_REGEX_CALL transform_primary(std::string& out, const std::string& in);

   static bool BOOST_REGEX_CALL is_separator(char c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == '\n') || (c == '\r'));
   }

   static bool BOOST_REGEX_CALL is_combining(char)
   {
      return false;
   }

   static bool BOOST_REGEX_CALL is_class(char c, boost::uint_fast32_t f)
   {
      return BOOST_REGEX_MAKE_BOOL(class_map[(size_type)(uchar_type)c] & f);
   }

   static int BOOST_REGEX_CALL toi(char c);
   static int BOOST_REGEX_CALL toi(const char*& first, const char* last, int radix);

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const char* first, const char* last)
   {
      std::string s(first, last);
      return do_lookup_class(s.c_str());
   }

   static bool BOOST_REGEX_CALL lookup_collatename(std::string& buf, const char* first, const char* last)
   {
      std::string s(first, last);
      return do_lookup_collate(buf, s.c_str());
   }

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }
   void swap(c_regex_traits&){}

   c_regex_traits()
   {
      init();
   }
   ~c_regex_traits()
   {
      m_free();
   }
   struct sentry
   {
      sentry(const c_regex_traits<char>&)
      { c_regex_traits<char>::update(); }
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update();
private:
   static void BOOST_REGEX_CALL init();
   static void BOOST_REGEX_CALL m_free();
   static c_regex_traits<char> i;

   static unsigned sort_type;
   static char sort_delim;
};

#ifndef BOOST_NO_WREGEX
template<>
class BOOST_REGEX_DECL c_regex_traits<regex_wchar_type> : public re_detail::c_traits_base
{
   typedef re_detail::c_traits_base base_type;
public:
   typedef regex_wchar_type char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<regex_wchar_type> string_type;
   typedef int locale_type;
#ifndef BOOST_REGEX_HAS_SHORT_WCHAR_T
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(p);
   }
#else
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(reinterpret_cast<const wchar_t*>(p));
   }
#endif
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c);
   static regex_wchar_type BOOST_REGEX_CALL translate(regex_wchar_type c, bool icase)
   {
      return icase ? ((c < 256) ? re_detail::wide_lower_case_map[(uchar_type)c] : std::towlower(c)) : c;
   }

   static void BOOST_REGEX_CALL transform(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in);

   static void BOOST_REGEX_CALL transform_primary(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in);

   static bool BOOST_REGEX_CALL is_separator(regex_wchar_type c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == L'\n') || (c == L'\r') || (c == (regex_wchar_type)0x2028) || (c == (regex_wchar_type)0x2029));
   }

   static bool BOOST_REGEX_CALL is_combining(regex_wchar_type c)
   { return re_detail::is_combining(c); }

   static bool BOOST_REGEX_CALL is_class(regex_wchar_type c, boost::uint_fast32_t f)
   {
      return BOOST_REGEX_MAKE_BOOL(((uchar_type)c < 256) ? (re_detail::wide_unicode_classes[(size_type)(uchar_type)c] & f) : do_iswclass(c, f));
   }

   static int BOOST_REGEX_CALL toi(regex_wchar_type c);
   static int BOOST_REGEX_CALL toi(const regex_wchar_type*& first, const regex_wchar_type* last, int radix);

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const regex_wchar_type* first, const regex_wchar_type* last);

   static bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<regex_wchar_type>& s, const regex_wchar_type* first, const regex_wchar_type* last);

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }
   void swap(c_regex_traits&){}
   c_regex_traits<regex_wchar_type>()
   { init(); }
   ~c_regex_traits<regex_wchar_type>()
   { m_free(); }
   struct sentry
   {
      sentry(const c_regex_traits<regex_wchar_type>&)
      { c_regex_traits<regex_wchar_type>::update(); }
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update();
   static std::size_t BOOST_REGEX_CALL strnarrow(char *s1, std::size_t len, const regex_wchar_type *s2);
   static std::size_t BOOST_REGEX_CALL strwiden(regex_wchar_type *s1, std::size_t len, const char *s2);
private:
   static bool BOOST_REGEX_CALL do_iswclass(regex_wchar_type c, boost::uint_fast32_t f);
   static void BOOST_REGEX_CALL m_free();
   static void BOOST_REGEX_CALL init();
   static bool BOOST_REGEX_CALL do_lookup_collate(std::basic_string<regex_wchar_type>& out, const regex_wchar_type* first, const regex_wchar_type* last);
   static c_regex_traits<regex_wchar_type> init_;

   static unsigned sort_type;
   static regex_wchar_type sort_delim;
};

#ifdef BOOST_REGEX_HAS_SHORT_WCHAR_T
//
// What follows here is Visual Studio specific - it is a thin wrapper
// that redirects calls to c_regex_traits<unsigned short> to
// c_regex_traits<__wchar_t>.  This allows the library to be built
// so that it supports programs built both with and without /Zc:wchar_t.
//
template<>
class c_regex_traits<unsigned short> : public re_detail::c_traits_base
{
   typedef re_detail::c_traits_base base_type;
public:
   typedef unsigned short char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<unsigned short> string_type;
   typedef int locale_type;
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return c_regex_traits<regex_wchar_type>::length(
         reinterpret_cast<const regex_wchar_type*>(p));
   }
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c)
   {
      return c_regex_traits<regex_wchar_type>::syntax_type(c);
   }
   static unsigned short BOOST_REGEX_CALL translate(unsigned short c, bool icase)
   {
      return c_regex_traits<regex_wchar_type>::translate(c, icase);
   }

   static void BOOST_REGEX_CALL transform(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)
   {
      c_regex_traits<regex_wchar_type>::transform(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in));
   }

   static void BOOST_REGEX_CALL transform_primary(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)
   {
      c_regex_traits<regex_wchar_type>::transform_primary(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in)); }

   static bool BOOST_REGEX_CALL is_separator(unsigned short c)
   {
      return c_regex_traits<regex_wchar_type>::is_separator(c);
   }

   static bool BOOST_REGEX_CALL is_combining(unsigned short c)
   {
      return c_regex_traits<regex_wchar_type>::is_combining(c);
   }

   static bool BOOST_REGEX_CALL is_class(unsigned short c, boost::uint_fast32_t f)
   {
      return c_regex_traits<regex_wchar_type>::is_class(c, f);
   }

   static int BOOST_REGEX_CALL toi(unsigned short c)
   {
      return c_regex_traits<regex_wchar_type>::toi(c);
   }
   static int BOOST_REGEX_CALL toi(const unsigned short*& first, const unsigned short* last, int radix)
   {
      return c_regex_traits<regex_wchar_type>::toi(
         reinterpret_cast<const regex_wchar_type*&>(first),
         reinterpret_cast<const regex_wchar_type*>(last),
         radix);
   }

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const unsigned short* first, const unsigned short* last)
   {
      return c_regex_traits<regex_wchar_type>::lookup_classname(
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   static bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<unsigned short>& s, const unsigned short* first, const unsigned short* last)
   {
      return c_regex_traits<regex_wchar_type>::lookup_collatename(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(s),
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }

   struct sentry
   {
      sentry(const c_regex_traits<unsigned short>&)
      { c_regex_traits<unsigned short>::update(); }
      ~sentry(){}
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update()
   {
      c_regex_traits<regex_wchar_type>::update();
   }
   void swap(c_regex_traits&){}
   c_regex_traits(){};
   ~c_regex_traits(){};
   static std::size_t BOOST_REGEX_CALL strnarrow(char *s1, std::size_t len, const unsigned short *s2)
   {
      return c_regex_traits<regex_wchar_type>::strnarrow(
         s1,
         len,
         reinterpret_cast<const regex_wchar_type *>(s2));
   }
   static std::size_t BOOST_REGEX_CALL strwiden(unsigned short *s1, std::size_t len, const char *s2)
   {
      return c_regex_traits<regex_wchar_type>::strwiden(
         reinterpret_cast<regex_wchar_type *>(s1), len, s2);
   }

private:
   c_regex_traits<regex_wchar_type> m_init;

};

#endif // BOOST_REGEX_HAS_SHORT_WCHAR_T

#endif // wide characters

#if defined(_WIN32) && !defined(BOOST_REGEX_NO_W32)

namespace re_detail{

struct BOOST_REGEX_DECL w32_traits_base : public regex_traits_base
{
   enum{
   char_class_none = 0,
   char_class_alnum = C1_ALPHA | C1_DIGIT,
   char_class_alpha = C1_ALPHA,
   char_class_cntrl = C1_CNTRL,
   char_class_digit = C1_DIGIT,
   char_class_graph = C1_UPPER | C1_LOWER | C1_DIGIT | C1_PUNCT | C1_ALPHA,
   char_class_lower = C1_LOWER,
   char_class_print = C1_UPPER | C1_LOWER | C1_DIGIT | C1_PUNCT | C1_BLANK | C1_ALPHA,
   char_class_punct = C1_PUNCT,
   char_class_space = C1_SPACE,
   char_class_upper = C1_UPPER,
   char_class_xdigit = C1_XDIGIT,
   char_class_blank = C1_BLANK,
   char_class_underscore = 0x4000,
   char_class_word = C1_ALPHA | C1_DIGIT | char_class_underscore,
   char_class_unicode = 0x8000,
   char_class_win = 0x01FF
   };

public:
   static std::string BOOST_REGEX_CALL set_message_catalogue(const std::string& s);
protected:
   static char regex_message_catalogue[BOOST_REGEX_MAX_PATH];
   enum syntax_map_size
   {
      map_size = UCHAR_MAX + 1
   };

   static unsigned char syntax_map[map_size];
   static unsigned short class_map[map_size];
   static char lower_case_map[map_size];

   static boost::uint_fast32_t BOOST_REGEX_CALL do_lookup_class(const char* p);
   static bool BOOST_REGEX_CALL do_lookup_collate(std::string& buf, const char* p);
   static void BOOST_REGEX_CALL do_free();
   static void BOOST_REGEX_CALL do_init();
public:
   static std::string BOOST_REGEX_CALL error_string(unsigned id);
   static char* BOOST_REGEX_CALL get_catalogue() { return regex_message_catalogue; }
};

} // namespace re_detail

template<class charT>
class w32_regex_traits;

template<>
class BOOST_REGEX_DECL w32_regex_traits<char> : public re_detail::w32_traits_base
{
   typedef re_detail::w32_traits_base base_type;
public:
   typedef char char_type;
   typedef unsigned char uchar_type;
   typedef unsigned int size_type;
   typedef std::string string_type;
   typedef int locale_type;

   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::strlen(p);
   }
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c)
   {
      return syntax_map[c];
   }
   static char BOOST_REGEX_CALL translate(char c, bool icase)
   {
      return icase ? lower_case_map[(size_type)(uchar_type)c] : c;
   }
   static void BOOST_REGEX_CALL transform(std::string& out, const std::string& in);

   static void BOOST_REGEX_CALL transform_primary(std::string& out, const std::string& in);

   static bool BOOST_REGEX_CALL is_separator(char c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == '\n') || (c == '\r'));
   }

   static bool BOOST_REGEX_CALL is_combining(char)
   {
      return false;
   }

   static bool BOOST_REGEX_CALL is_class(char c, boost::uint_fast32_t f)
   {
      return BOOST_REGEX_MAKE_BOOL(class_map[(size_type)(uchar_type)c] & f);
   }

   static int BOOST_REGEX_CALL toi(char c);
   static int BOOST_REGEX_CALL toi(const char*& first, const char* last, int radix);

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const char* first, const char* last)
   {
      std::string s(first, last);
      return do_lookup_class(s.c_str());
   }

   static bool BOOST_REGEX_CALL lookup_collatename(std::string& buf, const char* first, const char* last)
   {
      std::string s(first, last);
      return do_lookup_collate(buf, s.c_str());
   }

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }

   struct sentry
   {
      sentry(const w32_regex_traits<char>&)
      { w32_regex_traits<char>::update(); }
      ~sentry(){}
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update();
   void swap(w32_regex_traits&){}
   w32_regex_traits();
   ~w32_regex_traits();
private:
   static w32_regex_traits<char> i;
};

#ifndef BOOST_NO_WREGEX
template<>
class BOOST_REGEX_DECL w32_regex_traits<regex_wchar_type> : public re_detail::w32_traits_base
{
   typedef re_detail::w32_traits_base base_type;
public:
   typedef regex_wchar_type char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<regex_wchar_type> string_type;
   typedef int locale_type;
#ifndef BOOST_REGEX_HAS_SHORT_WCHAR_T
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(p);
   }
#else
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(reinterpret_cast<const wchar_t*>(p));
   }
#endif
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c);
   static regex_wchar_type BOOST_REGEX_CALL translate(regex_wchar_type c, bool icase)
   {
      return icase ? ((c < 256) ? re_detail::wide_lower_case_map[(uchar_type)c] : wtolower(c)) : c;
   }

   static void BOOST_REGEX_CALL transform(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in);

   static void BOOST_REGEX_CALL transform_primary(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in);

   static bool BOOST_REGEX_CALL is_separator(regex_wchar_type c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == L'\n') || (c == L'\r') || (c == (regex_wchar_type)0x2028) || (c == (regex_wchar_type)0x2029));
   }

   static bool BOOST_REGEX_CALL is_combining(regex_wchar_type c)
   { return re_detail::is_combining(c); }

   static bool BOOST_REGEX_CALL is_class(regex_wchar_type c, boost::uint_fast32_t f)
   {
      return BOOST_REGEX_MAKE_BOOL(((uchar_type)c < 256) ? (wide_unicode_classes[(size_type)(uchar_type)c] & f) : do_iswclass(c, f));
   }

   static int BOOST_REGEX_CALL toi(regex_wchar_type c);
   static int BOOST_REGEX_CALL toi(const regex_wchar_type*& first, const regex_wchar_type* last, int radix);

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const regex_wchar_type* first, const regex_wchar_type* last);

   static bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<regex_wchar_type>& s, const regex_wchar_type* first, const regex_wchar_type* last);

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }

   struct sentry
   {
      sentry(const w32_regex_traits<regex_wchar_type>&)
      { w32_regex_traits<regex_wchar_type>::update(); }
      ~sentry(){}
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update();
   void swap(w32_regex_traits&){}
   w32_regex_traits();
   ~w32_regex_traits();
   static std::size_t BOOST_REGEX_CALL strnarrow(char *s1, std::size_t len, const regex_wchar_type *s2);
   static std::size_t BOOST_REGEX_CALL strwiden(regex_wchar_type *s1, std::size_t len, const char *s2);

private:
   static bool BOOST_REGEX_CALL do_iswclass(regex_wchar_type c, boost::uint_fast32_t f);
   static bool BOOST_REGEX_CALL do_lookup_collate(std::basic_string<regex_wchar_type>& out, const regex_wchar_type* first, const regex_wchar_type* last);
   static w32_regex_traits<regex_wchar_type> init_;
   static regex_wchar_type BOOST_REGEX_CALL wtolower(regex_wchar_type c);
   static unsigned short wide_unicode_classes[];
};

#ifdef BOOST_REGEX_HAS_SHORT_WCHAR_T
//
// What follows here is Visual Studio specific - it is a thin wrapper
// that redirects calls to w32_regex_traits<unsigned short> to
// w32_regex_traits<__wchar_t>.  This allows the library to be built
// so that it supports programs built both with and without /Zc:wchar_t.
//
template<>
class w32_regex_traits<unsigned short> : public re_detail::w32_traits_base
{
   typedef re_detail::w32_traits_base base_type;
public:
   typedef unsigned short char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<unsigned short> string_type;
   typedef int locale_type;
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return w32_regex_traits<regex_wchar_type>::length(
         reinterpret_cast<const regex_wchar_type*>(p));
   }
   static unsigned int BOOST_REGEX_CALL syntax_type(size_type c)
   {
      return w32_regex_traits<regex_wchar_type>::syntax_type(c);
   }
   static unsigned short BOOST_REGEX_CALL translate(unsigned short c, bool icase)
   {
      return w32_regex_traits<regex_wchar_type>::translate(c, icase);
   }

   static void BOOST_REGEX_CALL transform(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)
   {
      w32_regex_traits<regex_wchar_type>::transform(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in));
   }

   static void BOOST_REGEX_CALL transform_primary(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)
   {
      w32_regex_traits<regex_wchar_type>::transform_primary(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in)); }

   static bool BOOST_REGEX_CALL is_separator(unsigned short c)
   {
      return w32_regex_traits<regex_wchar_type>::is_separator(c);
   }

   static bool BOOST_REGEX_CALL is_combining(unsigned short c)
   {
      return w32_regex_traits<regex_wchar_type>::is_combining(c);
   }

   static bool BOOST_REGEX_CALL is_class(unsigned short c, boost::uint_fast32_t f)
   {
      return w32_regex_traits<regex_wchar_type>::is_class(c, f);
   }

   static int BOOST_REGEX_CALL toi(unsigned short c)
   {
      return w32_regex_traits<regex_wchar_type>::toi(c);
   }
   static int BOOST_REGEX_CALL toi(const unsigned short*& first, const unsigned short* last, int radix)
   {
      return w32_regex_traits<regex_wchar_type>::toi(
         reinterpret_cast<const regex_wchar_type*&>(first),
         reinterpret_cast<const regex_wchar_type*>(last),
         radix);
   }

   static boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const unsigned short* first, const unsigned short* last)
   {
      return w32_regex_traits<regex_wchar_type>::lookup_classname(
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   static bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<unsigned short>& s, const unsigned short* first, const unsigned short* last)
   {
      return w32_regex_traits<regex_wchar_type>::lookup_collatename(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(s),
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   static locale_type BOOST_REGEX_CALL imbue(locale_type l){ return l; }
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_type(); }

   struct sentry
   {
      sentry(const w32_regex_traits<unsigned short>&)
      { w32_regex_traits<unsigned short>::update(); }
      ~sentry(){}
      operator void*() { return this; }
   };
   static void BOOST_REGEX_CALL update()
   {
      w32_regex_traits<regex_wchar_type>::update();
   }
   void swap(w32_regex_traits&){}
   w32_regex_traits(){};
   ~w32_regex_traits(){};
   static std::size_t BOOST_REGEX_CALL strnarrow(char *s1, std::size_t len, const unsigned short *s2)
   {
      return w32_regex_traits<regex_wchar_type>::strnarrow(
         s1,
         len,
         reinterpret_cast<const regex_wchar_type *>(s2));
   }
   static std::size_t BOOST_REGEX_CALL strwiden(unsigned short *s1, std::size_t len, const char *s2)
   {
      return w32_regex_traits<regex_wchar_type>::strwiden(
         reinterpret_cast<regex_wchar_type *>(s1), len, s2);
   }

private:
   w32_regex_traits<regex_wchar_type> m_init;

};

#endif // BOOST_REGEX_HAS_SHORT_WCHAR_T

#endif // Wide strings
#endif // Win32

#if !defined(BOOST_NO_STD_LOCALE)

namespace re_detail
{

template <class charT>
struct message_data;

template <>
struct message_data<char>;

template <>
struct message_data<regex_wchar_type>;

struct BOOST_REGEX_DECL cpp_regex_traits_base : public regex_traits_base
{
   enum char_class_type
   {
      char_class_none = 0,
      char_class_alnum = std::ctype_base::alnum,
      char_class_alpha = std::ctype_base::alpha,
      char_class_cntrl = std::ctype_base::cntrl,
      char_class_digit = std::ctype_base::digit,
      char_class_graph = std::ctype_base::graph,
      char_class_lower = std::ctype_base::lower,
      char_class_print = std::ctype_base::print,
      char_class_punct = std::ctype_base::punct,
      char_class_space = std::ctype_base::space,
      char_class_upper = std::ctype_base::upper,
      char_class_xdigit = std::ctype_base::xdigit,
      char_class_blank = 1<<12,
      char_class_underscore = 1<<13,
      char_class_word = std::ctype_base::alnum | char_class_underscore,
      char_class_unicode = 1<<14,
      char_class_all_base = char_class_alnum | char_class_alpha | char_class_cntrl
                         | char_class_digit | char_class_graph | char_class_lower
                         | char_class_print | char_class_punct | char_class_space
                         | char_class_upper | char_class_xdigit
   };

   static std::string BOOST_REGEX_CALL set_message_catalogue(const std::string& s);
protected:
   static char regex_message_cat[BOOST_REGEX_MAX_PATH];
};

} // namespace re_detail

template <class charT>
class cpp_regex_traits;

template<>
class BOOST_REGEX_DECL cpp_regex_traits<char> : public re_detail::cpp_regex_traits_base
{
   typedef re_detail::cpp_regex_traits_base base_type;
private:
   re_detail::message_data<char>* pmd;
   const unsigned char* psyntax;
   char* lower_map;
   const std::ctype<char>* pctype;
   const std::collate<char>* pcollate;
   std::locale locale_inst;
   unsigned sort_type;
   char sort_delim;

   cpp_regex_traits(const cpp_regex_traits&);
   cpp_regex_traits& operator=(const cpp_regex_traits&);

public:
   typedef char char_type;
   typedef unsigned char uchar_type;
   typedef unsigned int size_type;
   typedef std::string string_type;
   typedef std::locale locale_type;

   cpp_regex_traits();
   ~cpp_regex_traits();

   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::strlen(p);
   }
   unsigned int BOOST_REGEX_CALL syntax_type(size_type c)const
   {
      return psyntax[c];
   }
   char BOOST_REGEX_CALL translate(char c, bool icase)const
   {
      return icase ? lower_map[(size_type)(uchar_type)c] : c;
   }
   void BOOST_REGEX_CALL transform(std::string& out, const std::string& in)const
   {
      out = pcollate->transform(in.c_str(), in.c_str() + in.size()).c_str();
   }

   void BOOST_REGEX_CALL transform_primary(std::string& out, const std::string& in)const;

   static bool BOOST_REGEX_CALL is_separator(char c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == '\n') || (c == '\r'));
   }

   static bool BOOST_REGEX_CALL is_combining(char)
   {
      return false;
   }

   bool BOOST_REGEX_CALL is_class(char c, boost::uint_fast32_t f)const
   {
      if(pctype->is((std::ctype<char>::mask)(f & char_class_all_base), c))
         return true;
      if((f & char_class_underscore) && (c == '_'))
         return true;
      if((f & char_class_blank) && ((c == ' ') || (c == '\t')))
         return true;
      return false;
   }

   int BOOST_REGEX_CALL toi(char c)const;
   int BOOST_REGEX_CALL toi(const char*& first, const char* last, int radix)const;

   boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const char* first, const char* last)const;
   bool BOOST_REGEX_CALL lookup_collatename(std::string& s, const char* first, const char* last)const;

   std::string BOOST_REGEX_CALL error_string(unsigned id)const;
   locale_type BOOST_REGEX_CALL imbue(locale_type l);
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_inst; }
   void swap(cpp_regex_traits&);

   struct sentry
   {
      sentry(const cpp_regex_traits<char>&){}
      operator void*() { return this; }
   };
};

#if !defined(BOOST_NO_WREGEX) && !defined(BOOST_NO_STD_WSTREAMBUF)
template<>
class BOOST_REGEX_DECL cpp_regex_traits<regex_wchar_type> : public re_detail::cpp_regex_traits_base
{
   typedef re_detail::cpp_regex_traits_base base_type;
public:
   typedef regex_wchar_type char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<regex_wchar_type> string_type;
   typedef std::locale locale_type;

private:
   re_detail::message_data<regex_wchar_type>* pmd;
   const unsigned char* psyntax;
   regex_wchar_type* lower_map;
   const std::ctype<regex_wchar_type>* pctype;
   const std::collate<regex_wchar_type>* pcollate;
   const std::codecvt<regex_wchar_type, char, std::mbstate_t>* pcdv;
   std::locale locale_inst;
   unsigned int BOOST_REGEX_CALL do_syntax_type(size_type c)const;
   unsigned sort_type;
   regex_wchar_type sort_delim;

   cpp_regex_traits(const cpp_regex_traits&);
   cpp_regex_traits& operator=(const cpp_regex_traits&);

public:
#ifndef BOOST_REGEX_HAS_SHORT_WCHAR_T
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(p);
   }
#else
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return std::wcslen(reinterpret_cast<const wchar_t*>(p));
   }
#endif
   unsigned int BOOST_REGEX_CALL syntax_type(size_type c)const
   {
      return (c < UCHAR_MAX) ? psyntax[c] : do_syntax_type(c);
   }
   regex_wchar_type BOOST_REGEX_CALL translate(regex_wchar_type c, bool icase)const
   {
      return icase ? (((uchar_type)c) <= UCHAR_MAX) ? lower_map[c] : pctype->tolower(c) : c;
   }
   void BOOST_REGEX_CALL transform(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in)const
   {
      out = pcollate->transform(in.c_str(), in.c_str() + in.size());
   }

   void BOOST_REGEX_CALL transform_primary(std::basic_string<regex_wchar_type>& out, const std::basic_string<regex_wchar_type>& in)const;

   static bool BOOST_REGEX_CALL is_separator(regex_wchar_type c)
   {
      return BOOST_REGEX_MAKE_BOOL((c == L'\n') || (c == L'\r') || (c == (regex_wchar_type)0x2028) || (c == (regex_wchar_type)0x2029));
   }

   static bool BOOST_REGEX_CALL is_combining(regex_wchar_type c)
   { return re_detail::is_combining(c); }

   bool BOOST_REGEX_CALL is_class(regex_wchar_type c, boost::uint_fast32_t f)const
   {
      if(pctype->is((std::ctype<regex_wchar_type>::mask)(f & char_class_all_base), c))
         return true;
      if((f & char_class_underscore) && (c == '_'))
         return true;
      if((f & char_class_blank) && ((c == ' ') || (c == '\t')))
         return true;
      if((f & char_class_unicode) && ((uchar_type)c > (uchar_type)255))
         return true;
      return false;
   }

   int BOOST_REGEX_CALL toi(regex_wchar_type c)const;
   int BOOST_REGEX_CALL toi(const regex_wchar_type*& first, const regex_wchar_type* last, int radix)const;

   boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const regex_wchar_type* first, const regex_wchar_type* last)const;
   bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<regex_wchar_type>& s, const regex_wchar_type* first, const regex_wchar_type* last)const;

   std::string BOOST_REGEX_CALL error_string(unsigned id)const;
   void swap(cpp_regex_traits&);
   cpp_regex_traits();
   ~cpp_regex_traits();
   locale_type BOOST_REGEX_CALL imbue(locale_type l);
   locale_type BOOST_REGEX_CALL getloc()const{ return locale_inst; }
   std::size_t BOOST_REGEX_CALL strwiden(regex_wchar_type *s1, std::size_t len, const char *s2)const;

   struct sentry
   {
      sentry(const cpp_regex_traits<regex_wchar_type>&){}
      operator void*() { return this; }
   };
};

#ifdef BOOST_REGEX_HAS_SHORT_WCHAR_T
//
// What follows here is Visual Studio specific - it is a thin wrapper
// that redirects calls to cpp_regex_traits<unsigned short> to
// cpp_regex_traits<__wchar_t>.  This allows the library to be built
// so that it supports programs built both with and without /Zc:wchar_t.
//
template<>
class cpp_regex_traits<unsigned short> : public re_detail::cpp_regex_traits_base
{
   typedef re_detail::cpp_regex_traits_base base_type;
public:
   typedef unsigned short char_type;
   typedef unsigned short uchar_type;
   typedef unsigned int size_type;
   typedef std::basic_string<unsigned short> string_type;
   typedef std::locale locale_type;
   static std::size_t BOOST_REGEX_CALL length(const char_type* p)
   {
      return cpp_regex_traits<regex_wchar_type>::length(
         reinterpret_cast<const regex_wchar_type*>(p));
   }
   unsigned int BOOST_REGEX_CALL syntax_type(size_type c)const
   {
      return m_imp.syntax_type(c);
   }
   unsigned short BOOST_REGEX_CALL translate(unsigned short c, bool icase)const
   {
      return m_imp.translate(c, icase);
   }

   void BOOST_REGEX_CALL transform(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)const
   {
      m_imp.transform(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in));
   }

   void BOOST_REGEX_CALL transform_primary(std::basic_string<unsigned short>& out, const std::basic_string<unsigned short>& in)const
   {
      m_imp.transform_primary(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(out),
         reinterpret_cast<const std::basic_string<regex_wchar_type>&>(in)); }

   static bool BOOST_REGEX_CALL is_separator(unsigned short c)
   {
      return cpp_regex_traits<regex_wchar_type>::is_separator(c);
   }

   static bool BOOST_REGEX_CALL is_combining(unsigned short c)
   {
      return cpp_regex_traits<regex_wchar_type>::is_combining(c);
   }

   bool BOOST_REGEX_CALL is_class(unsigned short c, boost::uint_fast32_t f)const
   {
      return m_imp.is_class(c, f);
   }

   int BOOST_REGEX_CALL toi(unsigned short c)const
   {
      return m_imp.toi(c);
   }
   int BOOST_REGEX_CALL toi(const unsigned short*& first, const unsigned short* last, int radix)const
   {
      return m_imp.toi(
         reinterpret_cast<const regex_wchar_type*&>(first),
         reinterpret_cast<const regex_wchar_type*>(last),
         radix);
   }

   boost::uint_fast32_t BOOST_REGEX_CALL lookup_classname(const unsigned short* first, const unsigned short* last)const
   {
      return m_imp.lookup_classname(
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   bool BOOST_REGEX_CALL lookup_collatename(std::basic_string<unsigned short>& s, const unsigned short* first, const unsigned short* last)const
   {
      return m_imp.lookup_collatename(
         reinterpret_cast<std::basic_string<regex_wchar_type>&>(s),
         reinterpret_cast<const regex_wchar_type*>(first),
         reinterpret_cast<const regex_wchar_type*>(last));
   }

   locale_type BOOST_REGEX_CALL imbue(locale_type l)
   {
      return m_imp.imbue(l);
   }
   locale_type BOOST_REGEX_CALL getloc()const
   {
      return m_imp.getloc();
   }

   struct sentry
   {
      sentry(const cpp_regex_traits<unsigned short>&){}
      operator void*() { return this; }
   };
   void swap(cpp_regex_traits& that)
   {
      m_imp.swap(that.m_imp);
   }
   cpp_regex_traits(){};
   ~cpp_regex_traits(){};
   std::size_t BOOST_REGEX_CALL strwiden(unsigned short *s1, std::size_t len, const char *s2)const
   {
      return m_imp.strwiden(
         reinterpret_cast<regex_wchar_type *>(s1), len, s2);
   }
   std::string BOOST_REGEX_CALL error_string(unsigned id)const
   {
      return m_imp.error_string(id);
   }

private:
   cpp_regex_traits<regex_wchar_type> m_imp;

};

#endif // BOOST_REGEX_HAS_SHORT_WCHAR_T
#endif // BOOST_NO_WREGEX

#endif // BOOST_NO_STD_LOCALE

#ifdef BOOST_REGEX_USE_WIN32_LOCALE

template <class charT>
class regex_traits : public w32_regex_traits<charT>
{
};

#elif defined(BOOST_REGEX_USE_C_LOCALE)

template <class charT>
class regex_traits : public c_regex_traits<charT>
{
};

#elif defined(BOOST_REGEX_USE_CPP_LOCALE)

template <class charT>
class regex_traits : public cpp_regex_traits<charT>
{
};

#else
#error No default localisation model defined
#endif

#ifdef BOOST_HAS_ABI_HEADERS
#  include BOOST_ABI_SUFFIX
#endif

} // namespace boost

#endif // include

max_stars_repo_name: macaurther/DOCUSA

max_issues_repo_name: macaurther/DOCUSA

max_forks_repo_name: dguenms/Dawn-of-Civilization


text:
/**
 * @file lllogin.cpp
 *
 * $LicenseInfo:firstyear=2009&license=viewerlgpl$
 * Second Life Viewer Source Code
 * Copyright (C) 2010, Linden Research, Inc.
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation;
 * version 2.1 of the License only.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * Linden Research, Inc., 945 Battery Street, San Francisco, CA  94111  USA
 * $/LicenseInfo$
 */

#include "linden_common.h"
#include "llsd.h"
#include "llsdutil.h"

/*==========================================================================*|
#ifdef LL_WINDOWS
	// non-virtual destructor warning, boost::statechart does this intentionally.
	#pragma warning (disable : 4265)
#endif
|*==========================================================================*/

#include "lllogin.h"

#include <boost/bind.hpp>

#include "llcoros.h"
#include "llevents.h"
#include "lleventfilter.h"
#include "lleventcoro.h"

//*********************
// LLLogin
// *NOTE:Mani - Is this Impl needed now that the state machine runs the show?
class LLLogin::Impl
{
public:
    Impl():
		mPump("login", true) // Create the module's event pump with a tweaked (unique) name.
    {
        mValidAuthResponse["status"]        = LLSD();
        mValidAuthResponse["errorcode"]     = LLSD();
        mValidAuthResponse["error"]         = LLSD();
        mValidAuthResponse["transfer_rate"] = LLSD();
    }

    void connect(const std::string& uri, const LLSD& credentials);
    void disconnect();
	LLEventPump& getEventPump() { return mPump; }

private:
	LLSD getProgressEventLLSD(const std::string& state, const std::string& change,
						   const LLSD& data = LLSD())
	{
		LLSD status_data;
		status_data["state"] = state;
		status_data["change"] = change;
		status_data["progress"] = 0.0f;

		if(mAuthResponse.has("transfer_rate"))
		{
			status_data["transfer_rate"] = mAuthResponse["transfer_rate"];
		}

		if(data.isDefined())
		{
			status_data["data"] = data;
		}
		return status_data;
	}

	void sendProgressEvent(const std::string& state, const std::string& change,
						   const LLSD& data = LLSD())
	{
		LLSD status_data = getProgressEventLLSD(state, change, data);
		mPump.post(status_data);
	}

    LLSD validateResponse(const std::string& pumpName, const LLSD& response)
    {
        // Validate the response. If we don't recognize it, things
        // could get ugly.
        std::string mismatch(llsd_matches(mValidAuthResponse, response));
        if (! mismatch.empty())
        {
            LL_ERRS("LLLogin") << "Received unrecognized event (" << mismatch << ") on "
                               << pumpName << "pump: " << response
                               << LL_ENDL;
            return LLSD();
        }

        return response;
    }

    // In a coroutine's top-level function args, do NOT NOT NOT accept
    // references (const or otherwise) to anything but the self argument! Pass
    // by value only!
    void login_(LLCoros::self& self, std::string uri, LLSD credentials);

    LLEventStream mPump;
	LLSD mAuthResponse, mValidAuthResponse;
};

void LLLogin::Impl::connect(const std::string& uri, const LLSD& login_params)
{
    LL_DEBUGS("LLLogin") << " connect with  uri '" << uri << "', login_params " << login_params << LL_ENDL;

    // Launch a coroutine with our login_() method. Run the coroutine until
    // its first wait; at that point, return here.
    std::string coroname =
        LLCoros::instance().launch("LLLogin::Impl::login_",
                                   boost::bind(&Impl::login_, this, _1, uri, login_params));
    LL_DEBUGS("LLLogin") << " connected with  uri '" << uri << "', login_params " << login_params << LL_ENDL;
}

void LLLogin::Impl::login_(LLCoros::self& self, std::string uri, LLSD login_params)
{
	try
	{
	LLSD printable_params = login_params;
	//if(printable_params.has("params")
	//	&& printable_params["params"].has("passwd"))
	//{
	//	printable_params["params"]["passwd"] = "*******";
	//}
	LL_DEBUGS("LLLogin") << "Entering coroutine " << LLCoros::instance().getName(self)
                        << " with uri '" << uri << "', parameters " << printable_params << LL_ENDL;

	// Arriving in SRVRequest state
    LLEventStream replyPump("SRVreply", true);
    // Should be an array of one or more uri strings.

    LLSD rewrittenURIs;
    {
		LLEventTimeout filter(replyPump);
		sendProgressEvent("offline", "srvrequest");

      // Request SRV record.
		LL_DEBUGS("LLLogin") << "Requesting SRV record from " << uri << LL_ENDL;

      // *NOTE:Mani - Completely arbitrary default timeout value for SRV request.
		F32 seconds_to_timeout = 5.0f;
		if(login_params.has("cfg_srv_timeout"))
		{
			seconds_to_timeout = login_params["cfg_srv_timeout"].asReal();
		}

		// If the SRV request times out (e.g. EXT-3934), simulate response: an
		// array containing our original URI.
		LLSD fakeResponse(LLSD::emptyArray());
		fakeResponse.append(uri);
		filter.eventAfter(seconds_to_timeout, fakeResponse);

		std::string srv_pump_name = "LLAres";
		if(login_params.has("cfg_srv_pump"))
		{
			srv_pump_name = login_params["cfg_srv_pump"].asString();
		}

		// Make request
		LLSD request;
		request["op"] = "rewriteURI";
		request["uri"] = uri;
		request["reply"] = replyPump.getName();
		rewrittenURIs = postAndWait(self, request, srv_pump_name, filter);
		// EXP-772: If rewrittenURIs fail, try original URI as a fallback.
		rewrittenURIs.append(uri);
    } // we no longer need the filter

    LLEventPump& xmlrpcPump(LLEventPumps::instance().obtain("LLXMLRPCTransaction"));
    // EXT-4193: use a DIFFERENT reply pump than for the SRV request. We used
    // to share them -- but the EXT-3934 fix made it possible for an abandoned
    // SRV response to arrive just as we were expecting the XMLRPC response.
    LLEventStream loginReplyPump("loginreply", true);

    // Loop through the rewrittenURIs, counting attempts along the way.
    // Because of possible redirect responses, we may make more than one
    // attempt per rewrittenURIs entry.
    LLSD::Integer attempts = 0;
    for (LLSD::array_const_iterator urit(rewrittenURIs.beginArray()),
             urend(rewrittenURIs.endArray());
         urit != urend; ++urit)
    {
        LLSD request(login_params);
        request["reply"] = loginReplyPump.getName();
        request["uri"] = *urit;
        std::string status;

        // Loop back to here if login attempt redirects to a different
        // request["uri"]
        for (;;)
        {
            ++attempts;
            LLSD progress_data;
            progress_data["attempt"] = attempts;
            progress_data["request"] = request;
			if(progress_data["request"].has("params")
				&& progress_data["request"]["params"].has("passwd"))
			{
				progress_data["request"]["params"]["passwd"] = "*******";
			}
            sendProgressEvent("offline", "authenticating", progress_data);

            // We expect zero or more "Downloading" status events, followed by
            // exactly one event with some other status. Use postAndWait() the
            // first time, because -- at least in unit-test land -- it's
            // possible for the reply to arrive before the post() call
            // returns. Subsequent responses, of course, must be awaited
            // without posting again.
            for (mAuthResponse = validateResponse(loginReplyPump.getName(),
                                 postAndWait(self, request, xmlrpcPump, loginReplyPump, "reply"));
                 mAuthResponse["status"].asString() == "Downloading";
                 mAuthResponse = validateResponse(loginReplyPump.getName(),
                                     waitForEventOn(self, loginReplyPump)))
            {
                // Still Downloading -- send progress update.
                sendProgressEvent("offline", "downloading");
            }

			LL_DEBUGS("LLLogin") << "Auth Response: " << mAuthResponse << LL_ENDL;
            status = mAuthResponse["status"].asString();

            // Okay, we've received our final status event for this
            // request. Unless we got a redirect response, break the retry
            // loop for the current rewrittenURIs entry.
            if (!(status == "Complete" &&
                  mAuthResponse["responses"]["login"].asString() == "indeterminate"))
            {
                break;
            }

			sendProgressEvent("offline", "indeterminate", mAuthResponse["responses"]);

            // Here the login service at the current URI is redirecting us
            // to some other URI ("indeterminate" -- why not "redirect"?).
            // The response should contain another uri to try, with its
            // own auth method.
            request["uri"] = mAuthResponse["responses"]["next_url"].asString();
            request["method"] = mAuthResponse["responses"]["next_method"].asString();
        } // loop back to try the redirected URI

        // Here we're done with redirects for the current rewrittenURIs
        // entry.
        if (status == "Complete")
        {
            // StatusComplete does not imply auth success. Check the
            // actual outcome of the request. We've already handled the
            // "indeterminate" case in the loop above.
            if (mAuthResponse["responses"]["login"].asString() == "true")
            {
                sendProgressEvent("online", "connect", mAuthResponse["responses"]);
            }
            else
            {
                sendProgressEvent("offline", "fail.login", mAuthResponse["responses"]);
            }
            return;             // Done!
        }

		/* Sometimes we end with "Started" here. Slightly slow server?
		 * Seems to be ok to just skip it. Otherwise we'd error out and crash in the if below.
		 */
		if( status == "Started")
		{
			LL_DEBUGS("LLLogin") << mAuthResponse << LL_ENDL;
			continue;
		}

        // If we don't recognize status at all, trouble
        if (! (status == "CURLError"
               || status == "XMLRPCError"
               || status == "OtherError"))
        {
            LL_ERRS("LLLogin") << "Unexpected status from " << xmlrpcPump.getName() << " pump: "
                               << mAuthResponse << LL_ENDL;
            return;
        }

        // Here status IS one of the errors tested above.
    } // Retry if there are any more rewrittenURIs.

    // Here we got through all the rewrittenURIs without succeeding. Tell
    // caller this didn't work out so well. Of course, the only failure data
    // we can reasonably show are from the last of the rewrittenURIs.

	// *NOTE: The response from LLXMLRPCListener's Poller::poll method returns an
	// llsd with no "responses" node. To make the output from an incomplete login symmetrical
	// to success, add a data/message and data/reason fields.
	LLSD error_response;
	error_response["reason"] = mAuthResponse["status"];
	error_response["errorcode"] = mAuthResponse["errorcode"];
	error_response["message"] = mAuthResponse["error"];
	if(mAuthResponse.has("certificate"))
	{
		error_response["certificate"] = mAuthResponse["certificate"];
	}
	sendProgressEvent("offline", "fail.login", error_response);
	}
	catch (...) {
		LL_ERRS() << "login exception caught" << LL_ENDL;
	}
}

void LLLogin::Impl::disconnect()
{
    sendProgressEvent("offline", "disconnect");
}

//*********************
// LLLogin
LLLogin::LLLogin() :
	mImpl(new LLLogin::Impl())
{
}

LLLogin::~LLLogin()
{
}

void LLLogin::connect(const std::string& uri, const LLSD& credentials)
{
	mImpl->connect(uri, credentials);
}

void LLLogin::disconnect()
{
	mImpl->disconnect();
}

LLEventPump& LLLogin::getEventPump()
{
	return mImpl->getEventPump();
}

// The following is the list of important functions that happen in the
// current login process that we want to move to this login module.

// The list associates to event with the original idle_startup() 'STATE'.

// Rewrite URIs
 // State_LOGIN_AUTH_INIT
// Given a vector of login uris (usually just one), perform a dns lookup for the
// SRV record from each URI. I think this is used to distribute login requests to
// a single URI to multiple hosts.
// This is currently a synchronous action. (See LLSRV::rewriteURI() implementation)
// On dns lookup error the output uris == the input uris.
//
// Input: A vector of login uris
// Output: A vector of login uris
//
// Code:
// std::vector<std::string> uris;
// LLViewerLogin::getInstance()->getLoginURIs(uris);
// std::vector<std::string>::const_iterator iter, end;
// for (iter = uris.begin(), end = uris.end(); iter != end; ++iter)
// {
//	std::vector<std::string> rewritten;
//	rewritten = LLSRV::rewriteURI(*iter);
//	sAuthUris.insert(sAuthUris.end(),
//					 rewritten.begin(), rewritten.end());
// }
// sAuthUriNum = 0;

// Authenticate
// STATE_LOGIN_AUTHENTICATE
// Connect to the login server, presumably login.cgi, requesting the login
// and a slew of related initial connection information.
// This is an asynch action. The final response, whether success or error
// is handled by STATE_LOGIN_PROCESS_REPONSE.
// There is no immediate error or output from this call.
//
// Input:
//  URI
//  Credentials (first, last, password)
//  Start location
//  Bool Flags:
//    skip optional update
//    accept terms of service
//    accept critical message
//  Last exec event. (crash state of previous session)
//  requested optional data (inventory skel, initial outfit, etc.)
//  local mac address
//  viewer serial no. (md5 checksum?)

//sAuthUriNum = llclamp(sAuthUriNum, 0, (S32)sAuthUris.size()-1);
//LLUserAuth::getInstance()->authenticate(
//	sAuthUris[sAuthUriNum],
//	auth_method,
//	firstname,
//	lastname,
//	password, // web_login_key,
//	start.str(),
//	gSkipOptionalUpdate,
//	gAcceptTOS,
//	gAcceptCriticalMessage,
//	gLastExecEvent,
//	requested_options,
//	hashed_mac_string,
//	LLAppViewer::instance()->getSerialNumber());

//
// Download the Response
// STATE_LOGIN_NO_REPONSE_YET and STATE_LOGIN_DOWNLOADING
// I had assumed that this was default behavior of the message system. However...
// During login, the message system is checked only by these two states in idle_startup().
// I guess this avoids the overhead of checking network messages for those login states
// that don't need to do so, but geez!
// There are two states to do this one function just to update the login
// status text from 'Logging In...' to 'Downloading...'
//

//
// Handle Login Response
// STATE_LOGIN_PROCESS_RESPONSE
//
// This state handle the result of the request to login. There is a metric ton of
// code in this case. This state will transition to:
// STATE_WORLD_INIT, on success.
// STATE_AUTHENTICATE, on failure.
// STATE_UPDATE_CHECK, to handle user during login interaction like TOS display.
//
// Much of the code in this case belongs on the viewer side of the fence and not in login.
// Login should probably return with a couple of events, success and failure.
// Failure conditions can be specified in the events data pacet to allow the viewer
// to re-engauge login as is appropriate. (Or should there be multiple failure messages?)
// Success is returned with the data requested from the login. According to OGP specs
// there may be intermediate steps before reaching this result in future login
// implementations.

max_stars_repo_name: humbletim/archived-casviewer

max_issues_repo_name: humbletim/archived-casviewer

max_forks_repo_name: humbletim/archived-casviewer


text:
// Boost.Range 2.0 Extension library
// via PStade Oven Library
//
// Copyright Akira Takahashi 2011.
// Copyright Shunsuke Sogame 2005-2007.
// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <iostream>
#include <vector>
#include <string>
#include <boost/assign/list_of.hpp>
#include <boost/range/adaptor/regular_extension/transformed.hpp>
#include <boost/range/algorithm/for_each.hpp>
#include <boost/lambda/lambda.hpp>

struct X {
    int a;
    std::string s;

    X(int a_, const std::string& s_) : a(a_), s(s_) {}
};

struct disper {
    template <class T>
    void operator()(const T& x) const
    {
        std::cout << x << std::endl;
    }
};

int main()
{
    const std::vector<X> v = boost::assign::list_of
        (X(1, "a"))
        (X(2, "b"))
        (X(3, "c"))
        ;

    using boost::lambda::_1;

    boost::for_each(v |+ boost::adaptors::transformed(&_1 ->* &X::s), disper());
}

/*
a
b
c

*/

max_stars_repo_name: Flast/OvenToBoost

max_issues_repo_name: Flast/OvenToBoost

max_forks_repo_name: Flast/OvenToBoost


text:
/**
 * Copyright (c) 2017 Melown Technologies SE
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * *  Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * *  Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
/**
 * \file registry/stringdict.hpp
 * \author Vaclav Blazek <vaclav.blazek@citationtech.net>
 */

#ifndef vtslibs_registry_stringdict_hpp_included_
#define vtslibs_registry_stringdict_hpp_included_

#include <map>
#include <string>
#include <algorithm>

#include <boost/optional.hpp>

#include "dbglog/dbglog.hpp"

namespace vtslibs { namespace registry {

namespace detail {

template <typename T> const std::string& getId(const T &value) {
    return value.id;
}

template <typename T> const std::string& getId(const T *value) {
    return value->id;
}

template <typename T> const std::string& getId(const boost::optional<T> &value)
{
    return value->id;
}

template <typename T> const std::string& getId(const boost::optional<T> *value)
{
    return (*value)->id;
}

template <typename T> const T& getValue(const T &value) {
    return value;
}

template <typename T> const T& getValue(const T *value) {
    return *value;
}

} // namespace detail

template <typename T>
class StringDictionary
{
private:
    typedef std::map<std::string, T> map;

public:
    StringDictionary() {}

    void set(const std::string &id, const T &value);
    void replace(const std::string &id, const T &value);
    const T* get(const std::string &id, std::nothrow_t) const;
    const T& get(const std::string &id) const;

    /** Same as above but performs the get only when id is not none.
     */
    const T* get(const boost::optional<std::string> &id) const;
    const T* get(const boost::optional<std::string> &id, std::nothrow_t) const;
    bool has(const std::string &id) const;

    template <typename U>
    inline void add(const U &value) {
        set(detail::getId(value), detail::getValue(value));
    }

    template <typename U>
    inline void replace(const U &value) {
        replace(detail::getId(value), detail::getValue(value));
    }

    typedef typename map::value_type value_type;
    typedef typename map::const_iterator const_iterator;
    typedef typename map::iterator iterator;
    const_iterator begin() const { return map_.begin(); }
    const_iterator end() const { return map_.end(); }
    iterator begin() { return map_.begin(); }
    iterator end() { return map_.end(); }

    void update(const StringDictionary &other);

    template <typename Op> void for_each(Op op)
    {
        std::for_each(map_.begin(), map_.end()
                      , [&](typename map::value_type &pair) {
                          op(pair.second);
                      });
    }

    template <typename Op> void for_each(Op op) const
    {
        std::for_each(map_.begin(), map_.end()
                      , [&](const typename map::value_type &pair) {
                          op(pair.second);
                      });
    }

    bool empty() const { return map_.empty(); }

    const T* operator()(const std::string &id, std::nothrow_t) const {
        return get(id, std::nothrow);
    }
    const T& operator()(const std::string &id) const { return get(id); }

    bool operator==(const StringDictionary &o) const { return map_ == o.map_; }
    bool operator!=(const StringDictionary &o) const { return map_ != o.map_; }

private:
    map map_;
};

template <typename T>
void StringDictionary<T>::set(const std::string &id, const T &value)
{
    map_.insert(typename map::value_type(id, value));
}

template <typename T>
void StringDictionary<T>::replace(const std::string &id, const T &value)
{
    auto res(map_.insert(typename map::value_type(id, value)));
    if (!res.second) {
        // already present, replace
        res.first->second = value;
    }
}

template <typename T>
const T* StringDictionary<T>::get(const std::string &id, std::nothrow_t) const
{
    auto fmap(map_.find(id));
    if (fmap == map_.end()) { return nullptr; }
    return &fmap->second;
}

template <typename T>
const T& StringDictionary<T>::get(const std::string &id) const
{
    const auto *value(get(id, std::nothrow));
    if (!value) {
        LOGTHROW(err1, storage::KeyError)
            << "<" << id << "> is not known " << T::typeName << ".";
    }
    return *value;
}

template <typename T>
const T* StringDictionary<T>::get(const boost::optional<std::string> &id) const
{
    if (!id) { return nullptr; }
    return &get(*id);
}

template <typename T>
const T* StringDictionary<T>::get(const boost::optional<std::string> &id
                                  , std::nothrow_t)
    const
{
    if (!id) { return nullptr; }
    return get(*id, std::nothrow);
}

template <typename T>
bool StringDictionary<T>::has(const std::string &id) const
{
    return (map_.find(id) != map_.end());
}

template <typename T>
void StringDictionary<T>::update(const StringDictionary &other)
{
    for (const auto &item : other) { map_.insert(item); }
}

} } // namespace vtslibs::registry

#endif // vtslibs_registry_stringdict_hpp_included_

max_stars_repo_name: melowntech/vts-libs

max_issues_repo_name: melowntech/vts-libs

max_forks_repo_name: melowntech/vts-libs