text:
/* vim: set tabstop=4 : */
#ifndef __terark_io_ZeroCopy_h__
#define __terark_io_ZeroCopy_h__

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
#endif

#include <boost/mpl/bool.hpp>
#include <assert.h>
#include <stdio.h> // for getFILE
#include <string.h>
#include <stdarg.h>
#include <string>
#include <terark/stdtypes.hpp>

namespace terark {

class TERARK_DLL_EXPORT IZeroCopyInputStream
{
public:
	typedef boost::mpl::false_ is_seekable;

	virtual ~IZeroCopyInputStream();

	/**
	 * get readbuffer for zero copy
	 */
	virtual const void* zcRead(size_t length, size_t* readed) = 0;

	/**
	 @brief End Of File

	  only InputStream has eof() mark, OutputStream does not have eof()
	 */
	virtual bool eof() const = 0;
};

class TERARK_DLL_EXPORT IZeroCopyOutputStream
{
public:
	typedef boost::mpl::false_ is_seekable;

	virtual ~IZeroCopyOutputStream();

	/**
	 * get write buffer for zero copy
	 */
	virtual void* zcWrite(size_t length, size_t* writable) = 0;

	/**
	 * after last zcWrite, caller may be not have written the whole buffer
	 * zcFlush tells the Stream how many bytes has actual written,
	 * next zcWrite will get the unwritten buffer lies in last buffer end.
	 */
	virtual void zcFlush(size_t nWritten) = 0;
};

class TERARK_DLL_EXPORT ZeroCopyBase
{
protected:
	unsigned char* m_beg;
	unsigned char* m_pos;
	unsigned char* m_end;
	size_t m_bufsize;

	void init(size_t bufsize)
	{
		m_beg = NULL;
		m_pos = NULL;
		m_end = NULL;
		m_bufsize = bufsize;
	}

public:
	typedef boost::mpl::false_ is_seekable;

	ptrdiff_t buf_remain_bytes() const { return m_end - m_pos; }
};

class TERARK_DLL_EXPORT ZcReader : public ZeroCopyBase
{
	IZeroCopyInputStream* m_is;

public:
	explicit ZcReader(IZeroCopyInputStream* stream = NULL, size_t bufsize = BUFSIZ)
	{
		attach(stream, BUFSIZ);
	}

	void attach(IZeroCopyInputStream* stream, size_t bufsize = BUFSIZ)
	{
		init(bufsize);
		m_is = stream;
	}

	bool eof() { return m_pos == m_end && test_eof(); }

	/**
	 * @return actually readed bytes, never return 0
	 *   -  if actually readed bytes is 0, throw EndOfFileException
	 */
	size_t read(void* vbuf, size_t length)
	{
		if (terark_likely(m_pos+length <= m_end)) {
			memcpy(vbuf, m_pos, length);
			m_pos += length;
			return length;
		} else
			return fill_and_read(vbuf, length);
	}

	/**
	 * always read requested bytes, or throw EndOfFileException
	 */
	void ensureRead(void* vbuf, size_t length)
	{
		// 为了效率，这么实现可以让编译器更好地 inline 这个函数
		// inline 后的函数体并尽可能小
		if (terark_likely(m_pos+length <= m_end)) {
			memcpy(vbuf, m_pos, length);
			m_pos += length;
		} else
			fill_and_ensureRead(vbuf, length);
	}

	byte readByte()
	{
		if (terark_likely(m_pos < m_end))
			return *m_pos++;
		else
			return fill_and_read_byte();
	}

	void getline(std::string& line, size_t maxlen = UINT_MAX);

	#include "var_int_declare_read.hpp"

protected:
	size_t fill_and_read(void* vbuf, size_t length);
	void   fill_and_ensureRead(void* vbuf, size_t length);
	byte   fill_and_read_byte();
	int    test_eof();

	size_t do_fill_and_read(void* vbuf, size_t length);
};

class TERARK_DLL_EXPORT ZcWriter : public ZeroCopyBase
{
	IZeroCopyOutputStream* m_os;

public:
	explicit ZcWriter(IZeroCopyOutputStream* stream = NULL, size_t bufsize = BUFSIZ)
	{
		attach(stream, BUFSIZ);
	}
	~ZcWriter();

	void attach(IZeroCopyOutputStream* stream, size_t bufsize = BUFSIZ)
	{
		init(bufsize);
		m_os = stream;
	}

	void flush();

	size_t write(const void* vbuf, size_t length)
	{
		if (terark_likely(m_pos+length <= m_end)) {
			memcpy(m_pos, vbuf, length);
			m_pos += length;
			return length;
		} else
			return flush_and_write(vbuf, length);
	}

	void ensureWrite(const void* vbuf, size_t length)
	{
		// 为了效率，这么实现可以让编译器更好地 inline 这个函数
		// inline 后的函数体并尽可能小
		if (terark_likely(m_pos+length <= m_end)) {
			memcpy(m_pos, vbuf, length);
			m_pos += length;
		} else
			flush_and_ensureWrite(vbuf, length);
	}

	void writeByte(byte b)
	{
		if (terark_likely(m_pos < m_end))
			*m_pos++ = b;
		else
			flush_and_write_byte(b);
	}

