<commit_before>// ----------------------------------------------------------------------------
// Constants.cpp
//
//
// Authors:
// Peter Polidoro peterpolidoro@gmail.com
// ----------------------------------------------------------------------------
#include "Constants.h"

namespace modular_server
{
namespace constants
{
CONSTANT_STRING(firmware_name,"ModularServer");
// Use semantic versioning http://semver.org/
const FirmwareInfo firmware_info =
{
  .name_ptr=&firmware_name,
  .version_major=5,
  .version_minor=0,
  .version_patch=3,
};

const long response_pipe_read_max = 100000;

const double epsilon = 0.000000001;

// Pins
const size_t pin_pulse_timer_number = 3;
const uint32_t pin_pulse_delay = 0;
const uint32_t pin_pulse_count = 1;
CONSTANT_STRING(pin_mode_digital_input,"DIGITAL_INPUT");
CONSTANT_STRING(pin_mode_digital_input_pullup,"DIGITAL_INPUT_PULLUP");
CONSTANT_STRING(pin_mode_digital_output,"DIGITAL_OUTPUT");
CONSTANT_STRING(pin_mode_analog_input,"ANALOG_INPUT");
CONSTANT_STRING(pin_mode_analog_output,"ANALOG_OUTPUT");
CONSTANT_STRING(pin_mode_pulse_rising,"PULSE_RISING");
CONSTANT_STRING(pin_mode_pulse_falling,"PULSE_FALLING");
CONSTANT_STRING(pin_mode_interrupt_low,"INTERRUPT_LOW");
CONSTANT_STRING(pin_mode_interrupt_change,"INTERRUPT_CHANGE");
CONSTANT_STRING(pin_mode_interrupt_rising,"INTERRUPT_RISING");
CONSTANT_STRING(pin_mode_interrupt_falling,"INTERRUPT_FALLING");

// Properties
CONSTANT_STRING(serial_number_property_name,"serialNumber");
const long serial_number_min = 0;
const long serial_number_max = 65535;
const long serial_number_default = serial_number_min;

// Parameters
CONSTANT_STRING(verbosity_names,"NAMES");
CONSTANT_STRING(verbosity_general,"GENERAL");
CONSTANT_STRING(verbosity_detailed,"DETAILED");
SubsetMemberType verbosity_ptr_subset[VERBOSITY_SUBSET_LENGTH] =
{
  {.cs_ptr=&verbosity_names},
  {.cs_ptr=&verbosity_general},
  {.cs_ptr=&verbosity_detailed},
};

CONSTANT_STRING(pin_name_parameter_name,"pin_name");

SubsetMemberType pin_mode_ptr_subset[PIN_MODE_SUBSET_LENGTH] =
{
  {.cs_ptr=&pin_mode_digital_input},
  {.cs_ptr=&pin_mode_digital_input_pullup},
  {.cs_ptr=&pin_mode_digital_output},
  {.cs_ptr=&pin_mode_analog_input},
  {.cs_ptr=&pin_mode_analog_output},
  {.cs_ptr=&pin_mode_pulse_rising},
  {.cs_ptr=&pin_mode_pulse_falling},
};

CONSTANT_STRING(pin_value_parameter_name,"pin_value");
const long pin_value_min = 0;
const long pin_value_max = 255;

// Functions
CONSTANT_STRING(get_method_ids_function_name,"getMethodIds");
CONSTANT_STRING(help_function_name,"?");
CONSTANT_STRING(verbose_help_function_name,"??");
CONSTANT_STRING(get_device_id_function_name,"getDeviceId");
CONSTANT_STRING(get_device_info_function_name,"getDeviceInfo");
CONSTANT_STRING(get_api_function_name,"getApi");
CONSTANT_STRING(get_property_default_values_function_name,"getPropertyDefaultValues");
CONSTANT_STRING(set_properties_to_defaults_function_name,"setPropertiesToDefaults");
CONSTANT_STRING(get_property_values_function_name,"getPropertyValues");
CONSTANT_STRING(get_pin_info_function_name,"getPinInfo");
CONSTANT_STRING(set_pin_mode_function_name,"setPinMode");
CONSTANT_STRING(get_pin_value_function_name,"getPinValue");
CONSTANT_STRING(set_pin_value_function_name,"setPinValue");
CONSTANT_STRING(get_memory_free_function_name,"getMemoryFree");

// Callbacks

// Errors
CONSTANT_STRING(parse_error_message,"Parse error");
CONSTANT_STRING(invalid_request_error_message,"Invalid Request");
CONSTANT_STRING(method_not_found_error_message,"Method not found");
CONSTANT_STRING(invalid_params_error_message,"Invalid params");
CONSTANT_STRING(server_error_error_message,"Server error");

CONSTANT_STRING(object_request_error_data,"JSON object requests not supported. Must use compact JSON array format for requests.");
CONSTANT_STRING(request_length_error_data,"Request length too long.");
CONSTANT_STRING(parameter_not_found_error_data,"Parameter not found");
CONSTANT_STRING(property_not_found_error_data,"Property not found");
CONSTANT_STRING(property_not_array_type_error_data,"Property not array type");
CONSTANT_STRING(property_element_index_out_of_bounds_error_data,"property_element_index out of bounds");
CONSTANT_STRING(cannot_set_element_in_string_property_with_subset_error_data,"Cannot set element in string property with subset.");
CONSTANT_STRING(incorrect_parameter_number_error_data,"Incorrect number of parameters. ")
CONSTANT_STRING(invalid_json_object_error_data," is not a valid JSON object.")
CONSTANT_STRING(invalid_json_array_error_data," is not a valid JSON array.")
CONSTANT_STRING(parameter_error_error_data,"Parameter value not valid. ");
CONSTANT_STRING(array_parameter_error_error_data,"Array parameter element value not valid. ");
CONSTANT_STRING(array_parameter_length_error_error_data,"Array parameter length not valid. ");
CONSTANT_STRING(value_not_in_subset_error_data,"Value not in subset: ");
CONSTANT_STRING(value_not_in_range_error_data,"Value not in range: ");
CONSTANT_STRING(property_function_not_found_error_data,"Property function not found");
CONSTANT_STRING(incorrect_property_parameter_number_error_data,"Incorrect number of property parameters. ")
CONSTANT_STRING(callback_function_not_found_error_data,"Callback function not found");
CONSTANT_STRING(incorrect_callback_parameter_number_error_data,"Incorrect number of callback parameters. ")

const int parse_error_code = -32700;
const int invalid_request_error_code = -32600;
const int method_not_found_error_code = -32601;
const int invalid_params_error_code = -32602;
const int internal_error_error_code = -32603;
const int server_error_error_code = -32000;

// Saved Variables
const size_t eeprom_initialized_default_value = 123;

// Constant Strings
CONSTANT_STRING(empty_constant_string,"");
CONSTANT_STRING(id_constant_string,"id");
CONSTANT_STRING(error_constant_string,"error");
CONSTANT_STRING(message_constant_string,"message");
CONSTANT_STRING(data_constant_string,"data");
CONSTANT_STRING(code_constant_string,"code");
CONSTANT_STRING(form_factor_constant_string,"form_factor");
CONSTANT_STRING(serial_number_constant_string,"serial_number");
CONSTANT_STRING(firmware_constant_string,"firmware");
CONSTANT_STRING(hardware_constant_string,"hardware");
CONSTANT_STRING(name_constant_string,"name");
CONSTANT_STRING(type_constant_string,"type");
CONSTANT_STRING(units_constant_string,"units");
CONSTANT_STRING(result_constant_string,"result");
CONSTANT_STRING(result_info_constant_string,"result_info");
CONSTANT_STRING(array_element_type_constant_string,"array_element_type");
CONSTANT_STRING(properties_constant_string,"properties");
CONSTANT_STRING(parameters_constant_string,"parameters");
CONSTANT_STRING(functions_constant_string,"functions");
CONSTANT_STRING(callbacks_constant_string,"callbacks");
CONSTANT_STRING(callback_constant_string,"callback");
CONSTANT_STRING(min_constant_string,"min");
CONSTANT_STRING(max_constant_string,"max");
CONSTANT_STRING(array_element_min_constant_string,"array_element_min");
CONSTANT_STRING(array_element_max_constant_string,"array_element_max");
CONSTANT_STRING(array_length_min_constant_string,"array_length_min");
CONSTANT_STRING(array_length_max_constant_string,"array_length_max");
CONSTANT_STRING(string_length_max_constant_string,"string_length_max");
CONSTANT_STRING(version_constant_string,"version");
CONSTANT_STRING(part_number_constant_string,"part_number");
CONSTANT_STRING(device_id_constant_string,"device_id");
CONSTANT_STRING(device_info_constant_string,"device_info");
CONSTANT_STRING(api_constant_string,"api");
CONSTANT_STRING(verbosity_constant_string,"verbosity");
CONSTANT_STRING(value_constant_string,"value");
CONSTANT_STRING(default_value_constant_string,"default_value");
CONSTANT_STRING(question_constant_string,"?");
CONSTANT_STRING(question_double_constant_string,"??");
CONSTANT_STRING(zero_constant_string,"0");
CONSTANT_STRING(given_constant_string," given. ");
CONSTANT_STRING(needed_constant_string," needed.");
CONSTANT_STRING(less_than_equal_constant_string," <= ");
CONSTANT_STRING(element_constant_string," element");
CONSTANT_STRING(array_length_constant_string,"array_length");
CONSTANT_STRING(array_length_default_constant_string,"array_length_default");
CONSTANT_STRING(array_length_spaces_constant_string," array length");
CONSTANT_STRING(string_length_constant_string,"string_length");
CONSTANT_STRING(array_open_constant_string,"[");
CONSTANT_STRING(array_close_constant_string,"]");
CONSTANT_STRING(array_separator_constant_string,",");
CONSTANT_STRING(version_property_separator_constant_string,".");
CONSTANT_STRING(subset_constant_string,"subset");
CONSTANT_STRING(all_constant_string,"ALL");
CONSTANT_STRING(array_element_subset_constant_string,"array_element_subset");
CONSTANT_STRING(pins_constant_string,"pins");
CONSTANT_STRING(interrupt_number_constant_string,"interrupt_number");
CONSTANT_STRING(pin_number_constant_string,"pin_number");
CONSTANT_STRING(pin_mode_constant_string,"pin_mode");
CONSTANT_STRING(processor_constant_string,"processor");

#if defined(__AVR_ATmega1280__)
CONSTANT_STRING(processor_name_constant_string,"ATmega1280");
#elif defined(__AVR_ATmega2560__)
CONSTANT_STRING(processor_name_constant_string,"ATmega2560");
#elif defined(__MK20DX128__)
CONSTANT_STRING(processor_name_constant_string,"MK20DX128");
#elif defined(__MK20DX256__)
CONSTANT_STRING(processor_name_constant_string,"MK20DX256");
#elif defined(__MK64FX512__)
CONSTANT_STRING(processor_name_constant_string,"MK64FX512");
#elif defined(__MK66FX1M0__)
CONSTANT_STRING(processor_name_constant_string,"MK66FX1M0");
#else
CONSTANT_STRING(processor_name_constant_string,"");
#endif

ConstantString * all_c_style_array[ALL_ARRAY_SIZE] =
{
  &all_constant_string,
};
Array<ConstantString *,ALL_ARRAY_SIZE> all_array(all_c_style_array);

}
}
<commit_msg>Add Teensy 4 processor<commit_after>// ----------------------------------------------------------------------------
// Constants.cpp
//
//
// Authors:
// Peter Polidoro peterpolidoro@gmail.com
// ----------------------------------------------------------------------------
#include "Constants.h"

namespace modular_server
{
namespace constants
{
CONSTANT_STRING(firmware_name,"ModularServer");
// Use semantic versioning http://semver.org/
const FirmwareInfo firmware_info =
{
  .name_ptr=&firmware_name,
  .version_major=5,
  .version_minor=0,
  .version_patch=3,
};

const long response_pipe_read_max = 100000;

const double epsilon = 0.000000001;

// Pins
const size_t pin_pulse_timer_number = 3;
const uint32_t pin_pulse_delay = 0;
const uint32_t pin_pulse_count = 1;
CONSTANT_STRING(pin_mode_digital_input,"DIGITAL_INPUT");
CONSTANT_STRING(pin_mode_digital_input_pullup,"DIGITAL_INPUT_PULLUP");
CONSTANT_STRING(pin_mode_digital_output,"DIGITAL_OUTPUT");
CONSTANT_STRING(pin_mode_analog_input,"ANALOG_INPUT");
CONSTANT_STRING(pin_mode_analog_output,"ANALOG_OUTPUT");
CONSTANT_STRING(pin_mode_pulse_rising,"PULSE_RISING");
CONSTANT_STRING(pin_mode_pulse_falling,"PULSE_FALLING");
CONSTANT_STRING(pin_mode_interrupt_low,"INTERRUPT_LOW");
CONSTANT_STRING(pin_mode_interrupt_change,"INTERRUPT_CHANGE");
CONSTANT_STRING(pin_mode_interrupt_rising,"INTERRUPT_RISING");
CONSTANT_STRING(pin_mode_interrupt_falling,"INTERRUPT_FALLING");

// Properties
CONSTANT_STRING(serial_number_property_name,"serialNumber");
const long serial_number_min = 0;
const long serial_number_max = 65535;
const long serial_number_default = serial_number_min;

// Parameters
CONSTANT_STRING(verbosity_names,"NAMES");
CONSTANT_STRING(verbosity_general,"GENERAL");
CONSTANT_STRING(verbosity_detailed,"DETAILED");
SubsetMemberType verbosity_ptr_subset[VERBOSITY_SUBSET_LENGTH] =
{
  {.cs_ptr=&verbosity_names},
  {.cs_ptr=&verbosity_general},
  {.cs_ptr=&verbosity_detailed},
};

CONSTANT_STRING(pin_name_parameter_name,"pin_name");

SubsetMemberType pin_mode_ptr_subset[PIN_MODE_SUBSET_LENGTH] =
{
  {.cs_ptr=&pin_mode_digital_input},
  {.cs_ptr=&pin_mode_digital_input_pullup},
  {.cs_ptr=&pin_mode_digital_output},
  {.cs_ptr=&pin_mode_analog_input},
  {.cs_ptr=&pin_mode_analog_output},
  {.cs_ptr=&pin_mode_pulse_rising},
  {.cs_ptr=&pin_mode_pulse_falling},
};

CONSTANT_STRING(pin_value_parameter_name,"pin_value");
const long pin_value_min = 0;
const long pin_value_max = 255;

// Functions
CONSTANT_STRING(get_method_ids_function_name,"getMethodIds");
CONSTANT_STRING(help_function_name,"?");
CONSTANT_STRING(verbose_help_function_name,"??");
CONSTANT_STRING(get_device_id_function_name,"getDeviceId");
CONSTANT_STRING(get_device_info_function_name,"getDeviceInfo");
CONSTANT_STRING(get_api_function_name,"getApi");
CONSTANT_STRING(get_property_default_values_function_name,"getPropertyDefaultValues");
CONSTANT_STRING(set_properties_to_defaults_function_name,"setPropertiesToDefaults");
CONSTANT_STRING(get_property_values_function_name,"getPropertyValues");
CONSTANT_STRING(get_pin_info_function_name,"getPinInfo");
CONSTANT_STRING(set_pin_mode_function_name,"setPinMode");
CONSTANT_STRING(get_pin_value_function_name,"getPinValue");
CONSTANT_STRING(set_pin_value_function_name,"setPinValue");
CONSTANT_STRING(get_memory_free_function_name,"getMemoryFree");

// Callbacks

// Errors
CONSTANT_STRING(parse_error_message,"Parse error");
CONSTANT_STRING(invalid_request_error_message,"Invalid Request");
CONSTANT_STRING(method_not_found_error_message,"Method not found");
CONSTANT_STRING(invalid_params_error_message,"Invalid params");
CONSTANT_STRING(server_error_error_message,"Server error");

CONSTANT_STRING(object_request_error_data,"JSON object requests not supported. Must use compact JSON array format for requests.");
CONSTANT_STRING(request_length_error_data,"Request length too long.");
CONSTANT_STRING(parameter_not_found_error_data,"Parameter not found");
CONSTANT_STRING(property_not_found_error_data,"Property not found");
CONSTANT_STRING(property_not_array_type_error_data,"Property not array type");
CONSTANT_STRING(property_element_index_out_of_bounds_error_data,"property_element_index out of bounds");
CONSTANT_STRING(cannot_set_element_in_string_property_with_subset_error_data,"Cannot set element in string property with subset.");
CONSTANT_STRING(incorrect_parameter_number_error_data,"Incorrect number of parameters. ")
CONSTANT_STRING(invalid_json_object_error_data," is not a valid JSON object.")
CONSTANT_STRING(invalid_json_array_error_data," is not a valid JSON array.")
CONSTANT_STRING(parameter_error_error_data,"Parameter value not valid. ");
CONSTANT_STRING(array_parameter_error_error_data,"Array parameter element value not valid. ");
CONSTANT_STRING(array_parameter_length_error_error_data,"Array parameter length not valid. ");
CONSTANT_STRING(value_not_in_subset_error_data,"Value not in subset: ");
CONSTANT_STRING(value_not_in_range_error_data,"Value not in range: ");
CONSTANT_STRING(property_function_not_found_error_data,"Property function not found");
CONSTANT_STRING(incorrect_property_parameter_number_error_data,"Incorrect number of property parameters. ")
CONSTANT_STRING(callback_function_not_found_error_data,"Callback function not found");
CONSTANT_STRING(incorrect_callback_parameter_number_error_data,"Incorrect number of callback parameters. ")

const int parse_error_code = -32700;
const int invalid_request_error_code = -32600;
const int method_not_found_error_code = -32601;
const int invalid_params_error_code = -32602;
const int internal_error_error_code = -32603;
const int server_error_error_code = -32000;

// Saved Variables
const size_t eeprom_initialized_default_value = 123;

// Constant Strings
CONSTANT_STRING(empty_constant_string,"");
CONSTANT_STRING(id_constant_string,"id");
CONSTANT_STRING(error_constant_string,"error");
CONSTANT_STRING(message_constant_string,"message");
CONSTANT_STRING(data_constant_string,"data");
CONSTANT_STRING(code_constant_string,"code");
CONSTANT_STRING(form_factor_constant_string,"form_factor");
CONSTANT_STRING(serial_number_constant_string,"serial_number");
CONSTANT_STRING(firmware_constant_string,"firmware");
CONSTANT_STRING(hardware_constant_string,"hardware");
CONSTANT_STRING(name_constant_string,"name");
CONSTANT_STRING(type_constant_string,"type");
CONSTANT_STRING(units_constant_string,"units");
CONSTANT_STRING(result_constant_string,"result");
CONSTANT_STRING(result_info_constant_string,"result_info");
CONSTANT_STRING(array_element_type_constant_string,"array_element_type");
CONSTANT_STRING(properties_constant_string,"properties");
CONSTANT_STRING(parameters_constant_string,"parameters");
CONSTANT_STRING(functions_constant_string,"functions");
CONSTANT_STRING(callbacks_constant_string,"callbacks");
CONSTANT_STRING(callback_constant_string,"callback");
CONSTANT_STRING(min_constant_string,"min");
CONSTANT_STRING(max_constant_string,"max");
CONSTANT_STRING(array_element_min_constant_string,"array_element_min");
CONSTANT_STRING(array_element_max_constant_string,"array_element_max");
CONSTANT_STRING(array_length_min_constant_string,"array_length_min");
CONSTANT_STRING(array_length_max_constant_string,"array_length_max");
CONSTANT_STRING(string_length_max_constant_string,"string_length_max");
CONSTANT_STRING(version_constant_string,"version");
CONSTANT_STRING(part_number_constant_string,"part_number");
CONSTANT_STRING(device_id_constant_string,"device_id");
CONSTANT_STRING(device_info_constant_string,"device_info");
CONSTANT_STRING(api_constant_string,"api");
CONSTANT_STRING(verbosity_constant_string,"verbosity");
CONSTANT_STRING(value_constant_string,"value");
CONSTANT_STRING(default_value_constant_string,"default_value");
CONSTANT_STRING(question_constant_string,"?");
CONSTANT_STRING(question_double_constant_string,"??");
CONSTANT_STRING(zero_constant_string,"0");
CONSTANT_STRING(given_constant_string," given. ");
CONSTANT_STRING(needed_constant_string," needed.");
CONSTANT_STRING(less_than_equal_constant_string," <= ");
CONSTANT_STRING(element_constant_string," element");
CONSTANT_STRING(array_length_constant_string,"array_length");
CONSTANT_STRING(array_length_default_constant_string,"array_length_default");
CONSTANT_STRING(array_length_spaces_constant_string," array length");
CONSTANT_STRING(string_length_constant_string,"string_length");
CONSTANT_STRING(array_open_constant_string,"[");
CONSTANT_STRING(array_close_constant_string,"]");
CONSTANT_STRING(array_separator_constant_string,",");
CONSTANT_STRING(version_property_separator_constant_string,".");
CONSTANT_STRING(subset_constant_string,"subset");
CONSTANT_STRING(all_constant_string,"ALL");
CONSTANT_STRING(array_element_subset_constant_string,"array_element_subset");
CONSTANT_STRING(pins_constant_string,"pins");
CONSTANT_STRING(interrupt_number_constant_string,"interrupt_number");
CONSTANT_STRING(pin_number_constant_string,"pin_number");
CONSTANT_STRING(pin_mode_constant_string,"pin_mode");
CONSTANT_STRING(processor_constant_string,"processor");

#if defined(__AVR_ATmega1280__)
CONSTANT_STRING(processor_name_constant_string,"ATmega1280");
#elif defined(__AVR_ATmega2560__)
CONSTANT_STRING(processor_name_constant_string,"ATmega2560");
#elif defined(__MK20DX128__)
CONSTANT_STRING(processor_name_constant_string,"MK20DX128");
#elif defined(__MK20DX256__)
CONSTANT_STRING(processor_name_constant_string,"MK20DX256");
#elif defined(__MK64FX512__)
CONSTANT_STRING(processor_name_constant_string,"MK64FX512");
#elif defined(__MK66FX1M0__)
CONSTANT_STRING(processor_name_constant_string,"MK66FX1M0");
#elif defined(__IMXRT1062__)
CONSTANT_STRING(processor_name_constant_string,"IMXRT1062");
#else
CONSTANT_STRING(processor_name_constant_string,"");
#endif

ConstantString * all_c_style_array[ALL_ARRAY_SIZE] =
{
  &all_constant_string,
};
Array<ConstantString *,ALL_ARRAY_SIZE> all_array(all_c_style_array);

}
}
<|endoftext|>


<commit_before>// SwiftShader Software Renderer
//
// Copyright(c) 2005-2013 TransGaming Inc.
//
// All rights reserved. No part of this software may be copied, distributed, transmitted,
// transcribed, stored in a retrieval system, translated into any human or computer
// language by any means, or disclosed to third parties without the explicit written
// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
// or implied, including but not limited to any patent rights, are granted to you.
//

// Buffer.cpp: Implements the Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.

#include "Buffer.h"

#include "main.h"
#include "VertexDataManager.h"
#include "IndexDataManager.h"

namespace es2
{

Buffer::Buffer(GLuint name) : NamedObject(name)
{
    mContents = 0;
    mSize = 0;
    mUsage = GL_DYNAMIC_DRAW;
	mIsMapped = false;
	mOffset = 0;
	mLength = 0;
	mAccess = 0;
}

Buffer::~Buffer()
{
    if(mContents)
	{
		mContents->destruct();
	}
}

void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
	if(mContents)
	{
		mContents->destruct();
		mContents = 0;
	}

	mSize = size;
	mUsage = usage;

	if(size > 0)
	{
		const int padding = 1024;   // For SIMD processing of vertices
		mContents = new sw::Resource(size + padding);

		if(!mContents)
		{
			return error(GL_OUT_OF_MEMORY);
		}

		if(data)
		{
			char *buffer = (char*)mContents->data();
			memcpy(buffer + mOffset, data, size);
		}
	}
}