	size_t printf(const char* format, ...)
#ifdef __GNUC__
	__attribute__ ((__format__ (__printf__, 2, 3)))
#endif
	;

	size_t vprintf(const char* format, va_list ap)
#ifdef __GNUC__
	__attribute__ ((__format__ (__printf__, 2, 0)))
#endif
	;

	#include "var_int_declare_write.hpp"

protected:
	size_t flush_and_write(const void* vbuf, size_t length);
	void   flush_and_ensureWrite(const void* vbuf, size_t length);
	void   flush_and_write_byte(byte b);

	size_t do_flush_and_write(const void* vbuf, size_t length);
};

} // namespace terark

#endif

max_stars_repo_name: noobpwnftw/terark-zip

max_issues_repo_name: noobpwnftw/terark-zip

max_forks_repo_name: noobpwnftw/terark-zip


text:
#include "base_driver.h"
#include "data_holder.h"
#include "simple_dataframe_master.h"

#include <std_msgs/Float32MultiArray.h>
#include <boost/assign/list_of.hpp>
#include <string.h>

#ifdef USE_BOOST_SERIAL_TRANSPORT
#include "serial_transport.h"
#else
#include "serial_transport2.h"
#endif

BaseDriver* BaseDriver::instance = NULL;

BaseDriver::BaseDriver() : pn("~"), bdg(pn)
{
	//init config
	bdg.init(&Data_holder::get()->parameter);

#ifdef USE_BOOST_SERIAL_TRANSPORT
	trans = boost::make_shared<Serial_transport>(bdg.port, bdg.baudrate);
#else
	trans = boost::make_shared<Serial_transport2>(bdg.port, bdg.baudrate);
#endif

	frame = boost::make_shared<Simple_dataframe>(trans.get());

	ROS_INFO("[KUBOT]base driver startup...");
	if (trans->init()) {
		ROS_INFO("[KUBOT]connected to driver board");
	}
	else {
		ROS_ERROR("[KUBOT]oops!!! can't connect to driver board, please check the usb connection or baudrate!");
		return;
	}
/*
	ros::Duration(3).sleep(); //wait for device
	ROS_INFO("[KUBOT]wait for device...");
*/
	frame->init();

	for (int i = 0;i < 3;i++) {
		if (frame->interact(ID_GET_VERSION))
			break;
		ros::Duration(1).sleep(); //wait for device
	}

	ROS_INFO("[KUBOT]robot version:%s build time:%s", Data_holder::get()->firmware_info.version,
		Data_holder::get()->firmware_info.time);

	init_robot_ip();

	init_cmd_odom();

	init_pid_debug();

	read_param();

	init_imu();

	init_sona_data();

	init_robot_status();
}

BaseDriver::~BaseDriver()
{
	if (instance != NULL)
		delete instance;
}

void BaseDriver::init_robot_ip()
{
	strcpy(Data_holder::get()->lcd_status.robot_ip, bdg.robot_ip.c_str());
	frame->interact(ID_SET_ROBOT_IP);
}

void BaseDriver::init_cmd_odom()
{
	frame->interact(ID_INIT_ODOM);

	ROS_INFO_STREAM("[KUBOT]subscribe cmd topic on [" << bdg.cmd_vel_topic << "]");
	cmd_vel_sub = nh.subscribe(bdg.cmd_vel_topic, 1000, &BaseDriver::cmd_vel_callback, this);

	ROS_INFO_STREAM("[KUBOT]advertise odom topic on [" << bdg.odom_topic << "]");
	odom_pub = nh.advertise<nav_msgs::Odometry>(bdg.odom_topic, 50);

	//init odom_trans
	odom_trans.header.frame_id = bdg.odom_frame;
	odom_trans.child_frame_id = bdg.base_frame;

	odom_trans.transform.translation.z = 0;

	//init odom
	odom.header.frame_id = bdg.odom_frame;
	odom.pose.pose.position.z = 0.0;
	odom.child_frame_id = bdg.base_frame;
	odom.twist.twist.linear.y = 0;

	if (!bdg.publish_tf)
	{
		odom.pose.covariance = boost::assign::list_of(1e-3) (0) (0)  (0)  (0)  (0)
			(0) (1e-3)  (0)  (0)  (0)  (0)
			(0)   (0)  (1e6) (0)  (0)  (0)
			(0)   (0)   (0) (1e6) (0)  (0)
			(0)   (0)   (0)  (0) (1e6) (0)
			(0)   (0)   (0)  (0)  (0)  (1e3);

		odom.twist.covariance = boost::assign::list_of(1e-3) (0)   (0)  (0)  (0)  (0)
			(0) (1e-3)  (0)  (0)  (0)  (0)
			(0)   (0)  (1e6) (0)  (0)  (0)
			(0)   (0)   (0) (1e6) (0)  (0)
			(0)   (0)   (0)  (0) (1e6) (0)
			(0)   (0)   (0)  (0)  (0)  (1e3);
	}

	need_update_speed = false;
}