void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
	if(mContents && data)
	{
		char *buffer = (char*)mContents->lock(sw::PUBLIC);
		memcpy(buffer + offset, data, size);
		mContents->unlock();
	}
}

void* Buffer::mapRange(GLintptr offset, GLsizeiptr length, GLbitfield access)
{
	if(mContents)
	{
		char* buffer = (char*)mContents->lock(sw::PUBLIC);
		mIsMapped = true;
		mOffset = offset;
		mLength = length;
		mAccess = access;
		return buffer + offset;
	}
	return nullptr;
}

bool Buffer::unmap()
{
	if(mContents)
	{
		mContents->unlock();
	}
	mIsMapped = false;
	mOffset = 0;
	mLength = 0;
	mAccess = 0;
	return true;
}

sw::Resource *Buffer::getResource()
{
	return mContents;
}

}
<commit_msg>Changed default buffer usage type<commit_after>// SwiftShader Software Renderer
//
// Copyright(c) 2005-2013 TransGaming Inc.
//
// All rights reserved. No part of this software may be copied, distributed, transmitted,
// transcribed, stored in a retrieval system, translated into any human or computer
// language by any means, or disclosed to third parties without the explicit written
// agreement of TransGaming Inc. Without such an agreement, no rights or licenses, express
// or implied, including but not limited to any patent rights, are granted to you.
//

// Buffer.cpp: Implements the Buffer class, representing storage of vertex and/or
// index data. Implements GL buffer objects and related functionality.
// [OpenGL ES 2.0.24] section 2.9 page 21.

#include "Buffer.h"

#include "main.h"
#include "VertexDataManager.h"
#include "IndexDataManager.h"

namespace es2
{

Buffer::Buffer(GLuint name) : NamedObject(name)
{
    mContents = 0;
    mSize = 0;
    mUsage = GL_STATIC_DRAW;
	mIsMapped = false;
	mOffset = 0;
	mLength = 0;
	mAccess = 0;
}

Buffer::~Buffer()
{
    if(mContents)
	{
		mContents->destruct();
	}
}

void Buffer::bufferData(const void *data, GLsizeiptr size, GLenum usage)
{
	if(mContents)
	{
		mContents->destruct();
		mContents = 0;
	}

	mSize = size;
	mUsage = usage;

	if(size > 0)
	{
		const int padding = 1024;   // For SIMD processing of vertices
		mContents = new sw::Resource(size + padding);

		if(!mContents)
		{
			return error(GL_OUT_OF_MEMORY);
		}

		if(data)
		{
			char *buffer = (char*)mContents->data();
			memcpy(buffer + mOffset, data, size);
		}
	}
}

void Buffer::bufferSubData(const void *data, GLsizeiptr size, GLintptr offset)
{
	if(mContents && data)
	{
		char *buffer = (char*)mContents->lock(sw::PUBLIC);
		memcpy(buffer + offset, data, size);
		mContents->unlock();
	}
}

void* Buffer::mapRange(GLintptr offset, GLsizeiptr length, GLbitfield access)
{
	if(mContents)
	{
		char* buffer = (char*)mContents->lock(sw::PUBLIC);
		mIsMapped = true;
		mOffset = offset;
		mLength = length;
		mAccess = access;
		return buffer + offset;
	}
	return nullptr;
}

bool Buffer::unmap()
{
	if(mContents)
	{
		mContents->unlock();
	}
	mIsMapped = false;
	mOffset = 0;
	mLength = 0;
	mAccess = 0;
	return true;
}

sw::Resource *Buffer::getResource()
{
	return mContents;
}

}
<|endoftext|>


<commit_before>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "TimeGraphLayout.h"

#include <imgui.h>

#include "OrbitBase/ThreadConstants.h"

TimeGraphLayout::TimeGraphLayout() {
  text_box_height_ = 20.f;
  core_height_ = 10.f;
  thread_state_track_height_ = 4.0f;
  event_track_height_ = 10.f;
  all_threads_event_track_scale_ = 2.f;
  variable_track_height_ = 20.f;
  track_content_bottom_margin_ = 5.f;
  track_content_top_margin_ = 5.f;
  space_between_cores_ = 2.f;
  space_between_gpu_depths_ = 2.f;
  space_between_tracks_ = 10.f;
  space_between_tracks_and_thread_ = 5.f;
  space_between_subtracks_ = -5.f;
  space_between_thread_blocks_ = 35.f;
  track_label_offset_x_ = 30.f;
  slider_width_ = 15.f;
  track_tab_width_ = 350.f;
  track_tab_height_ = 25.f;
  track_tab_offset_ = 0.f;
  track_intent_offset_ = 5.f;
  collapse_button_offset_ = 15.f;
  collapse_button_size_ = 10.f;
  collapse_button_decrease_per_indentation_ = 2.f;
  rounding_radius_ = 8.f;
  rounding_num_sides_ = 16;
  text_offset_ = 5.f;
  right_margin_ = 10.f;
  scheduler_track_offset_ = 10.f;
  toolbar_icon_height_ = 24.f;
  generic_fixed_spacer_width_ = 10.f;
  scale_ = 1.f;
  time_bar_height_ = 15.f;
  font_size_ = 14;
};

#define FLOAT_SLIDER(x) FLOAT_SLIDER_MIN_MAX(x, 0, 100.f)
#define FLOAT_SLIDER_MIN_MAX(x, min, max)     \
  if (ImGui::SliderFloat(#x, &x, min, max)) { \
    needs_redraw = true;                      \
  }

bool TimeGraphLayout::DrawProperties() {
  bool needs_redraw = false;
  FLOAT_SLIDER(track_label_offset_x_);
  FLOAT_SLIDER(text_box_height_);
  FLOAT_SLIDER(core_height_);
  FLOAT_SLIDER(thread_state_track_height_);
  FLOAT_SLIDER(event_track_height_);
  FLOAT_SLIDER_MIN_MAX(all_threads_event_track_scale_, 0, 10.f);
  FLOAT_SLIDER(variable_track_height_);
  FLOAT_SLIDER(space_between_cores_);
  FLOAT_SLIDER(space_between_gpu_depths_);
  FLOAT_SLIDER(space_between_tracks_);
  FLOAT_SLIDER(space_between_tracks_and_thread_);
  FLOAT_SLIDER(space_between_subtracks_);
  FLOAT_SLIDER(space_between_thread_blocks_);
  FLOAT_SLIDER(slider_width_);
  FLOAT_SLIDER(time_bar_height_);
  FLOAT_SLIDER(track_tab_height_);
  FLOAT_SLIDER(track_tab_offset_);
  FLOAT_SLIDER(track_intent_offset_);
  FLOAT_SLIDER(collapse_button_size_);
  FLOAT_SLIDER(collapse_button_decrease_per_indentation_);

  FLOAT_SLIDER(collapse_button_offset_);
  FLOAT_SLIDER(rounding_radius_);
  FLOAT_SLIDER(rounding_num_sides_);
  FLOAT_SLIDER(text_offset_);
  FLOAT_SLIDER(right_margin_);
  FLOAT_SLIDER(scheduler_track_offset_);
  FLOAT_SLIDER_MIN_MAX(track_tab_width_, 0, 1000.f);
  FLOAT_SLIDER_MIN_MAX(track_content_bottom_margin_, 0, 20.f);
  FLOAT_SLIDER_MIN_MAX(track_content_top_margin_, 0, 20.f);
  FLOAT_SLIDER(toolbar_icon_height_);
  FLOAT_SLIDER(generic_fixed_spacer_width_);
  FLOAT_SLIDER_MIN_MAX(scale_, kMinScale, kMaxScale);
  ImGui::Checkbox("Draw Track Background", &draw_track_background_);

  return needs_redraw;
}

float TimeGraphLayout::GetCollapseButtonSize(int indentation_level) const {
  float button_size_without_scaling =
      collapse_button_size_ -
      collapse_button_decrease_per_indentation_ * static_cast<float>(indentation_level);

  // We want the button to scale slower than other elements, so we use sqrt() function.
  return button_size_without_scaling * sqrt(scale_);
}

float TimeGraphLayout::GetBottomMargin() const {
  // The bottom consists of the slider (where we have to take the width, as it
  // is rotated), and the time bar.
  return GetSliderWidth() + GetTimeBarHeight();
}

float TimeGraphLayout::GetEventTrackHeightFromTid(uint32_t tid) const {
  float height = GetEventTrackHeight();
  if (tid == orbit_base::kAllProcessThreadsTid) {
    height *= GetAllThreadsEventTrackScale();
  }
  return height;
}
<commit_msg>Change the space between subtracks<commit_after>// Copyright (c) 2020 The Orbit Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "TimeGraphLayout.h"

#include <imgui.h>

#include "OrbitBase/ThreadConstants.h"

TimeGraphLayout::TimeGraphLayout() {
  text_box_height_ = 20.f;
  core_height_ = 10.f;
  thread_state_track_height_ = 4.0f;
  event_track_height_ = 10.f;
  all_threads_event_track_scale_ = 2.f;
  variable_track_height_ = 20.f;
  track_content_bottom_margin_ = 5.f;
  track_content_top_margin_ = 5.f;
  space_between_cores_ = 2.f;
  space_between_gpu_depths_ = 2.f;
  space_between_tracks_ = 10.f;
  space_between_tracks_and_thread_ = 5.f;
  space_between_subtracks_ = 0.f;
  space_between_thread_blocks_ = 35.f;
  track_label_offset_x_ = 30.f;
  slider_width_ = 15.f;
  track_tab_width_ = 350.f;
  track_tab_height_ = 25.f;
  track_tab_offset_ = 0.f;
  track_intent_offset_ = 5.f;
  collapse_button_offset_ = 15.f;
  collapse_button_size_ = 10.f;
  collapse_button_decrease_per_indentation_ = 2.f;
  rounding_radius_ = 8.f;
  rounding_num_sides_ = 16;
  text_offset_ = 5.f;
  right_margin_ = 10.f;
  scheduler_track_offset_ = 10.f;
  toolbar_icon_height_ = 24.f;
  generic_fixed_spacer_width_ = 10.f;
  scale_ = 1.f;
  time_bar_height_ = 15.f;
  font_size_ = 14;
};

#define FLOAT_SLIDER(x) FLOAT_SLIDER_MIN_MAX(x, 0, 100.f)
#define FLOAT_SLIDER_MIN_MAX(x, min, max)     \
  if (ImGui::SliderFloat(#x, &x, min, max)) { \
    needs_redraw = true;                      \
  }

bool TimeGraphLayout::DrawProperties() {
  bool needs_redraw = false;
  FLOAT_SLIDER(track_label_offset_x_);
  FLOAT_SLIDER(text_box_height_);
  FLOAT_SLIDER(core_height_);
  FLOAT_SLIDER(thread_state_track_height_);
  FLOAT_SLIDER(event_track_height_);
  FLOAT_SLIDER_MIN_MAX(all_threads_event_track_scale_, 0, 10.f);
  FLOAT_SLIDER(variable_track_height_);
  FLOAT_SLIDER(space_between_cores_);
  FLOAT_SLIDER(space_between_gpu_depths_);
  FLOAT_SLIDER(space_between_tracks_);
  FLOAT_SLIDER(space_between_tracks_and_thread_);
  FLOAT_SLIDER(space_between_subtracks_);
  FLOAT_SLIDER(space_between_thread_blocks_);
  FLOAT_SLIDER(slider_width_);
  FLOAT_SLIDER(time_bar_height_);
  FLOAT_SLIDER(track_tab_height_);
  FLOAT_SLIDER(track_tab_offset_);
  FLOAT_SLIDER(track_intent_offset_);
  FLOAT_SLIDER(collapse_button_size_);
  FLOAT_SLIDER(collapse_button_decrease_per_indentation_);

  FLOAT_SLIDER(collapse_button_offset_);
  FLOAT_SLIDER(rounding_radius_);
  FLOAT_SLIDER(rounding_num_sides_);
  FLOAT_SLIDER(text_offset_);
  FLOAT_SLIDER(right_margin_);
  FLOAT_SLIDER(scheduler_track_offset_);
  FLOAT_SLIDER_MIN_MAX(track_tab_width_, 0, 1000.f);
  FLOAT_SLIDER_MIN_MAX(track_content_bottom_margin_, 0, 20.f);
  FLOAT_SLIDER_MIN_MAX(track_content_top_margin_, 0, 20.f);
  FLOAT_SLIDER(toolbar_icon_height_);
  FLOAT_SLIDER(generic_fixed_spacer_width_);
  FLOAT_SLIDER_MIN_MAX(scale_, kMinScale, kMaxScale);
  ImGui::Checkbox("Draw Track Background", &draw_track_background_);

  return needs_redraw;
}

float TimeGraphLayout::GetCollapseButtonSize(int indentation_level) const {
  float button_size_without_scaling =
      collapse_button_size_ -
      collapse_button_decrease_per_indentation_ * static_cast<float>(indentation_level);

  // We want the button to scale slower than other elements, so we use sqrt() function.
  return button_size_without_scaling * sqrt(scale_);
}

float TimeGraphLayout::GetBottomMargin() const {
  // The bottom consists of the slider (where we have to take the width, as it
  // is rotated), and the time bar.
  return GetSliderWidth() + GetTimeBarHeight();
}

float TimeGraphLayout::GetEventTrackHeightFromTid(uint32_t tid) const {
  float height = GetEventTrackHeight();
  if (tid == orbit_base::kAllProcessThreadsTid) {
    height *= GetAllThreadsEventTrackScale();
  }
  return height;
}
<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2015 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  platform/application/base.hpp                                                   */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)

#define UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP

// includes, system

#include <boost/noncopyable.hpp> // boost::noncopyable
#include <memory>                // std::unique_ptr<>

// includes, project

#include <platform/application/command_line.hpp>
#include <platform/export.h>
#include <support/printable.hpp>

namespace platform {

  namespace application {

    // types, exported (class, enum, struct, union, typedef)

    class DCS08961_PLATFORM_EXPORT base : private boost::noncopyable,
                                          public support::printable {

    public:

      virtual signed run() =0;
      virtual void   process_command_line();

      virtual void print_on(std::ostream&) const;

    protected:

      command_line command_line_;
      unsigned     verbose_level_;

      explicit base(command_line const&);
      virtual ~base() =0;

    };

    template <typename T>
    class executor : private boost::noncopyable {

    public:

      explicit executor(command_line const&);
              ~executor();

      signed run();

    private:

      std::unique_ptr<T> instance_;

    };

    // variables, exported (extern)

    // functions, inlined (inline)

    // functions, exported (extern)

    template <typename T> signed execute(command_line const&);
    template <typename T> signed execute(command_line const&, std::nothrow_t const&) noexcept;

  } // namespace application {

} // namespace platform {

#include <platform/application/base.inl>

#endif // #if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)
<commit_msg>update: MSVC 18.0<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2015 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  platform/application/base.hpp                                                   */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)

#define UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP

// includes, system

#include <boost/noncopyable.hpp> // boost::noncopyable
#include <memory>                // std::unique_ptr<>

// includes, project

#include <platform/application/command_line.hpp>
#include <platform/export.h>
#include <support/printable.hpp>

#if defined(_MSC_VER) && (_MSC_VER < 1900)
#  define noexcept
#endif

namespace platform {

  namespace application {

    // types, exported (class, enum, struct, union, typedef)

    class DCS08961_PLATFORM_EXPORT base : private boost::noncopyable,
                                          public support::printable {

    public:

      virtual signed run() =0;
      virtual void   process_command_line();

      virtual void print_on(std::ostream&) const;

    protected:

      command_line command_line_;
      unsigned     verbose_level_;

      explicit base(command_line const&);
      virtual ~base() =0;

    };

    template <typename T>
    class executor : private boost::noncopyable {

    public:

      explicit executor(command_line const&);
              ~executor();

      signed run();

    private:

      std::unique_ptr<T> instance_;

    };

    // variables, exported (extern)

    // functions, inlined (inline)

    // functions, exported (extern)

    template <typename T> signed execute(command_line const&);
    template <typename T> signed execute(command_line const&, std::nothrow_t const&) noexcept;

  } // namespace application {

} // namespace platform {

#include <platform/application/base.inl>

#endif // #if !defined(UKACHULLDCS_08961_PLATFORM_APPLICATION_BASE_HPP)
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009, 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef OPTION_PARSER_HXX
# define OPTION_PARSER_HXX

# include <libport/lexical-cast.hh>

namespace libport
{
  template <typename T>
  inline
  T OptionValue::get(const boost::optional<T>& def) const
  {
    if (!filled_)
    {
      aver(def);
      return def.get();
    }
    return boost::lexical_cast<T>(value_);
  }

  template <typename T>
  inline
  T OptionValue::get() const
  {
    return get(boost::optional<T>());
  }

  inline
  std::ostream&
  operator<<(std::ostream& o, const OptionParser& p)
  {
    p.options_doc(o);
    return o;
  }

}

#endif
<commit_msg>build: fix.<commit_after>/*
 * Copyright (C) 2009, 2010, Gostai S.A.S.
 *
 * This software is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the
 * implied warranties of fitness for a particular purpose.
 *
 * See the LICENSE file for more information.
 */

#ifndef OPTION_PARSER_HXX
# define OPTION_PARSER_HXX

# include <libport/cassert>
# include <libport/lexical-cast.hh>

namespace libport
{
  template <typename T>
  inline
  T OptionValue::get(const boost::optional<T>& def) const
  {
    if (!filled_)
    {
      aver(def);
      return def.get();
    }
    return boost::lexical_cast<T>(value_);
  }

  template <typename T>
  inline
  T OptionValue::get() const
  {
    return get(boost::optional<T>());
  }

  inline
  std::ostream&
  operator<<(std::ostream& o, const OptionParser& p)
  {
    p.options_doc(o);
    return o;
  }

}

#endif
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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 OWNER 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.

*/

#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/deadline_timer.hpp"

#include <deque>
#include <boost/function/function4.hpp>

namespace libtorrent
{
	class connection_queue;

	class udp_socket
	{
	public:
		// TODO: instead of these callbacks, support observers
		typedef boost::function<void(error_code const& ec
			, udp::endpoint const&, char const* buf, int size)> callback_t;
		typedef boost::function<void(error_code const& ec
			, char const*, char const* buf, int size)> callback2_t;
		typedef boost::function<void()> drain_callback_t;

		udp_socket(io_service& ios, callback_t const& c, callback2_t const& c2
			, drain_callback_t const& dc, connection_queue& cc);
		~udp_socket();

		enum flags_t { dont_drop = 1, peer_connection = 2 };

		bool is_open() const
		{
			return m_ipv4_sock.is_open()
#if TORRENT_USE_IPV6
				|| m_ipv6_sock.is_open()
#endif
				;
		}
		io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }

		// this is only valid when using a socks5 proxy
		void send_hostname(char const* hostname, int port, char const* p, int len, error_code& ec);

		void send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
		void bind(udp::endpoint const& ep, error_code& ec);
		void bind(int port);
		void close();
		int local_port() const { return m_bind_port; }

		void set_proxy_settings(proxy_settings const& ps);
		proxy_settings const& get_proxy_settings() { return m_proxy_settings; }

		bool is_closed() const { return m_abort; }
		tcp::endpoint local_endpoint(error_code& ec) const
		{
			udp::endpoint ep = m_ipv4_sock.local_endpoint(ec);
			return tcp::endpoint(ep.address(), ep.port());
		}

		void set_buf_size(int s);

		template <class SocketOption>
		void set_option(SocketOption const& opt, error_code& ec)
		{
			m_ipv4_sock.set_option(opt, ec);
#if TORRENT_USE_IPV6
			m_ipv6_sock.set_option(opt, ec);
#endif
		}

		template <class SocketOption>
		void get_option(SocketOption& opt, error_code& ec)
		{
			m_ipv4_sock.get_option(opt, ec);
		}

		udp::endpoint proxy_addr() const { return m_proxy_addr; }

	protected:

		struct queued_packet
		{
			udp::endpoint ep;
			char* hostname;
			buffer buf;
			int flags;
		};

		// number of outstanding UDP socket operations
		// using the UDP socket buffer
		int num_outstanding() const
		{
			return m_v4_outstanding
#if TORRENT_USE_IPV6
			  	+ m_v6_outstanding
#endif
				;
		}

	private:
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
	// necessary for logging member offsets
	public:
#endif

		// callback for regular incoming packets
		callback_t m_callback;

		// callback for proxied incoming packets with a domain
		// name as source
		callback2_t m_callback2;

		// called every time we drain the udp sockets
		drain_callback_t m_drained_callback;

		void setup_read(udp::socket* s);
		void on_read(udp::socket* s);
		void on_read_impl(udp::socket* sock, udp::endpoint const& ep
			, error_code const& e, std::size_t bytes_transferred);
		void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
		void on_timeout();
		void on_connect(int ticket);
		void on_connected(error_code const& ec);
		void handshake1(error_code const& e);
		void handshake2(error_code const& e);
		void handshake3(error_code const& e);
		void handshake4(error_code const& e);
		void socks_forward_udp();
		void connect1(error_code const& e);
		void connect2(error_code const& e);
		void hung_up(error_code const& e);

		void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
		void wrap(char const* hostname, int port, char const* p, int len, error_code& ec);
		void unwrap(error_code const& e, char const* buf, int size);

		bool maybe_clear_callback();

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
#if defined BOOST_HAS_PTHREADS
		mutable pthread_t m_thread;
#endif
		bool is_single_thread() const
		{
#if defined BOOST_HAS_PTHREADS
			if (m_thread == 0)
				m_thread = pthread_self();
			return m_thread == pthread_self();
#endif
			return true;
		}
#endif

		udp::socket m_ipv4_sock;
		int m_buf_size;
		char* m_buf;

#if TORRENT_USE_IPV6
		udp::socket m_ipv6_sock;
#endif

		boost::uint16_t m_bind_port;
		boost::uint8_t m_v4_outstanding;
#if TORRENT_USE_IPV6
		boost::uint8_t m_v6_outstanding;
#endif

		tcp::socket m_socks5_sock;
		int m_connection_ticket;
		proxy_settings m_proxy_settings;
		connection_queue& m_cc;
		tcp::resolver m_resolver;
		char m_tmp_buf[270];
		bool m_queue_packets;
		bool m_tunnel_packets;
		bool m_abort;
		udp::endpoint m_proxy_addr;
		// while we're connecting to the proxy
		// we have to queue the packets, we'll flush
		// them once we're connected
		std::deque<queued_packet> m_queue;

		// counts the number of outstanding async
		// operations hanging on this socket
		int m_outstanding_ops;

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
		bool m_started;
		int m_magic;
		int m_outstanding_when_aborted;
#endif
	};

	struct rate_limited_udp_socket : public udp_socket
	{
		rate_limited_udp_socket(io_service& ios, callback_t const& c
			, callback2_t const& c2, drain_callback_t const& dc, connection_queue& cc);
		void set_rate_limit(int limit) { m_rate_limit = limit; }
		bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }
		bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
		void close();

	private:
		void on_tick(error_code const& e);

		deadline_timer m_timer;
		int m_queue_size_limit;
		int m_rate_limit;
		int m_quota;
		ptime m_last_tick;
		std::deque<queued_packet> m_queue;
	};
}

#endif

<commit_msg>fix build issue<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

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.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

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 OWNER 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.

*/

#ifndef TORRENT_UDP_SOCKET_HPP_INCLUDED
#define TORRENT_UDP_SOCKET_HPP_INCLUDED

#include "libtorrent/socket.hpp"
#include "libtorrent/io_service.hpp"
#include "libtorrent/error_code.hpp"
#include "libtorrent/session_settings.hpp"
#include "libtorrent/buffer.hpp"
#include "libtorrent/thread.hpp"
#include "libtorrent/deadline_timer.hpp"