void BaseDriver::cmd_vel_callback(const geometry_msgs::Twist& vel_cmd)
{
	ROS_INFO_STREAM("cmd_vel:[" << vel_cmd.linear.x << " " << vel_cmd.linear.y << " " << vel_cmd.angular.z << "]");

	Data_holder::get()->velocity.v_liner_x = vel_cmd.linear.x * 100;
	Data_holder::get()->velocity.v_liner_y = vel_cmd.linear.y * 100;
	Data_holder::get()->velocity.v_angular_z = vel_cmd.angular.z * 100;

	need_update_speed = true;
}

void BaseDriver::init_pid_debug()
{
	if (bdg.out_pid_debug_enable)
	{
		const char* input_topic_name[MAX_MOTOR_COUNT] = { "motor1_input", "motor2_input", "motor3_input", "motor4_input" };
		const char* output_topic_name[MAX_MOTOR_COUNT] = { "motor1_output", "motor2_output", "motor3_output", "motor4_output" };
		for (size_t i = 0; i < MAX_MOTOR_COUNT; i++)
		{
			pid_debug_pub_input[i] = nh.advertise<std_msgs::Int32>(input_topic_name[i], 1000);
			pid_debug_pub_output[i] = nh.advertise<std_msgs::Int32>(output_topic_name[i], 1000);
		}
	}
}

void BaseDriver::read_param()
{
	Robot_parameter* param = &Data_holder::get()->parameter;
	memset(param, 0, sizeof(Robot_parameter));

	frame->interact(ID_GET_ROBOT_PARAMTER);

	Data_holder::dump_params(param);

	bdg.SetRobotParameters();
}

void BaseDriver::init_imu()
{
	raw_imu_pub = nh.advertise<kubot_msgs::RawImu>("raw_imu", 50);
	raw_imu_msgs.header.frame_id = "imu_link";
	raw_imu_msgs.accelerometer = true;
	raw_imu_msgs.gyroscope = true;
	raw_imu_msgs.magnetometer = true;
}

void BaseDriver::init_sona_data()
{
	raw_sona_data_pub = nh.advertise<kubot_msgs::RawSona>("raw_sona_data_msgs", 50);
	raw_robot_status_msgs.header.frame_id = "sona_data";
}

void BaseDriver::init_robot_status()
{
	raw_robot_status_pub = nh.advertise<kubot_msgs::RawRobot>("raw_robot_status_msgs", 50);
	raw_robot_status_msgs.header.frame_id = "robot_status";
}

void BaseDriver::work_loop()
{
	ros::Rate loop(bdg.freq);
	while (ros::ok()) {
		//boost::posix_time::ptime my_posix_time = ros::Time::now().toBoost();
		update_param();

		update_odom();

		update_pid_debug();

		update_speed();

		if (Data_holder::get()->parameter.imu_type == IMU_TYPE_MPU6050
			|| Data_holder::get()->parameter.imu_type == IMU_TYPE_GY85
			|| Data_holder::get()->parameter.imu_type == IMU_TYPE_GY87
			|| Data_holder::get()->parameter.imu_type == IMU_TYPE_MPU9250
			|| Data_holder::get()->parameter.imu_type == IMU_TYPE_BMI160)
		{
			update_imu();
		}

		update_robot_status();

		update_sona_data();

		loop.sleep();

		ros::spinOnce();
	}
}

void BaseDriver::update_param()
{
#ifdef USE_DYNAMIC_RECONFIG
	if (bdg.get_param_update_flag()) {
		frame->interact(ID_SET_ROBOT_PARAMTER);
		ros::Rate loop(5);
		loop.sleep();
	}
#endif
}

void BaseDriver::update_odom()
{
	frame->interact(ID_GET_ODOM);

	ros::Time current_time = ros::Time::now();

	float x = Data_holder::get()->odom.x * 0.01;
	float y = Data_holder::get()->odom.y * 0.01;
	float th = Data_holder::get()->odom.yaw * 0.01;

	float vxy = Data_holder::get()->odom.v_liner_x * 0.01;
	float vth = Data_holder::get()->odom.v_angular_z * 0.01;

	//ROS_INFO("odom: x=%.2f y=%.2f th=%.2f vxy=%.2f vth=%.2f", x, y ,th, vxy,vth);

	geometry_msgs::Quaternion odom_quat = tf::createQuaternionMsgFromYaw(th);

	//publish_tf
	if (bdg.publish_tf)
	{
		odom_trans.header.stamp = current_time;
		odom_trans.transform.translation.x = x;
		odom_trans.transform.translation.y = y;
		odom_trans.transform.rotation = odom_quat;
		odom_broadcaster.sendTransform(odom_trans);
	}

	//publish the message
	odom.header.stamp = current_time;
	odom.pose.pose.position.x = x;
	odom.pose.pose.position.y = y;
	odom.pose.pose.orientation = odom_quat;
	odom.twist.twist.linear.x = vxy;
	odom.twist.twist.angular.z = vth;

	odom_pub.publish(odom);
}

void BaseDriver::update_speed()
{
	if (need_update_speed) {
		ROS_INFO_STREAM("update_speed");
		need_update_speed = !(frame->interact(ID_SET_VELOCITY));
	}
}