#include <deque>
#include <boost/function/function4.hpp>
#include <boost/function/function0.hpp>

namespace libtorrent
{
	class connection_queue;

	class udp_socket
	{
	public:
		// TODO: instead of these callbacks, support observers
		typedef boost::function<void(error_code const& ec
			, udp::endpoint const&, char const* buf, int size)> callback_t;
		typedef boost::function<void(error_code const& ec
			, char const*, char const* buf, int size)> callback2_t;
		typedef boost::function<void()> drain_callback_t;

		udp_socket(io_service& ios, callback_t const& c, callback2_t const& c2
			, drain_callback_t const& dc, connection_queue& cc);
		~udp_socket();

		enum flags_t { dont_drop = 1, peer_connection = 2 };

		bool is_open() const
		{
			return m_ipv4_sock.is_open()
#if TORRENT_USE_IPV6
				|| m_ipv6_sock.is_open()
#endif
				;
		}
		io_service& get_io_service() { return m_ipv4_sock.get_io_service(); }

		// this is only valid when using a socks5 proxy
		void send_hostname(char const* hostname, int port, char const* p, int len, error_code& ec);

		void send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
		void bind(udp::endpoint const& ep, error_code& ec);
		void bind(int port);
		void close();
		int local_port() const { return m_bind_port; }

		void set_proxy_settings(proxy_settings const& ps);
		proxy_settings const& get_proxy_settings() { return m_proxy_settings; }

		bool is_closed() const { return m_abort; }
		tcp::endpoint local_endpoint(error_code& ec) const
		{
			udp::endpoint ep = m_ipv4_sock.local_endpoint(ec);
			return tcp::endpoint(ep.address(), ep.port());
		}

		void set_buf_size(int s);

		template <class SocketOption>
		void set_option(SocketOption const& opt, error_code& ec)
		{
			m_ipv4_sock.set_option(opt, ec);
#if TORRENT_USE_IPV6
			m_ipv6_sock.set_option(opt, ec);
#endif
		}

		template <class SocketOption>
		void get_option(SocketOption& opt, error_code& ec)
		{
			m_ipv4_sock.get_option(opt, ec);
		}

		udp::endpoint proxy_addr() const { return m_proxy_addr; }

	protected:

		struct queued_packet
		{
			udp::endpoint ep;
			char* hostname;
			buffer buf;
			int flags;
		};

		// number of outstanding UDP socket operations
		// using the UDP socket buffer
		int num_outstanding() const
		{
			return m_v4_outstanding
#if TORRENT_USE_IPV6
			  	+ m_v6_outstanding
#endif
				;
		}

	private:
#if defined TORRENT_VERBOSE_LOGGING || defined TORRENT_LOGGING || defined TORRENT_ERROR_LOGGING
	// necessary for logging member offsets
	public:
#endif

		// callback for regular incoming packets
		callback_t m_callback;

		// callback for proxied incoming packets with a domain
		// name as source
		callback2_t m_callback2;

		// called every time we drain the udp sockets
		drain_callback_t m_drained_callback;

		void setup_read(udp::socket* s);
		void on_read(udp::socket* s);
		void on_read_impl(udp::socket* sock, udp::endpoint const& ep
			, error_code const& e, std::size_t bytes_transferred);
		void on_name_lookup(error_code const& e, tcp::resolver::iterator i);
		void on_timeout();
		void on_connect(int ticket);
		void on_connected(error_code const& ec);
		void handshake1(error_code const& e);
		void handshake2(error_code const& e);
		void handshake3(error_code const& e);
		void handshake4(error_code const& e);
		void socks_forward_udp();
		void connect1(error_code const& e);
		void connect2(error_code const& e);
		void hung_up(error_code const& e);

		void wrap(udp::endpoint const& ep, char const* p, int len, error_code& ec);
		void wrap(char const* hostname, int port, char const* p, int len, error_code& ec);
		void unwrap(error_code const& e, char const* buf, int size);

		bool maybe_clear_callback();

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
#if defined BOOST_HAS_PTHREADS
		mutable pthread_t m_thread;
#endif
		bool is_single_thread() const
		{
#if defined BOOST_HAS_PTHREADS
			if (m_thread == 0)
				m_thread = pthread_self();
			return m_thread == pthread_self();
#endif
			return true;
		}
#endif

		udp::socket m_ipv4_sock;
		int m_buf_size;
		char* m_buf;

#if TORRENT_USE_IPV6
		udp::socket m_ipv6_sock;
#endif

		boost::uint16_t m_bind_port;
		boost::uint8_t m_v4_outstanding;
#if TORRENT_USE_IPV6
		boost::uint8_t m_v6_outstanding;
#endif

		tcp::socket m_socks5_sock;
		int m_connection_ticket;
		proxy_settings m_proxy_settings;
		connection_queue& m_cc;
		tcp::resolver m_resolver;
		char m_tmp_buf[270];
		bool m_queue_packets;
		bool m_tunnel_packets;
		bool m_abort;
		udp::endpoint m_proxy_addr;
		// while we're connecting to the proxy
		// we have to queue the packets, we'll flush
		// them once we're connected
		std::deque<queued_packet> m_queue;

		// counts the number of outstanding async
		// operations hanging on this socket
		int m_outstanding_ops;

#if defined TORRENT_DEBUG || TORRENT_RELEASE_ASSERTS
		bool m_started;
		int m_magic;
		int m_outstanding_when_aborted;
#endif
	};

	struct rate_limited_udp_socket : public udp_socket
	{
		rate_limited_udp_socket(io_service& ios, callback_t const& c
			, callback2_t const& c2, drain_callback_t const& dc, connection_queue& cc);
		void set_rate_limit(int limit) { m_rate_limit = limit; }
		bool can_send() const { return int(m_queue.size()) >= m_queue_size_limit; }
		bool send(udp::endpoint const& ep, char const* p, int len, error_code& ec, int flags = 0);
		void close();

	private:
		void on_tick(error_code const& e);

		deadline_timer m_timer;
		int m_queue_size_limit;
		int m_rate_limit;
		int m_quota;
		ptime m_last_tick;
		std::deque<queued_packet> m_queue;
	};
}

#endif

<|endoftext|>


<commit_before>#include "sherwood_mex.h"

using namespace MicrosoftResearch::Cambridge::Sherwood;

// F: Feature Response
// S: StatisticsAggregator
template<typename F, typename S>
void sherwood_classify(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[],		/* mxArray input pointer array */
        Options options)
{
	unsigned int curarg = 0;
	const matrix<float> features = prhs[curarg++];

  if (options.Verbose) {
    mexPrintf("Loading tree at: %s\n", options.ForestName.c_str());
  }

	// Point class
	DataPointCollection testData(features);

	// Create the tree.
	std::auto_ptr<Forest<F, S> > forest;

	// Load the tree from file
  std::ifstream istream(options.ForestName.c_str(), std::ios_base::binary);
  forest = forest->Deserialize(istream);

  unsigned int num_classes = forest->GetTree(0).GetNode(0).TrainingDataStatistics.BinCount();

  if (options.Verbose)
  {
    mexPrintf("Number of classes: %d\n", num_classes);
    mexPrintf("Number of test data: %d\n", testData.Count());
  }

  // Output ordered as (class, index)
  matrix<double> output(num_classes,testData.Count());

  for (int i = 0; i < output.numel(); i++) {
    output(i) = 0;
  }

  // Perform classification
  // forest::apply is wasting memory, bypassing it.
  //
  // Note: leafNodeIndices should unsigned int, modify tree.h and the line below.
  //
  std::vector<int> leafNodeIndices;

  // Forest.h (Apply)
  for (unsigned int t = 0; t < forest->TreeCount(); t++)
  {
    Tree<F,S>& tree = forest->GetTree(t);

    // Tree.h
    tree.Apply(testData, leafNodeIndices);

    // Aggregate histograms
    if (options.TreeAggregator == Histogram) {

      for (unsigned int i = 0; i < testData.Count(); i++)
      {
        S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;

        for (unsigned int c = 0; c < num_classes; c++) {
          output(c,i) += aggregator.bins_[c];
        }
      }

    // Aggregate probabilities
    } else if (options.TreeAggregator ==  Probability) {

      int sum = 0;
      for (unsigned int i = 0; i < testData.Count(); i++)
      {
        S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;

        for (unsigned int c = 0; c < num_classes; c++) {
          sum += aggregator.bins_[c];
        }

       for (unsigned int c = 0; c < num_classes; c++) {
          output(c,i) += double(aggregator.bins_[c])/sum;
        }

        sum = 0;
      }

    } else {
      mexErrMsgTxt("Unkown aggregator.");
    }

    leafNodeIndices.clear();
  }

  plhs[0] = output;
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray  *prhs[])
{
  MexParams params(1, prhs+1);
  Options options(params);

  if (!options.WeakLearner.compare("axis-aligned-hyperplane"))
    sherwood_classify<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane"))
    sherwood_classify<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else
    mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane");

}<commit_msg>More code reuse.<commit_after>#include "sherwood_mex.h"

using namespace MicrosoftResearch::Cambridge::Sherwood;

// F: Feature Response
// S: StatisticsAggregator
template<typename F, typename S>
void sherwood_classify(int nlhs, 		    /* number of expected outputs */
        mxArray        *plhs[],	    /* mxArray output pointer array */
        int            nrhs, 		/* number of inputs */
        const mxArray  *prhs[],		/* mxArray input pointer array */
        Options options)
{
	unsigned int curarg = 0;
	const matrix<float> features = prhs[curarg++];

  if (options.Verbose) {
    mexPrintf("Loading tree at: %s\n", options.ForestName.c_str());
  }

	// Point class
	DataPointCollection testData(features);

	// Create the tree.
	std::auto_ptr<Forest<F, S> > forest;

	// Load the tree from file
  std::ifstream istream(options.ForestName.c_str(), std::ios_base::binary);
  forest = forest->Deserialize(istream);

  unsigned int num_classes = forest->GetTree(0).GetNode(0).TrainingDataStatistics.BinCount();

  if (options.Verbose)
  {
    mexPrintf("Number of classes: %d\n", num_classes);
    mexPrintf("Number of test data: %d\n", testData.Count());
  }

  // Output ordered as (class, index)
  matrix<double> output(num_classes,testData.Count());

  for (int i = 0; i < output.numel(); i++) {
    output(i) = 0;
  }

  // Perform classification
  // forest::apply is wasting memory, bypassing it.
  //
  // Note: leafNodeIndices should unsigned int, modify tree.h and the line below.
  //
  std::vector<int> leafNodeIndices;

  // Forest.h (Apply)
  for (unsigned int t = 0; t < forest->TreeCount(); t++)
  {
    Tree<F,S>& tree = forest->GetTree(t);

    // Tree.h
    tree.Apply(testData, leafNodeIndices);

    // Aggregate histograms
    if (options.TreeAggregator == Histogram) {

      for (unsigned int i = 0; i < testData.Count(); i++)
      {
        S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;

        for (unsigned int c = 0; c < num_classes; c++) {
          output(c,i) += aggregator.bins_[c];
        }
      }

    // Aggregate probabilities
    } else if (options.TreeAggregator ==  Probability) {
      for (unsigned int i = 0; i < testData.Count(); i++)
      {
        S aggregator = tree.GetNode(leafNodeIndices[i]).TrainingDataStatistics;

        for (unsigned int c = 0; c < num_classes; c++) {
          output(c,i) += aggregator.GetProbability(c);
        }
      }

    } else {
      mexErrMsgTxt("Unkown aggregator.");
    }

    leafNodeIndices.clear();
  }

  plhs[0] = output;
}

void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray  *prhs[])
{
  MexParams params(1, prhs+1);
  Options options(params);

  if (!options.WeakLearner.compare("axis-aligned-hyperplane"))
    sherwood_classify<AxisAlignedFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else if (!options.WeakLearner.compare("random-hyperplane"))
    sherwood_classify<RandomHyperplaneFeatureResponse, HistogramAggregator>(nlhs, plhs, nrhs, prhs, options);
  else
    mexErrMsgTxt("Unknown weak learner. Supported are: axis-aligned-hyperplane and random-hyperplane");

}<|endoftext|>


<commit_before>#include <cmath>

#include "checker.hpp"

bool Checker::checkStep(GameDesk& a, Points& points) {
    int rownumber = a.getRowNumber();
    int n1 = a.getDeskNumber(points.p1);
    int n2 = a.getDeskNumber(points.p2);
    return checkIndex(rownumber, points) && n1 == n2;
}

bool Checker::checkIndex(int max, Points& points) {
    int p1c = points.p1.col;
    int p2c = points.p2.col;
    int p1r = points.p1.row;
    int p2r = points.p2.row;
    if (checkRange(max, points)) {
        if ((p1c == p2c) && (std::abs((p1r - p2r)) == 1)) {
            return true;
        } else if ((p1r == p2r) && (std::abs(p1c - p2c) == 1)) {
            return true;
        }
        return false;
    }
    return false;
}

bool Checker::checkRange(int max, Points& points) {
    int p1c = points.p1.col;
    int p2c = points.p2.col;
    int p1r = points.p1.row;
    int p2r = points.p2.row;
    bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;
    bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;
    return gt0 && ltm;
}

<commit_msg>Reach compatibility with gcc 4.4<commit_after>#include "checker.hpp"

static int myAbs(int number) {
    if (number >= 0) {
        return number;
    } else {
        return -number;
    }
}

bool Checker::checkStep(GameDesk& a, Points& points) {
    int rownumber = a.getRowNumber();
    int n1 = a.getDeskNumber(points.p1);
    int n2 = a.getDeskNumber(points.p2);
    return checkIndex(rownumber, points) && n1 == n2;
}

bool Checker::checkIndex(int max, Points& points) {
    int p1c = points.p1.col;
    int p2c = points.p2.col;
    int p1r = points.p1.row;
    int p2r = points.p2.row;
    if (checkRange(max, points)) {
        if ((p1c == p2c) && (myAbs((p1r - p2r)) == 1)) {
            return true;
        } else if ((p1r == p2r) && (myAbs(p1c - p2c) == 1)) {
            return true;
        }
        return false;
    }
    return false;
}

bool Checker::checkRange(int max, Points& points) {
    int p1c = points.p1.col;
    int p2c = points.p2.col;
    int p1r = points.p1.row;
    int p2r = points.p2.row;
    bool gt0 = p1r >= 0 && p1c >= 0 && p2r >= 0 && p2c >= 0;
    bool ltm = p1r < max && p1c < max && p2r < max && p2c < max;
    return gt0 && ltm;
}

<|endoftext|>


<commit_before>#ifndef TWISTEDCPP_PROTOCOL_CORE
#define TWISTEDCPP_PROTOCOL_CORE

#include "detail/sockets.hpp"

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/ref.hpp>

#ifndef NDEBUG
#include <iostream>
#endif

namespace twisted {

template <typename ChildProtocol, typename BufferType>
class protocol_core : public std::enable_shared_from_this<ChildProtocol> {
public:
    typedef detail::socket_base socket_type;
    typedef boost::asio::steady_timer timer_type;
    typedef boost::asio::io_service::strand strand_type;
    typedef BufferType buffer_type;
    typedef typename buffer_type::iterator buffer_iterator;
    typedef typename buffer_type::const_iterator const_buffer_iterator;

    protocol_core() = default;
    protocol_core(protocol_core&&) = default;
    protocol_core& operator=(protocol_core&&) = default;

    void set_socket(std::unique_ptr<socket_type> socket) {
        _socket = std::move(socket);
    }

    void run_protocol() {
        auto self = this_protocol().shared_from_this();
        boost::asio::spawn(_socket->get_io_service(),
                           [this, self](boost::asio::yield_context yield) {
            _yield = boost::in_place(yield);

            try {
                _socket->do_handshake(*_yield);

                while (_socket->is_open()) {
                    auto bytes_read =
                        _socket->async_read_some(asio_buffer(), yield);
                    checked_on_message(buffer_begin(),
                                       std::next(buffer_begin(), bytes_read));
                }
            }
            catch (boost::system::system_error& connection_error) {
                handle_network_error(connection_error);
            }

            this_protocol().on_disconnect();
        });
    }

    template <typename Duration, typename Callable>
    void call_later(Duration duration, Callable callable) {
        auto self = this_protocol().shared_from_this();
        // we pass our existing yield_context and not the io_service such that
        // both contexts run under the same strand
        boost::asio::spawn(*_yield, [this, duration, callable, self](
                                        boost::asio::yield_context yield) {
            boost::asio::high_resolution_timer timer(_socket->get_io_service(),
                                                     duration);
            timer.async_wait(yield);

            // we need to exchange the yield context so that that the user can
            // use the send_message function in the right context
            boost::optional<boost::asio::yield_context> old_yield(
                boost::in_place(*_yield));
            _yield = boost::in_place(yield);
            callable();
            _yield = boost::in_place(*old_yield);
        });
    }

    template <typename Callable>
    void call(Callable callable) {
        call_later(std::chrono::seconds(0), std::move(callable));
    }

    template <typename Callable, typename... Args>
    void call_from_thread(Callable&& callable, Args&&... args) {
        _socket->get_io_service().post(std::bind(
            std::forward<Callable>(callable), std::forward<Args>(args)...));
    }

    template <typename Duration>
    void wait_for(const Duration& duration) const {
        boost::asio::high_resolution_timer timer(_socket->get_io_service(),
                                                 duration);
        timer.async_wait(*_yield);
    }

    template <typename Iter>
    void send_message(Iter begin, Iter end) {
        _socket->async_write(
            boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);
    }

    template <typename Iter>
    void forward(const protocol_core& other, Iter begin, Iter end) {
        other._socket->async_write(
            boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);
    }

    void send_buffers(const std::array<boost::asio::const_buffer, 2>& buffers) {
        _socket->async_write(buffers, *_yield);
    }

    /*
     * @brief default on_disconnect implementation; does nothing
     */
    void on_disconnect() {}

    /*
     * @brief default on_error implementation; swallows everything
     */
    void on_error(std::exception_ptr eptr) {
        try {
            std::rethrow_exception(eptr);
        }
        catch (const std::exception& excep) {
            print_exception_what(excep);
        }
    }

    bool is_connected() const { return _socket->is_open(); }

    void lose_connection() { _socket->close(); }

    /*
     * @brief CRTP wrapper for derived class access
     */
    ChildProtocol& this_protocol() {
        return *static_cast<ChildProtocol*>(this);
    }

    /*
     * @brief CRTP wrapper for derived class access
     */
    const ChildProtocol& this_protocol() const {
        return *static_cast<ChildProtocol*>(this);
    }

private:
    void checked_on_message(const_buffer_iterator begin,
                            const_buffer_iterator end) {
        try {
            this_protocol().on_message(begin, end);
        }
        catch (...) {
            this_protocol().on_error(std::current_exception());
        }
    }

#ifdef NDEBUG
    void handle_network_error(boost::system::system_error&) {
#else
    void handle_network_error(boost::system::system_error& connection_error) {
        print_connection_error(connection_error);
#endif
    }

    void handle_user_error(const std::exception_ptr& excep) {
        this_protocol().on_error(excep);
    }

    void print_connection_error(
        const boost::system::system_error& connection_error) const {
        std::cerr << "Client disconnected with code " << connection_error.what()
                  << std::endl;
    }

    void print_exception_what(const std::exception& excep) const {
        std::cerr << "Killing connection, exception in client handler: "
                  << excep.what() << std::endl;
    }

    buffer_iterator buffer_begin() {
        using std::begin;
        return begin(this_protocol().read_buffer());
    }

    buffer_iterator buffer_begin() const {
        using std::begin;
        return begin(this_protocol().read_buffer());
    }

    buffer_iterator buffer_end() {
        using std::end;
        return end(this_protocol().read_buffer());
    }

    buffer_iterator buffer_end() const {
        using std::end;
        return end(this_protocol().read_buffer());
    }

    boost::asio::mutable_buffers_1 asio_buffer() {
        return boost::asio::buffer(&*buffer_begin(),
                                   std::distance(buffer_begin(), buffer_end()));
    }

private:
    boost::optional<boost::asio::yield_context> _yield;
    std::unique_ptr<socket_type> _socket;
};

} // namespace twisted

#endif
<commit_msg>any ConstBufferSequence can now be passed to send_buffers<commit_after>#ifndef TWISTEDCPP_PROTOCOL_CORE
#define TWISTEDCPP_PROTOCOL_CORE

#include "detail/sockets.hpp"

#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/steady_timer.hpp>
#include <boost/optional.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>
#include <boost/asio/high_resolution_timer.hpp>
#include <boost/ref.hpp>

#ifndef NDEBUG
#include <iostream>
#endif

namespace twisted {

template <typename ChildProtocol, typename BufferType>
class protocol_core : public std::enable_shared_from_this<ChildProtocol> {
public:
    typedef detail::socket_base socket_type;
    typedef boost::asio::steady_timer timer_type;
    typedef boost::asio::io_service::strand strand_type;
    typedef BufferType buffer_type;
    typedef typename buffer_type::iterator buffer_iterator;
    typedef typename buffer_type::const_iterator const_buffer_iterator;

    protocol_core() = default;
    protocol_core(protocol_core&&) = default;
    protocol_core& operator=(protocol_core&&) = default;

    void set_socket(std::unique_ptr<socket_type> socket) {
        _socket = std::move(socket);
    }

    void run_protocol() {
        auto self = this_protocol().shared_from_this();
        boost::asio::spawn(_socket->get_io_service(),
                           [this, self](boost::asio::yield_context yield) {
            _yield = boost::in_place(yield);

            try {
                _socket->do_handshake(*_yield);

                while (_socket->is_open()) {
                    auto bytes_read =
                        _socket->async_read_some(asio_buffer(), yield);
                    checked_on_message(buffer_begin(),
                                       std::next(buffer_begin(), bytes_read));
                }
            }
            catch (boost::system::system_error& connection_error) {
                handle_network_error(connection_error);
            }

            this_protocol().on_disconnect();
        });
    }

    template <typename Duration, typename Callable>
    void call_later(Duration duration, Callable callable) {
        auto self = this_protocol().shared_from_this();
        // we pass our existing yield_context and not the io_service such that
        // both contexts run under the same strand
        boost::asio::spawn(*_yield, [this, duration, callable, self](
                                        boost::asio::yield_context yield) {
            boost::asio::high_resolution_timer timer(_socket->get_io_service(),
                                                     duration);
            timer.async_wait(yield);

            // we need to exchange the yield context so that that the user can
            // use the send_message function in the right context
            boost::optional<boost::asio::yield_context> old_yield(
                boost::in_place(*_yield));
            _yield = boost::in_place(yield);
            callable();
            _yield = boost::in_place(*old_yield);
        });
    }

    template <typename Callable>
    void call(Callable callable) {
        call_later(std::chrono::seconds(0), std::move(callable));
    }

    template <typename Callable, typename... Args>
    void call_from_thread(Callable&& callable, Args&&... args) {
        _socket->get_io_service().post(std::bind(
            std::forward<Callable>(callable), std::forward<Args>(args)...));
    }

    template <typename Duration>
    void wait_for(const Duration& duration) const {
        boost::asio::high_resolution_timer timer(_socket->get_io_service(),
                                                 duration);
        timer.async_wait(*_yield);
    }

    template <typename Iter>
    void send_message(Iter begin, Iter end) {
        _socket->async_write(
            boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);
    }

    template <typename Iter>
    void forward(const protocol_core& other, Iter begin, Iter end) {
        other._socket->async_write(
            boost::asio::buffer(&*begin, std::distance(begin, end)), *_yield);
    }

    template<typename ConstBufferSequence>
    void send_buffers(const ConstBufferSequence& buffers) {
        _socket->async_write(buffers, *_yield);
    }

    /*
     * @brief default on_disconnect implementation; does nothing
     */
    void on_disconnect() {}