void BaseDriver::update_pid_debug()
{
	if (bdg.out_pid_debug_enable)
	{
		frame->interact(ID_GET_PID_DATA);

		for (size_t i = 0; i < MAX_MOTOR_COUNT; i++)
		{
			pid_debug_msg_input[i].data = Data_holder::get()->pid_data.input[i];
			pid_debug_msg_output[i].data = Data_holder::get()->pid_data.output[i];

			pid_debug_pub_input[i].publish(pid_debug_msg_input[i]);
			pid_debug_pub_output[i].publish(pid_debug_msg_output[i]);
		}
	}
}

void BaseDriver::update_imu()
{
	frame->interact(ID_GET_IMU_DATA);
	raw_imu_msgs.header.stamp = ros::Time::now();

	raw_imu_msgs.raw_linear_acceleration.x = Data_holder::get()->imu_data[0];
	raw_imu_msgs.raw_linear_acceleration.y = Data_holder::get()->imu_data[1];
	raw_imu_msgs.raw_linear_acceleration.z = Data_holder::get()->imu_data[2];
	raw_imu_msgs.raw_angular_velocity.x = Data_holder::get()->imu_data[3];
	raw_imu_msgs.raw_angular_velocity.y = Data_holder::get()->imu_data[4];
	raw_imu_msgs.raw_angular_velocity.z = Data_holder::get()->imu_data[5];
	raw_imu_msgs.raw_magnetic_field.x = Data_holder::get()->imu_data[6];
	raw_imu_msgs.raw_magnetic_field.y = Data_holder::get()->imu_data[7];
	raw_imu_msgs.raw_magnetic_field.z = Data_holder::get()->imu_data[8];

	raw_imu_pub.publish(raw_imu_msgs);
}

int UPDATE_SONA_STATUS_INTERVAL = 1;
void BaseDriver::update_sona_data()
{
	static int last_millis = 0;

	if (ros::Time::now().toSec() - last_millis > UPDATE_SONA_STATUS_INTERVAL) {

		frame->interact(ID_GET_SONA_DATA);
		raw_sona_data_msgs.header.stamp = ros::Time::now();

		raw_sona_data_msgs.sona1_dis = Data_holder::get()->sona_data[0];
		raw_sona_data_msgs.sona2_dis = Data_holder::get()->sona_data[1];
		raw_sona_data_msgs.sona3_dis = Data_holder::get()->sona_data[2];
		raw_sona_data_msgs.sona4_dis = Data_holder::get()->sona_data[3];
		raw_sona_data_msgs.sona5_dis = Data_holder::get()->sona_data[4];
		raw_sona_data_msgs.sona6_dis = Data_holder::get()->sona_data[5];
		raw_sona_data_msgs.sona7_dis = Data_holder::get()->sona_data[6];
		raw_sona_data_msgs.sona8_dis = Data_holder::get()->sona_data[7];

		raw_sona_data_pub.publish(raw_sona_data_msgs);
		last_millis = ros::Time::now().toSec();
	}
}

int UPDATE_ROBOT_STATUS_INTERVAL = 1;
void BaseDriver::update_robot_status()
{
	static int last_millis = 0;
	if (ros::Time::now().toSec() - last_millis > UPDATE_ROBOT_STATUS_INTERVAL) {
		frame->interact(ID_GET_ROBOT_STATUS);
		raw_robot_status_msgs.header.stamp = ros::Time::now();

		raw_robot_status_msgs.bumper_status = Data_holder::get()->robot_status.bumper_status;

		if (bdg.mcu_battery_volatge)
		{
			raw_robot_status_msgs.mcu_voltage = Data_holder::get()->robot_status.mcu_voltage;
		}

		raw_robot_status_pub.publish(raw_robot_status_msgs);
		last_millis = ros::Time::now().toSec();
	}
}

ext: cpp


text:
/* named_endpoint_test.cc                                          -*- C++ -*-
   Jeremy Barnes, 24 September 2012
   Copyright (c) 2012 Datacratic Inc.  All rights reserved.

   Test for named endpoint.
*/

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>
#include <boost/make_shared.hpp>
#include "soa/service/named_endpoint.h"
#include "soa/service/message_loop.h"
#include "soa/service/zmq_endpoint.h"
#include <sys/socket.h>
#include "jml/utils/guard.h"
#include "jml/arch/exception_handler.h"
#include "jml/utils/testing/watchdog.h"
#include "jml/utils/testing/fd_exhauster.h"
#include "jml/utils/vector_utils.h"
#include "jml/arch/timers.h"
#include <thread>
#include "soa/service/zmq_utils.h"
#include "soa/service/testing/zookeeper_temporary_server.h"

using namespace std;
using namespace ML;
using namespace Datacratic;

/*****************************************************************************/
/* ECHO SERVICE                                                              */
/*****************************************************************************/

/** Simple test service that listens on zeromq and simply echos everything
    that it gets back.
*/

struct EchoService : public ServiceBase {

    EchoService(std::shared_ptr<ServiceProxies> proxies,
                const std::string & serviceName)
        : ServiceBase(serviceName, proxies),
          context(new zmq::context_t(1)),
          endpoint(context),
          loop(1 /* num threads */, 0.0001 /* maxAddedLatency */)
    {
        proxies->config->removePath(serviceName);
        //registerService();
        endpoint.init(proxies->config, ZMQ_XREP, serviceName + "/echo");

        auto handler = [=] (vector<string> message)
            {
                //cerr << "got message " << message << endl;
                ExcAssertEqual(message.size(), 3);
                ExcAssertEqual(message[1], "ECHO");
                message[1] = "REPLY";

                endpoint.sendMessage(message);
            };

        endpoint.messageHandler = handler;

        loop.addSource("EchoService::endpoint", endpoint);
    }