    /*
     * @brief default on_error implementation; swallows everything
     */
    void on_error(std::exception_ptr eptr) {
        try {
            std::rethrow_exception(eptr);
        }
        catch (const std::exception& excep) {
            print_exception_what(excep);
        }
    }

    bool is_connected() const { return _socket->is_open(); }

    void lose_connection() { _socket->close(); }

    /*
     * @brief CRTP wrapper for derived class access
     */
    ChildProtocol& this_protocol() {
        return *static_cast<ChildProtocol*>(this);
    }

    /*
     * @brief CRTP wrapper for derived class access
     */
    const ChildProtocol& this_protocol() const {
        return *static_cast<ChildProtocol*>(this);
    }

private:
    void checked_on_message(const_buffer_iterator begin,
                            const_buffer_iterator end) {
        try {
            this_protocol().on_message(begin, end);
        }
        catch (...) {
            this_protocol().on_error(std::current_exception());
        }
    }

#ifdef NDEBUG
    void handle_network_error(boost::system::system_error&) {
#else
    void handle_network_error(boost::system::system_error& connection_error) {
        print_connection_error(connection_error);
#endif
    }

    void handle_user_error(const std::exception_ptr& excep) {
        this_protocol().on_error(excep);
    }

    void print_connection_error(
        const boost::system::system_error& connection_error) const {
        std::cerr << "Client disconnected with code " << connection_error.what()
                  << std::endl;
    }

    void print_exception_what(const std::exception& excep) const {
        std::cerr << "Killing connection, exception in client handler: "
                  << excep.what() << std::endl;
    }

    buffer_iterator buffer_begin() {
        using std::begin;
        return begin(this_protocol().read_buffer());
    }

    buffer_iterator buffer_begin() const {
        using std::begin;
        return begin(this_protocol().read_buffer());
    }

    buffer_iterator buffer_end() {
        using std::end;
        return end(this_protocol().read_buffer());
    }

    buffer_iterator buffer_end() const {
        using std::end;
        return end(this_protocol().read_buffer());
    }

    boost::asio::mutable_buffers_1 asio_buffer() {
        return boost::asio::buffer(&*buffer_begin(),
                                   std::distance(buffer_begin(), buffer_end()));
    }

private:
    boost::optional<boost::asio::yield_context> _yield;
    std::unique_ptr<socket_type> _socket;
};

} // namespace twisted

#endif
<|endoftext|>


<commit_before>#ifndef VSMC_INTERNAL_FORWARD_HPP
#define VSMC_INTERNAL_FORWARD_HPP

namespace vsmc {

namespace internal {

template <typename, typename> class InitializeBase;
template <typename, typename> class MoveBase;
template <typename, unsigned, typename> class MonitorEvalBase;
template <typename, typename> class PathEvalBase;

} // namespace vsmc::internal

class NullTimer;

class VirtualDerivedTag {};
class StaticDerivedTag  {};
class PreResamplingTag  {};
class PostResamplingTag {};

template <typename> class Sampler;
template <typename> class Particle;
template <typename> class Monitor;
template <typename> class Path;

template <unsigned, typename> class StateBase;
template <typename> class SingleParticle;
template <typename> class ConstSingleParticle;

template <unsigned, typename, typename P = NullTimer> class StateSeq;
template <typename, typename D = StaticDerivedTag> class InitializeSeq;
template <typename, typename D = StaticDerivedTag> class MoveSeq;
template <typename, unsigned, typename D = StaticDerivedTag>
class MonitorEvalSeq;
template <typename, typename D = StaticDerivedTag> class PathEvalSeq;

template <unsigned, typename, typename P = NullTimer> class StateTBB;
template <typename, typename D = StaticDerivedTag> class InitializeTBB;
template <typename, typename D = StaticDerivedTag> class MoveTBB;
template <typename, unsigned, typename D = StaticDerivedTag>
class MonitorEvalTBB;
template <typename, typename D = StaticDerivedTag> class PathEvalTBB;

template <unsigned, typename, typename P = NullTimer> class StateCL;
template <typename> class InitializeCL;
template <typename> class MoveCL;
template <typename, unsigned> class MonitorEvalCL;
template <typename> class PathEvalCL;

} // namesapce vsmc

#endif // VSMC_INTERNAL_FORWARD_HPP
<commit_msg>fix the the default behavior<commit_after>#ifndef VSMC_INTERNAL_FORWARD_HPP
#define VSMC_INTERNAL_FORWARD_HPP

namespace vsmc {

namespace internal {

template <typename, typename> class InitializeBase;
template <typename, typename> class MoveBase;
template <typename, unsigned, typename> class MonitorEvalBase;
template <typename, typename> class PathEvalBase;

} // namespace vsmc::internal

class NullTimer;

class VirtualDerivedTag {};
class StaticDerivedTag  {};
class PreResamplingTag  {};
class PostResamplingTag {};

template <typename> class Sampler;
template <typename> class Particle;
template <typename> class Monitor;
template <typename> class Path;

template <unsigned, typename> class StateBase;
template <typename> class SingleParticle;
template <typename> class ConstSingleParticle;

template <unsigned, typename, typename P = NullTimer> class StateSeq;
template <typename, typename D = VirtualDerivedTag> class InitializeSeq;
template <typename, typename D = VirtualDerivedTag> class MoveSeq;
template <typename, unsigned, typename D = VirtualDerivedTag>
class MonitorEvalSeq;
template <typename, typename D = VirtualDerivedTag> class PathEvalSeq;

template <unsigned, typename, typename P = NullTimer> class StateTBB;
template <typename, typename D = VirtualDerivedTag> class InitializeTBB;
template <typename, typename D = VirtualDerivedTag> class MoveTBB;
template <typename, unsigned, typename D = VirtualDerivedTag>
class MonitorEvalTBB;
template <typename, typename D = VirtualDerivedTag> class PathEvalTBB;

template <unsigned, typename, typename P = NullTimer> class StateCL;
template <typename> class InitializeCL;
template <typename> class MoveCL;
template <typename, unsigned> class MonitorEvalCL;
template <typename> class PathEvalCL;

} // namesapce vsmc

#endif // VSMC_INTERNAL_FORWARD_HPP
<|endoftext|>


<commit_before>#include <cppunit/tools/StringTools.h>
#include <cppunit/tools/XmlElement.h>
#include <stdexcept>

CPPUNIT_NS_BEGIN

XmlElement::XmlElement( std::string elementName,
                        std::string content )
  : m_name( elementName )
  , m_content( content )
{
}

XmlElement::XmlElement( std::string elementName,
                        int numericContent )
  : m_name( elementName )
{
  setContent( numericContent );
}

XmlElement::~XmlElement()
{
  Elements::iterator itNode = m_elements.begin();
  while ( itNode != m_elements.end() )
  {
    XmlElement *element = *itNode;
    delete *itNode++;
  }
}

std::string
XmlElement::name() const
{
  return m_name;
}

std::string
XmlElement::content() const
{
  return m_content;
}

void
XmlElement::setName( const std::string &name )
{
  m_name = name;
}

void
XmlElement::setContent( const std::string &content )
{
  m_content = content;
}

void
XmlElement::setContent( int numericContent )
{
  m_content = StringTools::toString( numericContent );
}

void
XmlElement::addAttribute( std::string attributeName,
                          std::string value  )
{
  m_attributes.push_back( Attribute( attributeName, value ) );
}

void
XmlElement::addAttribute( std::string attributeName,
                          int numericValue )
{
  addAttribute( attributeName, StringTools::toString( numericValue ) );
}

void
XmlElement::addElement( XmlElement *node )
{
  m_elements.push_back( node );
}

int
XmlElement::elementCount() const
{
  return m_elements.size();
}

XmlElement *
XmlElement::elementAt( int index ) const
{
  if ( index < 0  ||  index >= elementCount() )
    throw std::invalid_argument( "XmlElement::elementAt(), out of range index" );

  return m_elements[ index ];
}

XmlElement *
XmlElement::elementFor( const std::string &name ) const
{
  Elements::const_iterator itElement = m_elements.begin();
  for ( ; itElement != m_elements.end(); ++itElement )
  {
    if ( (*itElement)->name() == name )
      return *itElement;
  }

  throw std::invalid_argument( "XmlElement::elementFor(), not matching child element found" );
  return NULL;  // make some compilers happy.
}

std::string
XmlElement::toString( const std::string &indent ) const
{
  std::string element( indent );
  element += "<";
  element += m_name;
  if ( !m_attributes.empty() )
  {
    element += " ";
    element += attributesAsString();
  }
  element += ">";

  if ( !m_elements.empty() )
  {
    element += "\n";

    std::string subNodeIndent( indent + "  " );
    Elements::const_iterator itNode = m_elements.begin();
    while ( itNode != m_elements.end() )
    {
      const XmlElement *node = *itNode++;
      element += node->toString( subNodeIndent );
    }

    element += indent;
  }

  if ( !m_content.empty() )
  {
    element += escape( m_content );
    if ( !m_elements.empty() )
    {
      element += "\n";
      element += indent;
    }
  }

  element += "</";
  element += m_name;
  element += ">\n";

  return element;
}

std::string
XmlElement::attributesAsString() const
{
  std::string attributes;
  Attributes::const_iterator itAttribute = m_attributes.begin();
  while ( itAttribute != m_attributes.end() )
  {
    if ( !attributes.empty() )
       attributes += " ";

    const Attribute &attribute = *itAttribute++;
    attributes += attribute.first;
    attributes += "=\"";
    attributes += escape( attribute.second );
    attributes += "\"";
  }
  return attributes;
}

std::string
XmlElement::escape( std::string value ) const
{
  std::string escaped;
  for ( unsigned int index =0; index < value.length(); ++index )
  {
    char c = value[index ];
    switch ( c )    // escape all predefined XML entity (safe?)
    {
    case '<':
      escaped += "<";
      break;
    case '>':
      escaped += ">";
      break;
    case '&':
      escaped += "&";
      break;
    case '\'':
      escaped += "'";
      break;
    case '"':
      escaped += """;
      break;
    default:
      escaped += c;
    }
  }

  return escaped;
}

CPPUNIT_NS_END

<commit_msg>* clean up<commit_after>#include <cppunit/tools/StringTools.h>
#include <cppunit/tools/XmlElement.h>
#include <stdexcept>

CPPUNIT_NS_BEGIN

XmlElement::XmlElement( std::string elementName,
                        std::string content )
  : m_name( elementName )
  , m_content( content )
{
}

XmlElement::XmlElement( std::string elementName,
                        int numericContent )
  : m_name( elementName )
{
  setContent( numericContent );
}

XmlElement::~XmlElement()
{
  Elements::iterator itNode = m_elements.begin();
  while ( itNode != m_elements.end() )
  {
    XmlElement *element = *itNode++;
    delete element;
  }
}

std::string
XmlElement::name() const
{
  return m_name;
}

std::string
XmlElement::content() const
{
  return m_content;
}

void
XmlElement::setName( const std::string &name )
{
  m_name = name;
}

void
XmlElement::setContent( const std::string &content )
{
  m_content = content;
}

void
XmlElement::setContent( int numericContent )
{
  m_content = StringTools::toString( numericContent );
}

void
XmlElement::addAttribute( std::string attributeName,
                          std::string value  )
{
  m_attributes.push_back( Attribute( attributeName, value ) );
}

void
XmlElement::addAttribute( std::string attributeName,
                          int numericValue )
{
  addAttribute( attributeName, StringTools::toString( numericValue ) );
}

void
XmlElement::addElement( XmlElement *node )
{
  m_elements.push_back( node );
}

int
XmlElement::elementCount() const
{
  return m_elements.size();
}

XmlElement *
XmlElement::elementAt( int index ) const
{
  if ( index < 0  ||  index >= elementCount() )
    throw std::invalid_argument( "XmlElement::elementAt(), out of range index" );

  return m_elements[ index ];
}

XmlElement *
XmlElement::elementFor( const std::string &name ) const
{
  Elements::const_iterator itElement = m_elements.begin();
  for ( ; itElement != m_elements.end(); ++itElement )
  {
    if ( (*itElement)->name() == name )
      return *itElement;
  }

  throw std::invalid_argument( "XmlElement::elementFor(), not matching child element found" );
  return NULL;  // make some compilers happy.
}

std::string
XmlElement::toString( const std::string &indent ) const
{
  std::string element( indent );
  element += "<";
  element += m_name;
  if ( !m_attributes.empty() )
  {
    element += " ";
    element += attributesAsString();
  }
  element += ">";

  if ( !m_elements.empty() )
  {
    element += "\n";

    std::string subNodeIndent( indent + "  " );
    Elements::const_iterator itNode = m_elements.begin();
    while ( itNode != m_elements.end() )
    {
      const XmlElement *node = *itNode++;
      element += node->toString( subNodeIndent );
    }

    element += indent;
  }

  if ( !m_content.empty() )
  {
    element += escape( m_content );
    if ( !m_elements.empty() )
    {
      element += "\n";
      element += indent;
    }
  }

  element += "</";
  element += m_name;
  element += ">\n";

  return element;
}

std::string
XmlElement::attributesAsString() const
{
  std::string attributes;
  Attributes::const_iterator itAttribute = m_attributes.begin();
  while ( itAttribute != m_attributes.end() )
  {
    if ( !attributes.empty() )
       attributes += " ";

    const Attribute &attribute = *itAttribute++;
    attributes += attribute.first;
    attributes += "=\"";
    attributes += escape( attribute.second );
    attributes += "\"";
  }
  return attributes;
}

std::string
XmlElement::escape( std::string value ) const
{
  std::string escaped;
  for ( unsigned int index =0; index < value.length(); ++index )
  {
    char c = value[index ];
    switch ( c )    // escape all predefined XML entity (safe?)
    {
    case '<':
      escaped += "<";
      break;
    case '>':
      escaped += ">";
      break;
    case '&':
      escaped += "&";
      break;
    case '\'':
      escaped += "'";
      break;
    case '"':
      escaped += """;
      break;
    default:
      escaped += c;
    }
  }

  return escaped;
}

CPPUNIT_NS_END

<|endoftext|>


<commit_before>#include "../../include/controllers/StationPlayerController.hpp"
#include "../../include/StationPlayer.hpp"
#include "../../include/Constants.hpp"
#include "../../include/Utilities.hpp"

StationPlayerController::StationPlayerController(StatesManager& manager, State::Context context) noexcept
    : Controller(manager, context)
{
}

void StationPlayerController::process_event_command(const radiostream::Event e, std::any data)
{
    using namespace constants;
    switch (e)
    {
    case radiostream::Event::PauseClicked:
    {
        context_.station_player_.pause();
    }
    break;

    case radiostream::Event::PlayClicked:
    {
        context_.station_player_.play();
    }
    break;

    case radiostream::Event::VolumeChanged:
    {
        context_.station_player_.set_volume(volume_int_to_float(std::any_cast<unsigned>(data)));
    }
    break;

    case radiostream::Event::NewStationRequested:
    {
        const auto station = std::any_cast<Station>(data);
        std::thread thread = std::thread([this, station](){
            if(context_.station_player_.set_station(station))
                context_.station_player_.play();
        });
        thread.detach();
    }
    break;

    case radiostream::Event::MuteClicked:
    {
        context_.station_player_.mute();
    }
    break;

    case radiostream::Event::MuteUnclicked:
    {
        context_.station_player_.unmute();
    }
    break;
    }
}
<commit_msg>Missing header fix.<commit_after>#include "../../include/controllers/StationPlayerController.hpp"
#include "../../include/StationPlayer.hpp"
#include "../../include/Constants.hpp"
#include "../../include/Utilities.hpp"
#include <thread>

StationPlayerController::StationPlayerController(StatesManager& manager, State::Context context) noexcept
    : Controller(manager, context)
{
}

void StationPlayerController::process_event_command(const radiostream::Event e, std::any data)
{
    using namespace constants;
    switch (e)
    {
    case radiostream::Event::PauseClicked:
    {
        context_.station_player_.pause();
    }
    break;

    case radiostream::Event::PlayClicked:
    {
        context_.station_player_.play();
    }
    break;

    case radiostream::Event::VolumeChanged:
    {
        context_.station_player_.set_volume(volume_int_to_float(std::any_cast<unsigned>(data)));
    }
    break;

    case radiostream::Event::NewStationRequested:
    {
        const auto station = std::any_cast<Station>(data);
        std::thread thread = std::thread([this, station](){
            if(context_.station_player_.set_station(station))
                context_.station_player_.play();
        });
        thread.detach();
    }
    break;

    case radiostream::Event::MuteClicked:
    {
        context_.station_player_.mute();
    }
    break;

    case radiostream::Event::MuteUnclicked:
    {
        context_.station_player_.unmute();
    }
    break;
    }
}
<|endoftext|>


<commit_before>#include <Socket/SocketSerialized.hpp>
#include <Socket/define.hpp>

namespace ntw {

SocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)
{
    //reserver les 2 premier bits pour la taille
    _cursor_end =_cursor_begin = 4;
    //is_send=false;
};

SocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)
{
    std::swap(s.sock,sock);
    std::swap(s.sock_cfg,sock_cfg);
    _cursor_end =_cursor_begin = 4;
};

void SocketSerialized::send()
{
    //écrire la taille dans les 2 premier oct
    uint16_t size = _cursor_end - _cursor_begin;
    uint8_t *d = (uint8_t *)&size;
    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    _buffer[_cursor_begin - 4] = d[0];
    _buffer[_cursor_begin - 3] = d[1];
    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    _buffer[_cursor_begin - 4] = d[1];
    _buffer[_cursor_begin - 3] = d[0];
    #else
    #error "byte orden not suported (PDP endian)"
    #endif

    {
        uint16_t st = status;
        d = (uint8_t*)&st;
        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        _buffer[_cursor_begin - 2] = d[0];
        _buffer[_cursor_begin - 1] = d[1];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        _buffer[_cursor_begin - 2] = d[1];
        _buffer[_cursor_begin - 1] = d[0];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
    }
    //envoyer
    //std::cout<<"send: "<<*this<<std::endl;
    int res = Socket::send(_buffer+_cursor_begin-4, 4+size);
    std::cout<<"Send : "<<res<<"/"<<int(4+size)<<std::endl;
    //reset
    //clear();
};

int SocketSerialized::receive()
{
    //recuperer la taille dans les 4 premier oct
    int res = Socket::receive(_buffer,4);
    if (res > 0)
    {
        uint8_t d[2];
        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        d[0]= _buffer[0];
        d[1]= _buffer[1];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        d[1]= _buffer[0];
        d[0]= _buffer[1];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
        uint16_t size = *(uint16_t*)&d;

        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        d[0]= _buffer[2];
        d[1]= _buffer[3];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        d[1]= _buffer[2];
        d[0]= _buffer[3];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
        status = *(uint16_t*)&d;

        //reset
        if (int(_buffer_size) < 4+size)
            resize(4+size);
        //else _buffer_size ne change pas
        _cursor_begin = 4;
        _cursor_end = 4+size;
        //remplacer le buffer
        if(size>0)
        {
            int recv_left = size;
            int recv = 0;
            while(recv_left > 0)
            {
                recv = Socket::receive(_buffer+res,recv_left-recv);
                if(recv<0)
                    break;
                std::cout<<"Recv size: "<<recv<<std::endl;
                res+=recv;
                recv_left -=recv;
            }
        }
    }
    else
    {
        clear();
        setStatus(NTW_STOP_CONNEXION);
    }
    //std::cout<<"recv: "<<*this<<std::endl;
    std::cout<<"Recv real: "<<res<<std::endl;
    return res;
};

void SocketSerialized::setStatus(short int st)
{
    status = st;
}

short int SocketSerialized::getStatus()const
{
    return status;
}

void SocketSerialized::clear()
{
    _cursor_begin = _cursor_end = 4;
}

std::ostream& operator<<(std::ostream& output,const SocketSerialized& self)
{
    output<<"["<<self.size()<<":"<<self.status<<"]";
    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)
    {
        if(self._buffer[i] < 33 or self._buffer[i] >126)
            output<<"<"<<(int)self._buffer[i]<<">";
        else
            output<<"'"<<(char)self._buffer[i]<<"'";
    }
    return output;
};

};
<commit_msg>test fix bug<commit_after>#include <Socket/SocketSerialized.hpp>
#include <Socket/define.hpp>