    void start()
    {
        loop.start();
    }

    void shutdown()
    {
        loop.shutdown();
    }

    std::string bindTcp()
    {
        return endpoint.bindTcp();
    }

    std::shared_ptr<zmq::context_t> context;
    ZmqNamedEndpoint endpoint;
    MessageLoop loop;
};

BOOST_AUTO_TEST_CASE( test_named_endpoint )
{
    ZooKeeper::TemporaryServer zookeeper;
    zookeeper.start();

    auto proxies = std::make_shared<ServiceProxies>();
    proxies->useZookeeper(ML::format("localhost:%d", zookeeper.getPort()));

    EchoService service(proxies, "echo");
    auto addr = service.bindTcp();
    cerr << "echo service is listening on " << addr << endl;

    service.start();

    proxies->config->dump(cerr);

    volatile int numPings = 0;

    auto runThread = [&] ()
        {
            ZmqNamedProxy proxy;
            proxy.init(proxies->config, ZMQ_XREQ);
            proxy.connect("echo/echo");

            ML::sleep(0.1);

            cerr << "connected" << endl;

            while (numPings < 100000) {
                int i = __sync_add_and_fetch(&numPings, 1);

                if (i && i % 1000 == 0)
                    cerr << i << endl;

                vector<string> request;
                request.push_back("ECHO");
                request.push_back(to_string(i));

                sendAll(proxy.socket(), request);

                vector<string> res = recvAll(proxy.socket());

                ExcAssertEqual(res.size(), 2);
                ExcAssertEqual(res[0], "REPLY");
                ExcAssertEqual(res[1], to_string(i));
            }
        };

    boost::thread_group threads;
    for (unsigned i = 0;  i < 10;  ++i) {
        threads.create_thread(runThread);
    }

    threads.join_all();

    cerr << "finished requests" << endl;

    service.shutdown();
}

ext: cc

max_stars_repo_name: etnrlz/rtbkit

max_issues_repo_name: leobispo/soa

max_forks_repo_name: leobispo/soa


text: #include <boost/spirit/home/classic/dynamic/for.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
/**

\file
\author Datta Ramadasan
//==============================================================================
//         Copyright 2015 INSTITUT PASCAL UMR 6602 CNRS/Univ. Clermont II
//
//          Distributed under the Boost Software License, Version 1.0.
//                 See accompanying file LICENSE.txt or copy at
//                     http://www.boost.org/LICENSE_1_0.txt
//==============================================================================

*/

#ifndef __TTT_TRAITS_FUNCTIONTRAIT_HPP__
#define __TTT_TRAITS_FUNCTIONTRAIT_HPP__

#include <libv/lma/global.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/back.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/pop_back.hpp>
#include <boost/mpl/size.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_reference.hpp>
#include <type_traits>

namespace ttt
{
  // récupérer les paramètres d'une fonction membre const
  template<class> struct Extract;
  template<class Return, class F, class ...T> struct Extract< Return (F::*) (T...) const >
  {
    typedef Return ReturnType;
    typedef mpl::vector<T...> tmp1;
    typedef typename mpl::transform<tmp1,std::decay<mpl::_1>>::type tmp2;
    typedef typename mpl::back<tmp1>::type Residu;
    typedef typename mpl::pop_back<tmp2>::type Args;
  };

  template<class F> struct FunctorTrait
  {
    typedef F FunctorType;
    typedef Extract<FunctorType> Ext;

    typedef typename Ext::ReturnType ReturnType;
    typedef typename Ext::Residu Residu;
    typedef typename Ext::Args ParametersType;

    static const std::size_t size = mpl::size<ParametersType>::value;

    static_assert( boost::is_same<ReturnType,bool>::value, " Functor::operator() return type must be bool");
    static_assert( boost::is_reference<Residu>::value, " Functor::operator(param1,...,paramN, Residual& residual) : residual must be given by reference");
    static_assert( size !=0 , "Don't forget parameter or residual : Functor::operator(param1,...,paramN, Residual& residual)");
  };
}// eon

#endif

max_stars_repo_name: bezout/LMA

max_issues_repo_name: ayumizll/LMA

max_forks_repo_name: bezout/LMA


text:
#ifndef SKELETONS_API_HPP
#define SKELETONS_API_HPP

#include <boost/parameter.hpp>
#include <boost/serialization/access.hpp>

namespace YewPar { namespace Skeletons {

namespace parameter = boost::parameter;

namespace API {

// Compile time configuration

// Parameters that can be used by simply adding them to the template arg list (value-less)
#define DEF_PRESENT_PARAMETER(name, param)                      \
  BOOST_PARAMETER_TEMPLATE_KEYWORD(param)                       \
  struct name : param<std::integral_constant<bool, true> > {};

// Tree Search Types
DEF_PRESENT_PARAMETER(CountNodes, CountNodes_)
DEF_PRESENT_PARAMETER(Optimisation, Optimisation_)
DEF_PRESENT_PARAMETER(Decision, Decision_)

// Search Shape changers
DEF_PRESENT_PARAMETER(DepthLimited, DepthLimited_)

// Bounding/Pruning
BOOST_PARAMETER_TEMPLATE_KEYWORD(BoundFunction)
BOOST_PARAMETER_TEMPLATE_KEYWORD(ObjectiveComparison)
BOOST_PARAMETER_TEMPLATE_KEYWORD(MaxStackDepth)

// Optimisations
DEF_PRESENT_PARAMETER(PruneLevel, PruneLevel_)

// Depth bounded policies
BOOST_PARAMETER_TEMPLATE_KEYWORD(DepthBoundedPoolPolicy)

// Ordered Discrpancy search toggle
DEF_PRESENT_PARAMETER(DiscrepancySearch, DiscrepancySearch_)

// Verbose output
BOOST_PARAMETER_TEMPLATE_KEYWORD(Verbose_)
// Basic Info
struct Verbose : Verbose_<std::integral_constant<unsigned, 1> > {};
// Basic Info + Updates
struct MoreVerbose : Verbose_<std::integral_constant<unsigned, 2> > {};
// Basic Info + Updates + Parallelism information
struct EvenMoreVerbose : Verbose_<std::integral_constant<unsigned, 3> > {};

// Signature, everything is optional since the generators are explicitly passed as arg 1 on each skeleton
BOOST_PARAMETER_TEMPLATE_KEYWORD(null)
typedef parameter::parameters<parameter::optional<tag::null> > skeleton_signature;

template <typename Obj = bool>
struct Params {
  // For depth limited searches
  unsigned maxDepth = 5000;

  // For decision based problems
  Obj expectedObjective;

  // For B&B
  Obj initialBound = false;

  // Depth Spawns
  unsigned spawnDepth = 1;

  // Stack Steals
  // Should we steal all remaining nodes at the highest depth or just one?
  bool stealAll = false;

  // Budget
  // FIXME: How to determine a good value for this?
  unsigned backtrackBudget = 200;

  // Needed to push to registries on all nodes
  template <class Archive>
  void serialize(Archive & ar, const unsigned int version) {
    ar & maxDepth;
    ar & expectedObjective;
    ar & initialBound;
    ar & spawnDepth;
    ar & stealAll;
    ar & backtrackBudget;
  }
};

}}}

#endif

max_stars_repo_name: kyriacossofocleous/YewPar

max_issues_repo_name: kyriacossofocleous/YewPar

max_forks_repo_name: kyriacossofocleous/YewPar


text:
//
// Copyright (c) 2021 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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)
//
// Official repository: https://github.com/CPPAlliance/http_proto
//

#ifndef BOOST_HTTP_PROTO_IMPL_FIELDS_BASE_IPP
#define BOOST_HTTP_PROTO_IMPL_FIELDS_BASE_IPP

#include <boost/http_proto/fields.hpp>
#include <boost/http_proto/detail/copied_strings.hpp>
#include <boost/http_proto/detail/except.hpp>
#include <boost/http_proto/detail/fields_table.hpp>
#include <boost/assert.hpp>
#include <boost/assert/source_location.hpp>
#include <string>