namespace ntw {

SocketSerialized::SocketSerialized(Socket::Dommaine dommaine,Socket::Type type,int protocole): Serializer(255), Socket(dommaine,type,protocole), status(0)
{
    //reserver les 2 premier bits pour la taille
    _cursor_end =_cursor_begin = 4;
    //is_send=false;
};

SocketSerialized::SocketSerialized(Socket&& s) : Serializer(255)
{
    std::swap(s.sock,sock);
    std::swap(s.sock_cfg,sock_cfg);
    _cursor_end =_cursor_begin = 4;
};

void SocketSerialized::send()
{
    //écrire la taille dans les 2 premier oct
    uint16_t size = _cursor_end - _cursor_begin;
    uint8_t *d = (uint8_t *)&size;
    #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
    _buffer[_cursor_begin - 4] = d[0];
    _buffer[_cursor_begin - 3] = d[1];
    #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
    _buffer[_cursor_begin - 4] = d[1];
    _buffer[_cursor_begin - 3] = d[0];
    #else
    #error "byte orden not suported (PDP endian)"
    #endif

    {
        uint16_t st = status;
        d = (uint8_t*)&st;
        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        _buffer[_cursor_begin - 2] = d[0];
        _buffer[_cursor_begin - 1] = d[1];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        _buffer[_cursor_begin - 2] = d[1];
        _buffer[_cursor_begin - 1] = d[0];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
    }
    //envoyer
    //std::cout<<"send: "<<*this<<std::endl;
    int res = Socket::send(_buffer+_cursor_begin-4, 4+size);
    std::cout<<"Send : "<<res<<"/"<<int(4+size)<<std::endl;
    //reset
    //clear();
};

int SocketSerialized::receive()
{
    //recuperer la taille dans les 4 premier oct
    int res = Socket::receive(_buffer,4);
    if (res > 0)
    {
        uint8_t d[2];
        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        d[0]= _buffer[0];
        d[1]= _buffer[1];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        d[1]= _buffer[0];
        d[0]= _buffer[1];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
        uint16_t size = *(uint16_t*)&d;

        #if __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
        d[0]= _buffer[2];
        d[1]= _buffer[3];
        #elif __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
        d[1]= _buffer[2];
        d[0]= _buffer[3];
        #else
        #error "byte orden not suported (PDP endian)"
        #endif
        status = *(uint16_t*)&d;

        //reset
        if (int(_buffer_size) < 4+size)
            resize(4+size);
        //else _buffer_size ne change pas
        _cursor_begin = 4;
        _cursor_end = 4+size;
        //remplacer le buffer
        if(size>0)
        {
            int recv_left = size;
            int recv = 0;
            while(recv_left > 0)
            {
                recv = Socket::receive(_buffer+res,recv_left);
                if(recv<0)
                    break;
                std::cout<<"Recv size: "<<recv<<std::endl;
                res+=recv;
                recv_left -=recv;
            }
        }
    }
    else
    {
        clear();
        setStatus(NTW_STOP_CONNEXION);
    }
    //std::cout<<"recv: "<<*this<<std::endl;
    std::cout<<"Recv real: "<<res<<std::endl;
    return res;
};

void SocketSerialized::setStatus(short int st)
{
    status = st;
}

short int SocketSerialized::getStatus()const
{
    return status;
}

void SocketSerialized::clear()
{
    _cursor_begin = _cursor_end = 4;
}

std::ostream& operator<<(std::ostream& output,const SocketSerialized& self)
{
    output<<"["<<self.size()<<":"<<self.status<<"]";
    for(unsigned int i=self._cursor_begin; i<self._cursor_end;++i)
    {
        if(self._buffer[i] < 33 or self._buffer[i] >126)
            output<<"<"<<(int)self._buffer[i]<<">";
        else
            output<<"'"<<(char)self._buffer[i]<<"'";
    }
    return output;
};

};
<|endoftext|>