namespace boost {
namespace http_proto {

fields_base::
~fields_base()
{
    if(buf_)
        delete[] buf_;
}

fields_base::
fields_base(
    ctor_params const& init) noexcept
    : fields_view_base(init)
    , buf_(init.buf)
    , kind_(init.kind)
{
}

fields_base::
fields_base(
    char kind) noexcept
    : fields_view_base(kind)
    , buf_(nullptr)
    , kind_(kind)
{
}

// copy with start-line
fields_base::
fields_base(
    fields_view_base const& fv,
    char kind)
    : fields_base(
    [&fv, kind]
    {
        ctor_params init;
        if(! is_default(fv.cbuf_))
        {
            // copy start line and fields
            auto n = detail::buffer_needed(
                fv.end_pos_, fv.count_);
            auto buf = new char[n];
            std::memcpy(
                buf, fv.cbuf_, fv.end_pos_);
            fv.write_table(buf + n);
            init.cbuf = buf;
            init.buf_len = n;
            init.start_len = fv.start_len_;
            init.end_pos = fv.end_pos_;
            init.count = fv.count_;
            init.buf = buf;
            init.kind = kind;
            return init;
        }

        // default buffer
        init.cbuf = fv.cbuf_;
        init.buf_len = 0;
        init.start_len = fv.start_len_;
        init.end_pos = fv.end_pos_;
        init.count = fv.count_;
        init.buf = nullptr;
        init.kind = kind;
        return init;
    }())
{
}

// copy everything
void
fields_base::
copy(fields_view_base const& other)
{
    if(! is_default(other.cbuf_))
    {
        auto n = detail::buffer_needed(
            other.end_pos_, other.count_);
        if(n <= buf_len_)
        {
            // copy start line and fields
            other.write_table(buf_ + end_pos_);
            std::memcpy(
                buf_,
                other.cbuf_,
                other.end_pos_);
            start_len_ = other.start_len_;
            end_pos_ = other.end_pos_;
            count_ = other.count_;
            return;
        }
    }
    fields_base tmp(other, kind_);
    tmp.swap(*this);
}

//------------------------------------------------
//
// Modifiers
//
//------------------------------------------------

void
fields_base::
reserve(std::size_t n)
{
    // align up
    n = detail::buffer_needed(n, 0);
    if(n <= buf_len_)
        return;
    auto buf = new char[n];
    if(buf_len_ > 0)
    {
        std::memcpy(
            buf,
            cbuf_,
            end_pos_);
        write_table(buf + n);
        delete[] buf_;
    }
    else
    {
        // default buffer
        std::memcpy(
            buf,
            cbuf_,
            end_pos_);
    }
    buf_len_ = n;
    cbuf_ = buf;
    buf_ = buf;
}

void
fields_base::
shrink_to_fit() noexcept
{
    if(detail::buffer_needed(
        end_pos_, count_) >=
            buf_len_)
        return;
    fields_base(*this, 0).swap(*this);
}

void
fields_base::
emplace_back(
    field id,
    string_view value)
{
    insert_impl(
        id,
        to_string(id),
        value,
        count_);
}

void
fields_base::
emplace_back(
    string_view name,
    string_view value)
{
    insert_impl(
        string_to_field(
            name),
        name,
        value,
        count_);
}

auto
fields_base::
emplace(
    iterator before,
    field id,
    string_view value) ->
        iterator
{
    insert_impl(
        id,
        to_string(id),
        value,
        before.i_);
    return before;
}

auto
fields_base::
emplace(
    iterator before,
    string_view name,
    string_view value) ->
        iterator
{
    insert_impl(
        string_to_field(name),
        name,
        value,
        before.i_);
    return before;
}

auto
fields_base::
erase(iterator it) noexcept ->
    iterator
{
    BOOST_ASSERT(it.i_ < count_);
    BOOST_ASSERT(buf_ != nullptr);
    detail::fields_table ft(
        buf_ + buf_len_);
    auto const p0 =
        offset(ft, it.i_);
    auto const p1 =
        offset(ft, it.i_ + 1);
    std::memmove(
        buf_ + p0,
        buf_ + p1,
        end_pos_ - p1);
    auto const n = p1 - p0;
    --count_;
    for(std::size_t i = it.i_;
            i < count_; ++i)
        ft[i] = ft[i + 1] - n;
    end_pos_ = static_cast<
        off_t>(end_pos_ - n);
    return iterator(this, it.i_);
}

std::size_t
fields_base::
erase(
    field id) noexcept
{
    auto it = find(id);
    if(it != end())
    {
        erase(it);
        return 1;
    }
    return 0;
}

std::size_t
fields_base::
erase(
    string_view name) noexcept
{
    auto it = find(name);
    if(it != end())
    {
        erase(it);
        return 1;
    }
    return 0;
}

std::size_t
fields_base::
erase_all(
    field id) noexcept
{
    std::size_t n = 0;
    std::size_t i = count_;
    while(i > 0)
    {
        --i;
        iterator it(this, i);
        if(it->id != id)
            continue;
        erase(it);
        ++n;
    }
    return n;
}

std::size_t
fields_base::
erase_all(
    string_view name) noexcept
{
    // find the first occurrence and use
    // its string instead, to handle the
    // case where `name` comes from the
    // fields buffer.
    auto it0 = find(name);
    if(it0 == end())
        return 0;
    name = it0->name;
    std::size_t n = 1;
    std::size_t i = count_ - 1;
    while(i != it0.i_)
    {
        iterator it(this, i);
        if(bnf::iequals(
            it->name, name))
        {
            erase(it);
            ++n;
        }
        --i;
    }
    erase(it0);
    return n;
}

//------------------------------------------------
//
// (implementation)
//
//------------------------------------------------

// return i-th field absolute offset
std::size_t
fields_base::
offset(
    detail::fields_table const& ft,
    std::size_t i) const noexcept
{
    if(i < count_)
        return start_len_ + ft[i].np;
    // make final CRLF the last "field"
    BOOST_ASSERT(i == count_);
    return end_pos_ - 2;
}

void
fields_base::
insert_impl(
    field id,
    string_view name,
    string_view value,
    std::size_t before)
{
    BOOST_ASSERT(before <= count_);
    auto const n0 =
        name.size() + 2 +
        value.size() + 2;
    auto const n1 = end_pos_ + n0;
    if(n1 > max_off_t)
        detail::throw_length_error(
            "too large",
            BOOST_CURRENT_LOCATION);
    auto const n =
        detail::buffer_needed(
            n1, count_ + 1);
    if(buf_len_ >= n)
    {
        BOOST_ASSERT(buf_ != nullptr);
        detail::copied_strings cs(
            string_view(cbuf_, end_pos_));
        name = cs.maybe_copy(name);
        value = cs.maybe_copy(value);
        detail::fields_table ft(
            buf_ + buf_len_);
        auto pos = offset(ft, before);
        char* dest = buf_ + pos;
        std::memmove(
            dest + n0,
            dest,
            end_pos_ - pos);
        name.copy(dest, name.size());
        dest += name.size();
        *dest++ = ':';
        *dest++ = ' ';
        value.copy(dest, value.size());
        dest += value.size();
        *dest++ = '\r';
        *dest++ = '\n';
        for(std::size_t i = count_;
            i > before; --i)
            ft[i] = ft[i-1] + n0;
        pos -= start_len_;
        auto& e = ft[before];
        e.np = static_cast<
            off_t>(pos);
        e.nn = static_cast<
            off_t>(name.size());
        e.vp = static_cast<off_t>(
            pos + name.size() + 2);
        e.vn = static_cast<
            off_t>(value.size());
        e.id = id;
        end_pos_ = static_cast<
            off_t>(end_pos_ + n0);
        ++count_;
    }
    else if(buf_len_ > 0)
    {
        // grow
        BOOST_ASSERT(buf_ != nullptr);
        auto buf = new char[n];

        // copy existing fields
        // and write new field
        detail::fields_table ft0(
            buf_ + buf_len_);
        auto pos = offset(ft0, before);
        char* dest = buf;
        std::memcpy(
            dest,
            buf_,
            pos);
        dest += pos;
        name.copy(dest, name.size());
        dest += name.size();
        *dest++ = ':';
        *dest++ = ' ';
        value.copy(dest, value.size());
        dest += value.size();
        *dest++ = '\r';
        *dest++ = '\n';
        std::memcpy(
            dest,
            buf_ + pos,
            end_pos_ - pos);

        // write table
        ft0.copy(buf + n, before);
        detail::fields_table ft(buf + n);
        for(auto i = before;
            i < count_; ++i)
            ft[i + 1] = ft0[i] + n0;

        auto& e = ft[before];
        e.np = static_cast<
            off_t>(pos);
        e.nn = static_cast<
            off_t>(name.size());
        e.vp = static_cast<off_t>(
            pos + name.size() + 2);
        e.vn = static_cast<
            off_t>(value.size());
        e.id = id;

        delete[] buf_;
        buf_ = buf;
        cbuf_ = buf;
        buf_len_ = n;
        end_pos_ = static_cast<
            off_t>(n1);
        count_ += 1;
    }
    else
    {
        BOOST_ASSERT(buf_ == nullptr);
        BOOST_ASSERT(before == 0);
        BOOST_ASSERT(count_ == 0);

        // initial allocation
        auto s = default_buffer(kind_);
        buf_ = new char[n];
        cbuf_ = buf_;
        buf_len_ = n;
        start_len_ = static_cast<
            off_t>(s.size() - 2);
        end_pos_ = static_cast<
            off_t>(n1);
        count_ = 1;

        // start line
        char* dest = buf_;
        s.copy(dest, start_len_);
        dest += start_len_;

        // write field
        name.copy(dest, name.size());
        dest += name.size();
        *dest++ = ':';
        *dest++ = ' ';
        value.copy(dest, value.size());
        dest += value.size();
        *dest++ = '\r';
        *dest++ = '\n';

        *dest++ = '\r';
        *dest++ = '\n';

        // write table
        detail::fields_table ft(
            buf_ + buf_len_);
        auto& e = ft[before];
        e.id = id;
        e.np = 0;
        e.nn = static_cast<
            off_t>(name.size());
        e.vp = static_cast<
            off_t>(name.size() + 2);
        e.vn = static_cast<
            off_t>(value.size());
    }
}

//------------------------------------------------

void
fields_base::
swap(fields_base& other) noexcept
{
    using std::swap;
    this->fields_view_base::swap(other);
    swap(buf_, other.buf_);
    swap(kind_, other.kind_);
}

void
fields_base::
clear() noexcept
{
    if(! buf_)
        return;
    auto s =
        default_buffer(kind_);
    end_pos_ = static_cast<
        off_t>(s.size());
    start_len_ = end_pos_ - 2;
    count_ = 0;
    std::memcpy(
        buf_,
        s.data(),
        end_pos_);
}

char*
fields_base::
set_start_line_impl(
    std::size_t n)
{
    if( n > start_len_ ||
        buf_ == nullptr)
    {
        // allocate or grow
        if( n > start_len_ &&
            n - start_len_ >
                max_off_t - end_pos_)
            detail::throw_length_error(
                "too large",
                BOOST_CURRENT_LOCATION);
        auto n0 = detail::buffer_needed(
            n + end_pos_ - start_len_,
            count_);
        auto buf = new char[n0];
        if(buf_ != nullptr)
        {
            std::memcpy(
                buf + n,
                buf_ + start_len_,
                end_pos_ - start_len_);
            detail::fields_table ft(
                buf_ + buf_len_);
            ft.copy(buf + n0, count_);
            delete[] buf_;
        }
        else
        {
            std::memcpy(
                buf + n,
                cbuf_ + start_len_,
                end_pos_ - start_len_);
        }
        buf_ = buf;
        cbuf_ = buf;
        end_pos_ = static_cast<
            off_t>(end_pos_ +
                n - start_len_);
        start_len_ = static_cast<
            off_t>(n);
        buf_len_ = n0;
        return buf_;
    }

    // shrink
    std::memmove(
        buf_ + n,
        buf_ + start_len_,
        end_pos_ - start_len_);
    end_pos_ = static_cast<
        off_t>(end_pos_ -
            start_len_ + n);
    start_len_ = static_cast<
        off_t>(n);
    return buf_;
}

} // http_proto
} // boost

#endif

ext: ipp