text
stringlengths 54
60.6k
|
---|
<commit_before>/*!
* \file arc_stroked_point.hpp
* \brief file arc_stroked_point.hpp
*
* Copyright 2018 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/painter/painter_attribute.hpp>
namespace fastuidraw {
/*!\addtogroup Paths
* @{
*/
/*!
* \brief
* An ArcStrokedPoint holds the data for a point of stroking
* where the segments can be arcs of a circle. The upshot
* is that a fragment shader will determine per-pixel coverage.
* In addition, the data is so that changing the stroking width
* or miter limit does not change the stroking data.
*/
class ArcStrokedPoint
{
public:
/*!
* \brief
* Enumeration type to specify how to compute the location
* of an ArcStrokedPoint.
*/
enum offset_type_t
{
/*!
* A point of an arc. Indicates the point is part of
* an arc.
*/
offset_arc_point,
/*!
* The point is part of a line-segment
*/
offset_line_segment,
/*!
* Represents a point at the start or end of an edge.
* When performing dashed stroking with caps, these
* points can be expanded into quads to cover a cap
* induced by stroking at the start or end of an
* edge.
*/
offset_arc_point_dashed_capper,
/*!
* Number of offset types, not an actual offset type(!).
*/
number_offset_types,
};
/*!
* \brief
* Enumeration encoding of bits of \ref m_packed_data
* common to all offset types.
*/
enum packed_data_bit_layout_common_t
{
/*!
* Bit0 for holding the offset_type() value
* of the point.
*/
offset_type_bit0 = 0,
/*!
* number of bits needed to hold the
* offset_type() value of the point.
*/
offset_type_num_bits = 2,
/*!
* Bit indicates that the point in on the stroking
* boundary. Points with this bit down have that
* the vertex position after stroking is the same
* as \ref m_position.
*/
boundary_bit = offset_type_bit0 + offset_type_num_bits,
/*!
* Bit indicates that point is on the end of a
* segment.
*/
end_segment_bit,
/*!
* Bit indicates that when doing dashed stroking that
* the value the distance value is the same for all
* points of a triangle, i.e. the dashed coverage
* computation can be done purely from the vertex
* shader
*/
distance_constant_on_primitive_bit,
/*!
* Bit indicates that the primitive formed is for a join
*/
join_bit,
/*!
* Bit0 for holding the depth() value
* of the point
*/
depth_bit0,
/*!
* number of bits needed to hold the
* depth() value of the point.
*/
depth_num_bits = 20,
/*!
* Number of bits used on common packed data
*/
number_common_bits = depth_bit0 + depth_num_bits,
};
/*!
* Enumeration of the bits of \ref m_packed_data
* for those with offset type \ref offset_arc_point
*/
enum packed_data_bit_stroking_boundary_t
{
/*!
* Bit indicates that the point is a beyond stroking
* boundary bit. These points go beyond the stroking
* boundary to make sure that the triangles emitted
* contain the stroked arc.
*/
beyond_boundary_bit = number_common_bits,
/*!
* If bit is up, then point is on the inside
* stroking boundary, otherwise the point is
* on the outside stroking boundary.
*/
inner_stroking_bit,
/*!
* When this bit is up and the stroking radius exceeds
* the arc-radius, the point should be placed at the
* center of the arc.
*/
move_to_arc_center_bit,
};
/*!
* Enumeration of the bits of \ref m_packed_data
* for those with offset type \ref offset_arc_point_dashed_capper
*/
enum packed_data_bit_arc_point_dashed_capper
{
/*!
* if up, the point is to be moved in the direction
* of \ref m_data to cover an induced cap.
*/
extend_bit = number_common_bits,
};
/*!
* \brief
* Enumeration holding bit masks generated from
* values in \ref packed_data_bit_layout_common_t.
*/
enum packed_data_bit_masks_t
{
/*!
* Mask generated for \ref offset_type_bit0 and
* \ref offset_type_num_bits
*/
offset_type_mask = FASTUIDRAW_MASK(offset_type_bit0, offset_type_num_bits),
/*!
* Mask generated for \ref boundary_bit
*/
boundary_mask = FASTUIDRAW_MASK(boundary_bit, 1),
/*!
* Mask generated for \ref boundary_bit
*/
beyond_boundary_mask = FASTUIDRAW_MASK(beyond_boundary_bit, 1),
/*!
* Mask generated for \ref inner_stroking_bit
*/
inner_stroking_mask = FASTUIDRAW_MASK(inner_stroking_bit, 1),
/*!
* Mask generated for \ref move_to_arc_center_bit
*/
move_to_arc_center_mask = FASTUIDRAW_MASK(move_to_arc_center_bit, 1),
/*!
* Mask generated for \ref end_segment_bit
*/
end_segment_mask = FASTUIDRAW_MASK(end_segment_bit, 1),
/*!
* Mask generated for \ref distance_constant_on_primitive_bit
*/
distance_constant_on_primitive_mask = FASTUIDRAW_MASK(distance_constant_on_primitive_bit, 1),
/*!
* Mask generated for \ref join_bit
*/
join_mask = FASTUIDRAW_MASK(join_bit, 1),
/*!
* Mask generated for \ref extend_bit
*/
extend_mask = FASTUIDRAW_MASK(extend_bit, 1),
/*!
* Mask generated for \ref depth_bit0 and \ref depth_num_bits
*/
depth_mask = FASTUIDRAW_MASK(depth_bit0, depth_num_bits),
};
/*!
* Give the position of the point on the path.
*/
vec2 m_position;
/*!
* Gives the unit vector in which to push the point.
* For those points that are arc's the location of
* the center is always given by
* \ref m_position - \ref radius() * \ref m_offset_direction
*/
vec2 m_offset_direction;
/*!
* Meaning of \ref m_data depends on \ref offset_type(). If
* \ref offset_type() is \ref offset_line_segment, then
* \ref m_data holds the vector from this point to other
* point of the line segment. Otherwise, \ref m_data[0]
* holds the radius of the arc and \ref m_data[1] holds
* the angle difference from the end of the arc to the
* start of the arc.
*/
vec2 m_data;
/*!
* Gives the distance of the point from the start
* of the -edge- on which the point resides.
*/
float m_distance_from_edge_start;
/*!
* Gives the distance of the point from the start
* of the -contour- on which the point resides.
*/
float m_distance_from_contour_start;
/*!
* Gives the length of the edge on which the
* point lies. This value is the same for all
* points along a fixed edge.
*/
float m_edge_length;
/*!
* Gives the length of the contour open on which
* the point lies. This value is the same for all
* points along a fixed contour.
*/
float m_open_contour_length;
/*!
* Gives the length of the contour closed on which
* the point lies. This value is the same for all
* points along a fixed contour.
*/
float m_closed_contour_length;
/*!
* Bit field with data packed.
*/
uint32_t m_packed_data;
/*!
* Provides the point type from a value of \ref m_packed_data.
* The return value is one of the enumerations of
* \ref offset_type_t.
* \param packed_data_value value suitable for \ref m_packed_data
*/
static
enum offset_type_t
offset_type(uint32_t packed_data_value)
{
uint32_t v;
v = unpack_bits(offset_type_bit0, offset_type_num_bits, packed_data_value);
return static_cast<enum offset_type_t>(v);
}
/*!
* Provides the point type for the point. The return value
* is one of the enumerations of \ref offset_type_t.
*/
enum offset_type_t
offset_type(void) const
{
return offset_type(m_packed_data);
}
/*!
* If a point from an arc-segment, gives the radius
* of the arc, equivalent to \ref m_data[0].
*/
float
radius(void) const
{
return m_data[0];
}
/*!
* If a point from an arc-segment, gives the radius
* of the arc, equivalent to \ref m_data[0].
*/
float&
radius(void)
{
return m_data[0];
}
/*!
* If a point from an arc-segment, gives the angle
* of the arc, equivalent to \ref m_data[1].
*/
float
arc_angle(void) const
{
return m_data[1];
}
/*!
* If a point from an arc-segment, gives the angle
* of the arc, equivalent to \ref m_data[1].
*/
float&
arc_angle(void)
{
return m_data[1];
}
/*!
* When stroking the data, the depth test to only
* pass when the depth value is -strictly- larger
* so that a fixed pixel is not stroked twice by
* a single path. The value returned by depth() is
* a relative z-value for a vertex. The points
* drawn first have the largest z-values.
*/
uint32_t
depth(void) const
{
return unpack_bits(depth_bit0, depth_num_bits, m_packed_data);
}
/*!
* Pack the data of this \ref ArcStrokedPoint into a \ref
* PainterAttribute. The packing is as follows:
* - PainterAttribute::m_attrib0 .xy -> \ref m_position (float)
* - PainterAttribute::m_attrib0 .zw -> \ref m_offset_direction (float)
* - PainterAttribute::m_attrib1 .x -> \ref m_distance_from_edge_start (float)
* - PainterAttribute::m_attrib1 .y -> \ref m_distance_from_contour_start (float)
* - PainterAttribute::m_attrib1 .zw -> \ref m_data (float)
* - PainterAttribute::m_attrib2 .x -> \ref m_packed_data (uint)
* - PainterAttribute::m_attrib2 .y -> \ref m_edge_length (float)
* - PainterAttribute::m_attrib2 .z -> \ref m_open_contour_length (float)
* - PainterAttribute::m_attrib2 .w -> \ref m_closed_contour_length (float)
*
* \param dst PainterAttribute to which to pack
*/
void
pack_point(PainterAttribute *dst) const;
/*!
* Unpack an \ref ArcStrokedPoint from a \ref PainterAttribute.
* \param dst point to which to unpack data
* \param src PainterAttribute from which to unpack data
*/
static
void
unpack_point(ArcStrokedPoint *dst, const PainterAttribute &src);
};
/*! @} */
}
<commit_msg>fastuidraw/painter/arc_stroked_point: add method to set depth() value<commit_after>/*!
* \file arc_stroked_point.hpp
* \brief file arc_stroked_point.hpp
*
* Copyright 2018 by Intel.
*
* Contact: [email protected]
*
* This Source Code Form is subject to the
* terms of the Mozilla Public License, v. 2.0.
* If a copy of the MPL was not distributed with
* this file, You can obtain one at
* http://mozilla.org/MPL/2.0/.
*
* \author Kevin Rogovin <[email protected]>
*
*/
#pragma once
#include <fastuidraw/util/vecN.hpp>
#include <fastuidraw/util/util.hpp>
#include <fastuidraw/painter/painter_attribute.hpp>
namespace fastuidraw {
/*!\addtogroup Paths
* @{
*/
/*!
* \brief
* An ArcStrokedPoint holds the data for a point of stroking
* where the segments can be arcs of a circle. The upshot
* is that a fragment shader will determine per-pixel coverage.
* In addition, the data is so that changing the stroking width
* or miter limit does not change the stroking data.
*/
class ArcStrokedPoint
{
public:
/*!
* \brief
* Enumeration type to specify how to compute the location
* of an ArcStrokedPoint.
*/
enum offset_type_t
{
/*!
* A point of an arc. Indicates the point is part of
* an arc.
*/
offset_arc_point,
/*!
* The point is part of a line-segment
*/
offset_line_segment,
/*!
* Represents a point at the start or end of an edge.
* When performing dashed stroking with caps, these
* points can be expanded into quads to cover a cap
* induced by stroking at the start or end of an
* edge.
*/
offset_arc_point_dashed_capper,
/*!
* Number of offset types, not an actual offset type(!).
*/
number_offset_types,
};
/*!
* \brief
* Enumeration encoding of bits of \ref m_packed_data
* common to all offset types.
*/
enum packed_data_bit_layout_common_t
{
/*!
* Bit0 for holding the offset_type() value
* of the point.
*/
offset_type_bit0 = 0,
/*!
* number of bits needed to hold the
* offset_type() value of the point.
*/
offset_type_num_bits = 2,
/*!
* Bit indicates that the point in on the stroking
* boundary. Points with this bit down have that
* the vertex position after stroking is the same
* as \ref m_position.
*/
boundary_bit = offset_type_bit0 + offset_type_num_bits,
/*!
* Bit indicates that point is on the end of a
* segment.
*/
end_segment_bit,
/*!
* Bit indicates that when doing dashed stroking that
* the value the distance value is the same for all
* points of a triangle, i.e. the dashed coverage
* computation can be done purely from the vertex
* shader
*/
distance_constant_on_primitive_bit,
/*!
* Bit indicates that the primitive formed is for a join
*/
join_bit,
/*!
* Bit0 for holding the depth() value
* of the point
*/
depth_bit0,
/*!
* number of bits needed to hold the
* depth() value of the point.
*/
depth_num_bits = 20,
/*!
* Number of bits used on common packed data
*/
number_common_bits = depth_bit0 + depth_num_bits,
};
/*!
* Enumeration of the bits of \ref m_packed_data
* for those with offset type \ref offset_arc_point
*/
enum packed_data_bit_stroking_boundary_t
{
/*!
* Bit indicates that the point is a beyond stroking
* boundary bit. These points go beyond the stroking
* boundary to make sure that the triangles emitted
* contain the stroked arc.
*/
beyond_boundary_bit = number_common_bits,
/*!
* If bit is up, then point is on the inside
* stroking boundary, otherwise the point is
* on the outside stroking boundary.
*/
inner_stroking_bit,
/*!
* When this bit is up and the stroking radius exceeds
* the arc-radius, the point should be placed at the
* center of the arc.
*/
move_to_arc_center_bit,
};
/*!
* Enumeration of the bits of \ref m_packed_data
* for those with offset type \ref offset_arc_point_dashed_capper
*/
enum packed_data_bit_arc_point_dashed_capper
{
/*!
* if up, the point is to be moved in the direction
* of \ref m_data to cover an induced cap.
*/
extend_bit = number_common_bits,
};
/*!
* \brief
* Enumeration holding bit masks generated from
* values in \ref packed_data_bit_layout_common_t.
*/
enum packed_data_bit_masks_t
{
/*!
* Mask generated for \ref offset_type_bit0 and
* \ref offset_type_num_bits
*/
offset_type_mask = FASTUIDRAW_MASK(offset_type_bit0, offset_type_num_bits),
/*!
* Mask generated for \ref boundary_bit
*/
boundary_mask = FASTUIDRAW_MASK(boundary_bit, 1),
/*!
* Mask generated for \ref boundary_bit
*/
beyond_boundary_mask = FASTUIDRAW_MASK(beyond_boundary_bit, 1),
/*!
* Mask generated for \ref inner_stroking_bit
*/
inner_stroking_mask = FASTUIDRAW_MASK(inner_stroking_bit, 1),
/*!
* Mask generated for \ref move_to_arc_center_bit
*/
move_to_arc_center_mask = FASTUIDRAW_MASK(move_to_arc_center_bit, 1),
/*!
* Mask generated for \ref end_segment_bit
*/
end_segment_mask = FASTUIDRAW_MASK(end_segment_bit, 1),
/*!
* Mask generated for \ref distance_constant_on_primitive_bit
*/
distance_constant_on_primitive_mask = FASTUIDRAW_MASK(distance_constant_on_primitive_bit, 1),
/*!
* Mask generated for \ref join_bit
*/
join_mask = FASTUIDRAW_MASK(join_bit, 1),
/*!
* Mask generated for \ref extend_bit
*/
extend_mask = FASTUIDRAW_MASK(extend_bit, 1),
/*!
* Mask generated for \ref depth_bit0 and \ref depth_num_bits
*/
depth_mask = FASTUIDRAW_MASK(depth_bit0, depth_num_bits),
};
/*!
* Give the position of the point on the path.
*/
vec2 m_position;
/*!
* Gives the unit vector in which to push the point.
* For those points that are arc's the location of
* the center is always given by
* \ref m_position - \ref radius() * \ref m_offset_direction
*/
vec2 m_offset_direction;
/*!
* Meaning of \ref m_data depends on \ref offset_type(). If
* \ref offset_type() is \ref offset_line_segment, then
* \ref m_data holds the vector from this point to other
* point of the line segment. Otherwise, \ref m_data[0]
* holds the radius of the arc and \ref m_data[1] holds
* the angle difference from the end of the arc to the
* start of the arc.
*/
vec2 m_data;
/*!
* Gives the distance of the point from the start
* of the -edge- on which the point resides.
*/
float m_distance_from_edge_start;
/*!
* Gives the distance of the point from the start
* of the -contour- on which the point resides.
*/
float m_distance_from_contour_start;
/*!
* Gives the length of the edge on which the
* point lies. This value is the same for all
* points along a fixed edge.
*/
float m_edge_length;
/*!
* Gives the length of the contour open on which
* the point lies. This value is the same for all
* points along a fixed contour.
*/
float m_open_contour_length;
/*!
* Gives the length of the contour closed on which
* the point lies. This value is the same for all
* points along a fixed contour.
*/
float m_closed_contour_length;
/*!
* Bit field with data packed.
*/
uint32_t m_packed_data;
/*!
* Provides the point type from a value of \ref m_packed_data.
* The return value is one of the enumerations of
* \ref offset_type_t.
* \param packed_data_value value suitable for \ref m_packed_data
*/
static
enum offset_type_t
offset_type(uint32_t packed_data_value)
{
uint32_t v;
v = unpack_bits(offset_type_bit0, offset_type_num_bits, packed_data_value);
return static_cast<enum offset_type_t>(v);
}
/*!
* Provides the point type for the point. The return value
* is one of the enumerations of \ref offset_type_t.
*/
enum offset_type_t
offset_type(void) const
{
return offset_type(m_packed_data);
}
/*!
* If a point from an arc-segment, gives the radius
* of the arc, equivalent to \ref m_data[0].
*/
float
radius(void) const
{
return m_data[0];
}
/*!
* If a point from an arc-segment, gives the radius
* of the arc, equivalent to \ref m_data[0].
*/
float&
radius(void)
{
return m_data[0];
}
/*!
* If a point from an arc-segment, gives the angle
* of the arc, equivalent to \ref m_data[1].
*/
float
arc_angle(void) const
{
return m_data[1];
}
/*!
* If a point from an arc-segment, gives the angle
* of the arc, equivalent to \ref m_data[1].
*/
float&
arc_angle(void)
{
return m_data[1];
}
/*!
* When stroking the data, the depth test to only
* pass when the depth value is -strictly- larger
* so that a fixed pixel is not stroked twice by
* a single path. The value returned by depth() is
* a relative z-value for a vertex. The points
* drawn first have the largest z-values.
*/
uint32_t
depth(void) const
{
return unpack_bits(depth_bit0, depth_num_bits, m_packed_data);
}
/*!
* Set the value returned by depth().
*/
void
depth(const uint32_t v)
{
m_packed_data &= ~depth_mask;
m_packed_data |= pack_bits(depth_bit0, depth_num_bits, v);
}
/*!
* Pack the data of this \ref ArcStrokedPoint into a \ref
* PainterAttribute. The packing is as follows:
* - PainterAttribute::m_attrib0 .xy -> \ref m_position (float)
* - PainterAttribute::m_attrib0 .zw -> \ref m_offset_direction (float)
* - PainterAttribute::m_attrib1 .x -> \ref m_distance_from_edge_start (float)
* - PainterAttribute::m_attrib1 .y -> \ref m_distance_from_contour_start (float)
* - PainterAttribute::m_attrib1 .zw -> \ref m_data (float)
* - PainterAttribute::m_attrib2 .x -> \ref m_packed_data (uint)
* - PainterAttribute::m_attrib2 .y -> \ref m_edge_length (float)
* - PainterAttribute::m_attrib2 .z -> \ref m_open_contour_length (float)
* - PainterAttribute::m_attrib2 .w -> \ref m_closed_contour_length (float)
*
* \param dst PainterAttribute to which to pack
*/
void
pack_point(PainterAttribute *dst) const;
/*!
* Unpack an \ref ArcStrokedPoint from a \ref PainterAttribute.
* \param dst point to which to unpack data
* \param src PainterAttribute from which to unpack data
*/
static
void
unpack_point(ArcStrokedPoint *dst, const PainterAttribute &src);
};
/*! @} */
}
<|endoftext|> |
<commit_before>#ifndef ARABICA_XSLT_EXECUTION_CONTEXT_HPP
#define ARABICA_XSLT_EXECUTION_CONTEXT_HPP
#include <ostream>
#include "xslt_sink.hpp"
#include "xslt_variable_stack.hpp"
namespace Arabica
{
namespace XSLT
{
template<class string_type, class string_adaptor> class CompiledStylesheet;
template<class string_type, class string_adaptor> class ExecutionContext;
template<class string_type, class string_adaptor>
class Variable_declaration
{
protected:
Variable_declaration() { }
public:
virtual const string_type& name() const = 0;
virtual Arabica::XPath::XPathValue<string_type> value(const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context,
DOMSink<string_type, string_adaptor>& sink) const = 0;
virtual const Precedence& precedence() const = 0;
private:
Variable_declaration(const Variable_declaration&);
Variable_declaration& operator=(const Variable_declaration&);
bool operator==(const Variable_declaration&) const;
}; // class Variable_declaration
template<class string_type, class string_adaptor>
class ExecutionContext
{
public:
ExecutionContext(const CompiledStylesheet<string_type, string_adaptor>& stylesheet,
Sink<string_type, string_adaptor>& output,
std::ostream& error_output) :
stylesheet_(stylesheet),
sink_(output.asOutput()),
message_sink_(error_output),
to_msg_(0)
{
xpathContext_.setVariableResolver(stack_);
sink_.set_warning_sink(message_sink_.asOutput());
message_sink_.asOutput().set_warning_sink(message_sink_.asOutput());
} // ExecutionContext
ExecutionContext(Sink<string_type, string_adaptor>& output,
ExecutionContext<string_type, string_adaptor>& rhs) :
stylesheet_(rhs.stylesheet_),
stack_(rhs.stack_),
sink_(output.asOutput()),
message_sink_(rhs.message_sink_),
to_msg_(false)
{
xpathContext_.setVariableResolver(stack_);
xpathContext_.setCurrentNode(rhs.xpathContext().currentNode());
xpathContext_.setPosition(rhs.xpathContext().position());
xpathContext_.setLast(rhs.xpathContext().last());
} // ExecutionContext
const CompiledStylesheet<string_type, string_adaptor>& stylesheet() const { return stylesheet_; }
Output<string_type, string_adaptor>& sink()
{
return !to_msg_ ? sink_ : message_sink_.asOutput();
} // sink
void redirectToMessageSink() { ++to_msg_; }
void revertFromMessageSink() { --to_msg_; }
const Arabica::XPath::ExecutionContext<string_type, string_adaptor>& xpathContext() const { return xpathContext_; }
void topLevelParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
string_type passParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
void unpassParam(const string_type& name);
void declareParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
void declareVariable(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& variable);
void freezeTopLevel();
void injectGlobalScope(const typename ScopeType<string_type, string_adaptor>::Scope& scope);
void setPosition(const DOM::Node<string_type, string_adaptor>& current, size_t pos) { setPosition(current, static_cast<int>(pos)); }
void setPosition(const DOM::Node<string_type, string_adaptor>& current, int pos)
{
xpathContext_.setCurrentNode(current);
xpathContext_.setPosition(pos);
} // setPosition
int setLast(int last)
{
int old = xpathContext_.last();
xpathContext_.setLast(last);
return old;
} // setLast
private:
void pushStackFrame() { stack_.pushScope(); }
void chainStackFrame() { stack_.chainScope(); }
void popStackFrame() { stack_.popScope(); }
private:
const CompiledStylesheet<string_type, string_adaptor>& stylesheet_;
VariableStack<string_type, string_adaptor> stack_;
Arabica::XPath::ExecutionContext<string_type, string_adaptor> xpathContext_;
Output<string_type, string_adaptor>& sink_;
StreamSink<string_type, string_adaptor> message_sink_;
int to_msg_;
template<class string_type, class string_adaptor> friend class StackFrame;
template<class string_type, class string_adaptor> friend class ChainStackFrame;
}; // class ExecutionContext
///////////////////////////
template<class string_type, class string_adaptor>
class VariableClosure : public Variable_instance<string_type, string_adaptor>
{
public:
typedef typename ScopeType<string_type, string_adaptor>::Variable_instance_ptr Variable_instance_ptr;
static Variable_instance_ptr create(const Variable_declaration<string_type, string_adaptor>& var,
const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context)
{
return Variable_instance_ptr(new VariableClosure(var, node, context));
} // create
virtual const string_type& name() const { return var_.name(); }
virtual const Precedence& precedence() const { return var_.precedence(); }
virtual Arabica::XPath::XPathValue<string_type, string_adaptor> value() const
{
if(!value_)
value_ = var_.value(node_, context_, sink_);
return value_;
} // value
virtual void injectGlobalScope(const Scope& scope) const
{
context_.injectGlobalScope(scope);
} // globalScope
private:
VariableClosure(const Variable_declaration<string_type, string_adaptor>& var,
const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context) :
var_(var),
sink_(),
node_(node),
context_(sink_, context)
{
} // VariableClosure
const Variable_declaration<string_type, string_adaptor>& var_;
mutable DOMSink<string_type, string_adaptor> sink_;
const DOM::Node<string_type, string_adaptor> node_;
mutable ExecutionContext<string_type, string_adaptor> context_;
mutable Arabica::XPath::XPathValue<string_type, string_adaptor> value_;
VariableClosure();
VariableClosure(const VariableClosure&);
VariableClosure& operator=(const VariableClosure&);
const VariableClosure& operator==(const VariableClosure&) const;
}; // class VariableClosure
///////////////////////////
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::topLevelParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
stack_.topLevelParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // topLevelParam
template<class string_type, class string_adaptor>
string_type ExecutionContext<string_type, string_adaptor>::passParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
return stack_.passParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // passParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::unpassParam(const string_type& name)
{
stack_.unpassParam(name);
} // unpassParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::declareParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
if(!stack_.findPassedParam(param.name()))
stack_.declareParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // declareParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::declareVariable(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& variable)
{
stack_.declareVariable(VariableClosure<string_type, string_adaptor>::create(variable, node, *this));
} // declareVariable
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::freezeTopLevel()
{
stack_.freezeTopLevel();
} // freezeTopLevel
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::injectGlobalScope(const typename ScopeType<string_type, string_adaptor>::Scope& scope)
{
stack_.injectGlobalScope(scope);
} // injectGlobalScope
///////////////////////////
template<class string_type, class string_adaptor>
class StackFrame
{
public:
StackFrame(ExecutionContext<string_type, string_adaptor>& context) : context_(context) { context_.pushStackFrame(); }
~StackFrame() { context_.popStackFrame(); }
private:
ExecutionContext<string_type, string_adaptor>& context_;
StackFrame(const StackFrame&);
StackFrame& operator=(const StackFrame&);
bool operator==(const StackFrame&) const;
}; // class StackFrame
template<class string_type, class string_adaptor>
class ChainStackFrame
{
public:
ChainStackFrame(ExecutionContext<string_type, string_adaptor>& context) : context_(context) { context_.chainStackFrame(); }
~ChainStackFrame() { context_.popStackFrame(); }
private:
ExecutionContext<string_type, string_adaptor>& context_;
ChainStackFrame(const ChainStackFrame&);
ChainStackFrame& operator=(const ChainStackFrame&);
bool operator==(const ChainStackFrame&) const;
}; // class ChainStackFrame
///////////////////////////
template<class string_type, class string_adaptor>
class LastFrame
{
public:
LastFrame(ExecutionContext<string_type, string_adaptor>& context, int last) : context_(context)
{
oldLast_ = context_.setLast(last);
} // LastFrame
LastFrame(ExecutionContext<string_type, string_adaptor>& context, size_t last) : context_(context)
{
oldLast_ = context_.setLast(static_cast<int>(last));
} // LastFrame
~LastFrame()
{
context_.setLast(oldLast_);
} // ~LastFrame
private:
ExecutionContext<string_type, string_adaptor>& context_;
int oldLast_;
LastFrame(const LastFrame&);
LastFrame& operator=(const LastFrame&);
bool operator==(const LastFrame&) const;
}; // class LastFrame
} // namespace XSLT
} // namespace Arabica
#endif // ARABICA_XSLT_EXECUTION_CONTEXT_HPP
<commit_msg>execution context<commit_after>#ifndef ARABICA_XSLT_EXECUTION_CONTEXT_HPP
#define ARABICA_XSLT_EXECUTION_CONTEXT_HPP
#include <ostream>
#include "xslt_sink.hpp"
#include "xslt_variable_stack.hpp"
namespace Arabica
{
namespace XSLT
{
template<class string_type, class string_adaptor> class CompiledStylesheet;
template<class string_type, class string_adaptor> class ExecutionContext;
template<class string_type, class string_adaptor> class StackFrame;
template<class string_type, class string_adaptor> class ChainStackFrame;
template<class string_type, class string_adaptor>
class Variable_declaration
{
protected:
Variable_declaration() { }
public:
virtual const string_type& name() const = 0;
virtual Arabica::XPath::XPathValue<string_type> value(const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context,
DOMSink<string_type, string_adaptor>& sink) const = 0;
virtual const Precedence& precedence() const = 0;
private:
Variable_declaration(const Variable_declaration&);
Variable_declaration& operator=(const Variable_declaration&);
bool operator==(const Variable_declaration&) const;
}; // class Variable_declaration
template<class string_type, class string_adaptor>
class ExecutionContext
{
public:
ExecutionContext(const CompiledStylesheet<string_type, string_adaptor>& stylesheet,
Sink<string_type, string_adaptor>& output,
std::ostream& error_output) :
stylesheet_(stylesheet),
sink_(output.asOutput()),
message_sink_(error_output),
to_msg_(0)
{
xpathContext_.setVariableResolver(stack_);
sink_.set_warning_sink(message_sink_.asOutput());
message_sink_.asOutput().set_warning_sink(message_sink_.asOutput());
} // ExecutionContext
ExecutionContext(Sink<string_type, string_adaptor>& output,
ExecutionContext<string_type, string_adaptor>& rhs) :
stylesheet_(rhs.stylesheet_),
stack_(rhs.stack_),
sink_(output.asOutput()),
message_sink_(rhs.message_sink_),
to_msg_(false)
{
xpathContext_.setVariableResolver(stack_);
xpathContext_.setCurrentNode(rhs.xpathContext().currentNode());
xpathContext_.setPosition(rhs.xpathContext().position());
xpathContext_.setLast(rhs.xpathContext().last());
} // ExecutionContext
const CompiledStylesheet<string_type, string_adaptor>& stylesheet() const { return stylesheet_; }
Output<string_type, string_adaptor>& sink()
{
return !to_msg_ ? sink_ : message_sink_.asOutput();
} // sink
void redirectToMessageSink() { ++to_msg_; }
void revertFromMessageSink() { --to_msg_; }
const Arabica::XPath::ExecutionContext<string_type, string_adaptor>& xpathContext() const { return xpathContext_; }
void topLevelParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
string_type passParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
void unpassParam(const string_type& name);
void declareParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param);
void declareVariable(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& variable);
void freezeTopLevel();
void injectGlobalScope(const typename ScopeType<string_type, string_adaptor>::Scope& scope);
void setPosition(const DOM::Node<string_type, string_adaptor>& current, size_t pos) { setPosition(current, static_cast<int>(pos)); }
void setPosition(const DOM::Node<string_type, string_adaptor>& current, int pos)
{
xpathContext_.setCurrentNode(current);
xpathContext_.setPosition(pos);
} // setPosition
int setLast(int last)
{
int old = xpathContext_.last();
xpathContext_.setLast(last);
return old;
} // setLast
private:
void pushStackFrame() { stack_.pushScope(); }
void chainStackFrame() { stack_.chainScope(); }
void popStackFrame() { stack_.popScope(); }
private:
const CompiledStylesheet<string_type, string_adaptor>& stylesheet_;
VariableStack<string_type, string_adaptor> stack_;
Arabica::XPath::ExecutionContext<string_type, string_adaptor> xpathContext_;
Output<string_type, string_adaptor>& sink_;
StreamSink<string_type, string_adaptor> message_sink_;
int to_msg_;
friend class StackFrame<string_type, string_adaptor> ;
friend class ChainStackFrame<string_type, string_adaptor> ;
}; // class ExecutionContext
///////////////////////////
template<class string_type, class string_adaptor>
class VariableClosure : public Variable_instance<string_type, string_adaptor>
{
public:
typedef typename ScopeType<string_type, string_adaptor>::Variable_instance_ptr Variable_instance_ptr;
static Variable_instance_ptr create(const Variable_declaration<string_type, string_adaptor>& var,
const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context)
{
return Variable_instance_ptr(new VariableClosure(var, node, context));
} // create
virtual const string_type& name() const { return var_.name(); }
virtual const Precedence& precedence() const { return var_.precedence(); }
virtual Arabica::XPath::XPathValue<string_type, string_adaptor> value() const
{
if(!value_)
value_ = var_.value(node_, context_, sink_);
return value_;
} // value
virtual void injectGlobalScope(const Scope& scope) const
{
context_.injectGlobalScope(scope);
} // globalScope
private:
VariableClosure(const Variable_declaration<string_type, string_adaptor>& var,
const DOM::Node<string_type, string_adaptor>& node,
ExecutionContext<string_type, string_adaptor>& context) :
var_(var),
sink_(),
node_(node),
context_(sink_, context)
{
} // VariableClosure
const Variable_declaration<string_type, string_adaptor>& var_;
mutable DOMSink<string_type, string_adaptor> sink_;
const DOM::Node<string_type, string_adaptor> node_;
mutable ExecutionContext<string_type, string_adaptor> context_;
mutable Arabica::XPath::XPathValue<string_type, string_adaptor> value_;
VariableClosure();
VariableClosure(const VariableClosure&);
VariableClosure& operator=(const VariableClosure&);
const VariableClosure& operator==(const VariableClosure&) const;
}; // class VariableClosure
///////////////////////////
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::topLevelParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
stack_.topLevelParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // topLevelParam
template<class string_type, class string_adaptor>
string_type ExecutionContext<string_type, string_adaptor>::passParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
return stack_.passParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // passParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::unpassParam(const string_type& name)
{
stack_.unpassParam(name);
} // unpassParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::declareParam(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& param)
{
if(!stack_.findPassedParam(param.name()))
stack_.declareParam(VariableClosure<string_type, string_adaptor>::create(param, node, *this));
} // declareParam
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::declareVariable(const DOM::Node<string_type, string_adaptor>& node, const Variable_declaration<string_type, string_adaptor>& variable)
{
stack_.declareVariable(VariableClosure<string_type, string_adaptor>::create(variable, node, *this));
} // declareVariable
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::freezeTopLevel()
{
stack_.freezeTopLevel();
} // freezeTopLevel
template<class string_type, class string_adaptor>
void ExecutionContext<string_type, string_adaptor>::injectGlobalScope(const typename ScopeType<string_type, string_adaptor>::Scope& scope)
{
stack_.injectGlobalScope(scope);
} // injectGlobalScope
///////////////////////////
template<class string_type, class string_adaptor>
class StackFrame
{
public:
StackFrame(ExecutionContext<string_type, string_adaptor>& context) : context_(context) { context_.pushStackFrame(); }
~StackFrame() { context_.popStackFrame(); }
private:
ExecutionContext<string_type, string_adaptor>& context_;
StackFrame(const StackFrame&);
StackFrame& operator=(const StackFrame&);
bool operator==(const StackFrame&) const;
}; // class StackFrame
template<class string_type, class string_adaptor>
class ChainStackFrame
{
public:
ChainStackFrame(ExecutionContext<string_type, string_adaptor>& context) : context_(context) { context_.chainStackFrame(); }
~ChainStackFrame() { context_.popStackFrame(); }
private:
ExecutionContext<string_type, string_adaptor>& context_;
ChainStackFrame(const ChainStackFrame&);
ChainStackFrame& operator=(const ChainStackFrame&);
bool operator==(const ChainStackFrame&) const;
}; // class ChainStackFrame
///////////////////////////
template<class string_type, class string_adaptor>
class LastFrame
{
public:
LastFrame(ExecutionContext<string_type, string_adaptor>& context, int last) : context_(context)
{
oldLast_ = context_.setLast(last);
} // LastFrame
LastFrame(ExecutionContext<string_type, string_adaptor>& context, size_t last) : context_(context)
{
oldLast_ = context_.setLast(static_cast<int>(last));
} // LastFrame
~LastFrame()
{
context_.setLast(oldLast_);
} // ~LastFrame
private:
ExecutionContext<string_type, string_adaptor>& context_;
int oldLast_;
LastFrame(const LastFrame&);
LastFrame& operator=(const LastFrame&);
bool operator==(const LastFrame&) const;
}; // class LastFrame
} // namespace XSLT
} // namespace Arabica
#endif // ARABICA_XSLT_EXECUTION_CONTEXT_HPP
<|endoftext|> |
<commit_before>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include "hadesmem/config.hpp"
namespace hadesmem
{
namespace detail
{
#ifndef HADESMEM_NO_VARIADIC_TEMPLATES
template <typename FuncT>
struct FuncArgs
{ };
template <typename R, typename... Args>
struct FuncArgs<R (*)(Args...)>
{
typedef std::tuple<Args...> type;
};
#else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES
template <typename FuncT>
struct FuncArgs
{ };
template <typename R>
struct FuncArgs<R (*)()>
{ };
template <typename R, typename A0>
struct FuncArgs<R (*)(A0)>
{
typedef std::tuple<A0> type;
};
template <typename R, typename A0, typename A1>
struct FuncArgs<R (*)(A0, A1)>
{
typedef std::tuple<A0, A1> type;
};
template <typename R, typename A0, typename A1, typename A2>
struct FuncArgs<R (*)(A0, A1, A2)>
{
typedef std::tuple<A0, A1, A2> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3>
struct FuncArgs<R (*)(A0, A1, A2, A3)>
{
typedef std::tuple<A0, A1, A2, A3> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4)>
{
typedef std::tuple<A0, A1, A2, A3, A4> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7, typename A8>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7, A8)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7, typename A8, typename A9>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8, A9> type;
};
#endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES
}
}
<commit_msg>* Add missing header.<commit_after>// Copyright (C) 2010-2012 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <utility>
#include "hadesmem/config.hpp"
namespace hadesmem
{
namespace detail
{
#ifndef HADESMEM_NO_VARIADIC_TEMPLATES
template <typename FuncT>
struct FuncArgs
{ };
template <typename R, typename... Args>
struct FuncArgs<R (*)(Args...)>
{
typedef std::tuple<Args...> type;
};
#else // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES
template <typename FuncT>
struct FuncArgs
{ };
template <typename R>
struct FuncArgs<R (*)()>
{ };
template <typename R, typename A0>
struct FuncArgs<R (*)(A0)>
{
typedef std::tuple<A0> type;
};
template <typename R, typename A0, typename A1>
struct FuncArgs<R (*)(A0, A1)>
{
typedef std::tuple<A0, A1> type;
};
template <typename R, typename A0, typename A1, typename A2>
struct FuncArgs<R (*)(A0, A1, A2)>
{
typedef std::tuple<A0, A1, A2> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3>
struct FuncArgs<R (*)(A0, A1, A2, A3)>
{
typedef std::tuple<A0, A1, A2, A3> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4)>
{
typedef std::tuple<A0, A1, A2, A3, A4> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7, typename A8>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7, A8)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8> type;
};
template <typename R, typename A0, typename A1, typename A2, typename A3,
typename A4, typename A5, typename A6, typename A7, typename A8, typename A9>
struct FuncArgs<R (*)(A0, A1, A2, A3, A4, A5, A6, A7, A8, A9)>
{
typedef std::tuple<A0, A1, A2, A3, A4, A5, A6, A7, A8, A9> type;
};
#endif // #ifndef HADESMEM_NO_VARIADIC_TEMPLATES
}
}
<|endoftext|> |
<commit_before>// The Art of C++ / PostgreSQL
// Copyright (c) 2016-2018 Daniel Frey
#ifndef TAO_POSTGRES_RESULT_TRAITS_TUPLE_HPP
#define TAO_POSTGRES_RESULT_TRAITS_TUPLE_HPP
#include <tao/postgres/result_traits.hpp>
#include <tao/postgres/row.hpp>
#include <tuple>
#include <type_traits>
#include <utility>
namespace tao
{
namespace postgres
{
namespace impl
{
template< typename, std::size_t... >
struct exclusive_scan;
template< std::size_t... Is, std::size_t... Ns >
struct exclusive_scan< std::index_sequence< Is... >, Ns... >
{
template< std::size_t I >
static constexpr std::size_t partial_sum = ( ( ( Is < I ) ? Ns : 0 ) + ... );
using type = std::index_sequence< partial_sum< Is >... >;
};
template< std::size_t... Ns >
using exclusive_scan_t = typename exclusive_scan< std::make_index_sequence< sizeof...( Ns ) >, Ns... >::type;
} // namespace impl
template< typename... Ts >
struct result_traits< std::tuple< Ts... >, std::enable_if_t< sizeof...( Ts ) == 1 > >
{
using T = std::tuple_element_t< 0, std::tuple< Ts... > >;
static constexpr std::size_t size = result_traits_size< T >;
static std::enable_if_t< result_traits_has_null< T >, std::tuple< T > > null()
{
return std::tuple< T >( result_traits< T >::null() );
}
static std::tuple< T > from( const char* value )
{
return std::tuple< T >( result_traits< T >::from( value ) );
}
};
template< typename... Ts >
struct result_traits< std::tuple< Ts... >, std::enable_if_t< ( sizeof...( Ts ) > 1 ) > >
{
static constexpr std::size_t size = ( result_traits_size< Ts > + ... );
template< std::size_t... Ns >
static std::tuple< Ts... > from( const row& row, const std::index_sequence< Ns... >& )
{
return std::tuple< Ts... >( row.get< Ts >( Ns )... );
}
static std::tuple< Ts... > from( const row& row )
{
return from( row, impl::exclusive_scan_t< result_traits_size< Ts >... >() );
}
};
} // namespace postgres
} // namespace tao
#endif
<commit_msg>Try fix MSVC<commit_after>// The Art of C++ / PostgreSQL
// Copyright (c) 2016-2018 Daniel Frey
#ifndef TAO_POSTGRES_RESULT_TRAITS_TUPLE_HPP
#define TAO_POSTGRES_RESULT_TRAITS_TUPLE_HPP
#include <tao/postgres/result_traits.hpp>
#include <tao/postgres/row.hpp>
#include <tuple>
#include <type_traits>
#include <utility>
namespace tao
{
namespace postgres
{
namespace impl
{
template< typename, std::size_t... >
struct exclusive_scan;
template< std::size_t... Is, std::size_t... Ns >
struct exclusive_scan< std::index_sequence< Is... >, Ns... >
{
template< std::size_t I >
static constexpr std::size_t partial_sum = ( ( ( Is < I ) ? Ns : 0 ) + ... );
using type = std::index_sequence< partial_sum< Is >... >;
};
template< std::size_t... Ns >
using exclusive_scan_t = typename exclusive_scan< std::make_index_sequence< sizeof...( Ns ) >, Ns... >::type;
} // namespace impl
template< typename... Ts >
struct result_traits< std::tuple< Ts... >, std::enable_if_t< sizeof...( Ts ) == 1 > >
{
using T = std::tuple_element_t< 0, std::tuple< Ts... > >;
static constexpr std::size_t size = result_traits_size< T >;
static std::enable_if_t< result_traits_has_null< T >, std::tuple< T > > null()
{
return std::tuple< T >( result_traits< T >::null() );
}
static std::tuple< T > from( const char* value )
{
return std::tuple< T >( result_traits< T >::from( value ) );
}
};
template< typename... Ts >
struct result_traits< std::tuple< Ts... >, std::enable_if_t< ( sizeof...( Ts ) > 1 ) > >
{
static constexpr std::size_t size{ ( result_traits_size< Ts > + ... ) };
template< std::size_t... Ns >
static std::tuple< Ts... > from( const row& row, const std::index_sequence< Ns... >& )
{
return std::tuple< Ts... >( row.get< Ts >( Ns )... );
}
static std::tuple< Ts... > from( const row& row )
{
return from( row, impl::exclusive_scan_t< result_traits_size< Ts >... >() );
}
};
} // namespace postgres
} // namespace tao
#endif
<|endoftext|> |
<commit_before>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
---
Copyright (C) 2004, Anders Lund <[email protected]>
*/
#include "katemwmodonhddialog.h"
#include "katemwmodonhddialog.moc"
#include "katedocmanager.h"
#include <KTextEditor/Document>
#include <KIconLoader>
#include <KLocale>
#include <KMessageBox>
#include <KProcIO>
#include <KRun>
#include <KTemporaryFile>
#include <KPushButton>
#include <KVBox>
#include <QLabel>
#include <QLayout>
#include <QPushButton>
#include <QTextStream>
class KateDocItem : public QTreeWidgetItem
{
public:
KateDocItem( KTextEditor::Document *doc, const QString &status, QTreeWidget *tw )
: QTreeWidgetItem( tw ),
document( doc )
{
setText( 0, doc->url().prettyUrl() );
setText( 1, status );
if ( ! doc->isModified() )
setCheckState( 0, Qt::Checked );
else
setCheckState( 0, Qt::Unchecked );
}
~KateDocItem()
{};
KTextEditor::Document *document;
};
KateMwModOnHdDialog::KateMwModOnHdDialog( DocVector docs, QWidget *parent, const char *name )
: KDialog( parent )
{
setCaption( i18n("Documents Modified on Disk") );
setButtons( User1 | User2 | User3 );
setButtonGuiItem( User1, KGuiItem (i18n("&Ignore"), "window-close") );
setButtonGuiItem( User2, KStandardGuiItem::overwrite() );
setButtonGuiItem( User3, KGuiItem (i18n("&Reload"), "view-refresh") );
setObjectName( name );
setModal( true );
setDefaultButton( KDialog::User3 );
setButtonWhatsThis( User1, i18n(
"Removes the modified flag from the selected documents and closes the "
"dialog if there are no more unhandled documents.") );
setButtonWhatsThis( User2, i18n(
"Overwrite selected documents, discarding the disk changes and closes the "
"dialog if there are no more unhandled documents.") );
setButtonWhatsThis( User3, i18n(
"Reloads the selected documents from disk and closes the dialog if there "
"are no more unhandled documents.") );
KVBox *w = new KVBox( this );
setMainWidget( w );
w->setSpacing( KDialog::spacingHint() );
KHBox *lo1 = new KHBox( w );
// dialog text
QLabel *icon = new QLabel( lo1 );
icon->setPixmap( DesktopIcon("dialog-warning") );
QLabel *t = new QLabel( i18n(
"<qt>The documents listed below has changed on disk.<p>Select one "
"or more at the time and press an action button until the list is empty.</qt>"), lo1 );
lo1->setStretchFactor( t, 1000 );
// document list
twDocuments = new QTreeWidget( w );
QStringList header;
header << i18n("Filename") << i18n("Status on Disk");
twDocuments->setHeaderLabels(header);
twDocuments->setSelectionMode( QAbstractItemView::SingleSelection );
QStringList l;
l << "" << i18n("Modified") << i18n("Created") << i18n("Deleted");
for ( uint i = 0; i < docs.size(); i++ )
{
new KateDocItem( docs[i], l[ (uint)KateDocManager::self()->documentInfo( docs[i] )->modifiedOnDiscReason ], twDocuments );
}
connect( twDocuments, SIGNAL(currentItemChanged(QTreeWidget *, QTreeWidget *)), this, SLOT(slotSelectionChanged(QTreeWidget *, QTreeWidget *)) );
// diff button
KHBox *lo2 = new KHBox ( w );
QWidget *d = new QWidget (lo2);
lo2->setStretchFactor (d, 2);
btnDiff = new KPushButton( KGuiItem (i18n("&View Difference"), "edit"), lo2 );
btnDiff->setWhatsThis(i18n(
"Calculates the difference between the the editor contents and the disk "
"file for the selected document, and shows the difference with the "
"default application. Requires diff(1).") );
connect( btnDiff, SIGNAL(clicked()), this, SLOT(slotDiff()) );
connect( this, SIGNAL(user1Clicked()), this, SLOT(slotUser1()) );
connect( this, SIGNAL(user2Clicked()), this, SLOT(slotUser2()) );
connect( this, SIGNAL(user3Clicked()), this, SLOT(slotUser3()) );
slotSelectionChanged(NULL, NULL);
m_tmpfile = 0;
}
KateMwModOnHdDialog::~KateMwModOnHdDialog()
{}
void KateMwModOnHdDialog::slotUser1()
{
handleSelected( Ignore );
}
void KateMwModOnHdDialog::slotUser2()
{
handleSelected( Overwrite );
}
void KateMwModOnHdDialog::slotUser3()
{
handleSelected( Reload );
}
void KateMwModOnHdDialog::handleSelected( int action )
{
// collect all items we can remove
QList<QTreeWidgetItem *> itemsToDelete;
for ( QTreeWidgetItemIterator it ( twDocuments ); *it; ++it )
{
KateDocItem *item = (KateDocItem *) * it;
if ( item->checkState(0) == Qt::Checked )
{
KTextEditor::ModificationInterface::ModifiedOnDiskReason reason = KateDocManager::self()->documentInfo( item->document )->modifiedOnDiscReason;
bool success = true;
if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document))
iface->setModifiedOnDisk( KTextEditor::ModificationInterface::OnDiskUnmodified );
switch ( action )
{
case Overwrite:
success = item->document->save();
if ( ! success )
{
KMessageBox::sorry( this,
i18n("Could not save the document \n'%1'",
item->document->url().prettyUrl() ) );
}
break;
case Reload:
item->document->documentReload();
break;
default:
break;
}
if ( success )
itemsToDelete.append( item );
else
{
if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document))
iface->setModifiedOnDisk( reason );
}
}
}
// remove the marked items
for (int i = 0; i < itemsToDelete.count(); ++i)
delete itemsToDelete[i];
// any documents left unhandled?
if ( ! twDocuments->topLevelItemCount() )
done( Ok );
}
void KateMwModOnHdDialog::slotSelectionChanged(QTreeWidget *current, QTreeWidget *)
{
// set the diff button enabled
btnDiff->setEnabled( current &&
KateDocManager::self()->documentInfo( ((KateDocItem*)current)->document )->modifiedOnDiscReason != 3 );
}
// ### the code below is slightly modified from kdelibs/kate/part/katedialogs,
// class KateModOnHdPrompt.
void KateMwModOnHdDialog::slotDiff()
{
if ( m_tmpfile ) // we are already somewhere in this process.
return;
if ( ! twDocuments->currentItem() )
return;
KTextEditor::Document *doc = ((KateDocItem*)twDocuments->currentItem())->document;
// don't try o diff a deleted file
if ( KateDocManager::self()->documentInfo( doc )->modifiedOnDiscReason == 3 )
return;
// Start a KProcess that creates a diff
KProcIO *p = new KProcIO();
p->setComm( KProcess::All );
*p << "diff" << "-ub" << "-" << doc->url().path();
connect( p, SIGNAL(processExited(KProcess*)), this, SLOT(slotPDone(KProcess*)) );
connect( p, SIGNAL(readReady(KProcIO*)), this, SLOT(slotPRead(KProcIO*)) );
setCursor( Qt::WaitCursor );
p->start( KProcess::NotifyOnExit, true );
uint lastln = doc->lines();
for ( uint l = 0; l < lastln; l++ )
p->writeStdin( doc->line( l ), l < lastln );
p->closeWhenDone();
}
void KateMwModOnHdDialog::slotPRead( KProcIO *p)
{
// create a file for the diff if we haven't one already
if ( ! m_tmpfile )
{
m_tmpfile = new KTemporaryFile();
m_tmpfile->setAutoRemove(false);
m_tmpfile->open();
}
// put all the data we have in it
QString stmp;
bool readData = false;
QTextStream textStream ( m_tmpfile );
while ( p->readln( stmp, false ) > -1 )
{
textStream << stmp << endl;
readData = true;
}
textStream.flush();
// dominik: only ackRead(), when we *really* read data, otherwise, this slot
// is called infinity times, which leads to a crash (#123887)
if (readData)
p->ackRead();
}
void KateMwModOnHdDialog::slotPDone( KProcess *p )
{
setCursor( Qt::ArrowCursor );
// dominik: whitespace changes lead to diff with 0 bytes, so that slotPRead is
// never called. Thus, m_tmpfile can be NULL
if( m_tmpfile )
m_tmpfile->close();
if ( ! p->normalExit() /*|| p->exitStatus()*/ )
{
KMessageBox::sorry( this,
i18n("The diff command failed. Please make sure that "
"diff(1) is installed and in your PATH."),
i18n("Error Creating Diff") );
delete m_tmpfile;
m_tmpfile = 0;
return;
}
if ( ! m_tmpfile )
{
KMessageBox::information( this,
i18n("Besides white space changes, the files are identical."),
i18n("Diff Output") );
return;
}
KRun::runUrl( m_tmpfile->fileName(), "text/x-diff", this, true );
delete m_tmpfile;
m_tmpfile = 0;
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<commit_msg>Use standard mimetype names. KBabel, if it is to stay, probably needs some fixes to be able to open .pot files (text/x-gettext-translation-template) in addition to .po files (text/x-gettext-translation).<commit_after>/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License version 2 as published by the Free Software Foundation.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
Boston, MA 02110-1301, USA.
---
Copyright (C) 2004, Anders Lund <[email protected]>
*/
#include "katemwmodonhddialog.h"
#include "katemwmodonhddialog.moc"
#include "katedocmanager.h"
#include <KTextEditor/Document>
#include <KIconLoader>
#include <KLocale>
#include <KMessageBox>
#include <KProcIO>
#include <KRun>
#include <KTemporaryFile>
#include <KPushButton>
#include <KVBox>
#include <QLabel>
#include <QLayout>
#include <QPushButton>
#include <QTextStream>
class KateDocItem : public QTreeWidgetItem
{
public:
KateDocItem( KTextEditor::Document *doc, const QString &status, QTreeWidget *tw )
: QTreeWidgetItem( tw ),
document( doc )
{
setText( 0, doc->url().prettyUrl() );
setText( 1, status );
if ( ! doc->isModified() )
setCheckState( 0, Qt::Checked );
else
setCheckState( 0, Qt::Unchecked );
}
~KateDocItem()
{};
KTextEditor::Document *document;
};
KateMwModOnHdDialog::KateMwModOnHdDialog( DocVector docs, QWidget *parent, const char *name )
: KDialog( parent )
{
setCaption( i18n("Documents Modified on Disk") );
setButtons( User1 | User2 | User3 );
setButtonGuiItem( User1, KGuiItem (i18n("&Ignore"), "window-close") );
setButtonGuiItem( User2, KStandardGuiItem::overwrite() );
setButtonGuiItem( User3, KGuiItem (i18n("&Reload"), "view-refresh") );
setObjectName( name );
setModal( true );
setDefaultButton( KDialog::User3 );
setButtonWhatsThis( User1, i18n(
"Removes the modified flag from the selected documents and closes the "
"dialog if there are no more unhandled documents.") );
setButtonWhatsThis( User2, i18n(
"Overwrite selected documents, discarding the disk changes and closes the "
"dialog if there are no more unhandled documents.") );
setButtonWhatsThis( User3, i18n(
"Reloads the selected documents from disk and closes the dialog if there "
"are no more unhandled documents.") );
KVBox *w = new KVBox( this );
setMainWidget( w );
w->setSpacing( KDialog::spacingHint() );
KHBox *lo1 = new KHBox( w );
// dialog text
QLabel *icon = new QLabel( lo1 );
icon->setPixmap( DesktopIcon("dialog-warning") );
QLabel *t = new QLabel( i18n(
"<qt>The documents listed below has changed on disk.<p>Select one "
"or more at the time and press an action button until the list is empty.</qt>"), lo1 );
lo1->setStretchFactor( t, 1000 );
// document list
twDocuments = new QTreeWidget( w );
QStringList header;
header << i18n("Filename") << i18n("Status on Disk");
twDocuments->setHeaderLabels(header);
twDocuments->setSelectionMode( QAbstractItemView::SingleSelection );
QStringList l;
l << "" << i18n("Modified") << i18n("Created") << i18n("Deleted");
for ( uint i = 0; i < docs.size(); i++ )
{
new KateDocItem( docs[i], l[ (uint)KateDocManager::self()->documentInfo( docs[i] )->modifiedOnDiscReason ], twDocuments );
}
connect( twDocuments, SIGNAL(currentItemChanged(QTreeWidget *, QTreeWidget *)), this, SLOT(slotSelectionChanged(QTreeWidget *, QTreeWidget *)) );
// diff button
KHBox *lo2 = new KHBox ( w );
QWidget *d = new QWidget (lo2);
lo2->setStretchFactor (d, 2);
btnDiff = new KPushButton( KGuiItem (i18n("&View Difference"), "edit"), lo2 );
btnDiff->setWhatsThis(i18n(
"Calculates the difference between the the editor contents and the disk "
"file for the selected document, and shows the difference with the "
"default application. Requires diff(1).") );
connect( btnDiff, SIGNAL(clicked()), this, SLOT(slotDiff()) );
connect( this, SIGNAL(user1Clicked()), this, SLOT(slotUser1()) );
connect( this, SIGNAL(user2Clicked()), this, SLOT(slotUser2()) );
connect( this, SIGNAL(user3Clicked()), this, SLOT(slotUser3()) );
slotSelectionChanged(NULL, NULL);
m_tmpfile = 0;
}
KateMwModOnHdDialog::~KateMwModOnHdDialog()
{}
void KateMwModOnHdDialog::slotUser1()
{
handleSelected( Ignore );
}
void KateMwModOnHdDialog::slotUser2()
{
handleSelected( Overwrite );
}
void KateMwModOnHdDialog::slotUser3()
{
handleSelected( Reload );
}
void KateMwModOnHdDialog::handleSelected( int action )
{
// collect all items we can remove
QList<QTreeWidgetItem *> itemsToDelete;
for ( QTreeWidgetItemIterator it ( twDocuments ); *it; ++it )
{
KateDocItem *item = (KateDocItem *) * it;
if ( item->checkState(0) == Qt::Checked )
{
KTextEditor::ModificationInterface::ModifiedOnDiskReason reason = KateDocManager::self()->documentInfo( item->document )->modifiedOnDiscReason;
bool success = true;
if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document))
iface->setModifiedOnDisk( KTextEditor::ModificationInterface::OnDiskUnmodified );
switch ( action )
{
case Overwrite:
success = item->document->save();
if ( ! success )
{
KMessageBox::sorry( this,
i18n("Could not save the document \n'%1'",
item->document->url().prettyUrl() ) );
}
break;
case Reload:
item->document->documentReload();
break;
default:
break;
}
if ( success )
itemsToDelete.append( item );
else
{
if (KTextEditor::ModificationInterface *iface = qobject_cast<KTextEditor::ModificationInterface *>(item->document))
iface->setModifiedOnDisk( reason );
}
}
}
// remove the marked items
for (int i = 0; i < itemsToDelete.count(); ++i)
delete itemsToDelete[i];
// any documents left unhandled?
if ( ! twDocuments->topLevelItemCount() )
done( Ok );
}
void KateMwModOnHdDialog::slotSelectionChanged(QTreeWidget *current, QTreeWidget *)
{
// set the diff button enabled
btnDiff->setEnabled( current &&
KateDocManager::self()->documentInfo( ((KateDocItem*)current)->document )->modifiedOnDiscReason != 3 );
}
// ### the code below is slightly modified from kdelibs/kate/part/katedialogs,
// class KateModOnHdPrompt.
void KateMwModOnHdDialog::slotDiff()
{
if ( m_tmpfile ) // we are already somewhere in this process.
return;
if ( ! twDocuments->currentItem() )
return;
KTextEditor::Document *doc = ((KateDocItem*)twDocuments->currentItem())->document;
// don't try o diff a deleted file
if ( KateDocManager::self()->documentInfo( doc )->modifiedOnDiscReason == 3 )
return;
// Start a KProcess that creates a diff
KProcIO *p = new KProcIO();
p->setComm( KProcess::All );
*p << "diff" << "-ub" << "-" << doc->url().path();
connect( p, SIGNAL(processExited(KProcess*)), this, SLOT(slotPDone(KProcess*)) );
connect( p, SIGNAL(readReady(KProcIO*)), this, SLOT(slotPRead(KProcIO*)) );
setCursor( Qt::WaitCursor );
p->start( KProcess::NotifyOnExit, true );
uint lastln = doc->lines();
for ( uint l = 0; l < lastln; l++ )
p->writeStdin( doc->line( l ), l < lastln );
p->closeWhenDone();
}
void KateMwModOnHdDialog::slotPRead( KProcIO *p)
{
// create a file for the diff if we haven't one already
if ( ! m_tmpfile )
{
m_tmpfile = new KTemporaryFile();
m_tmpfile->setAutoRemove(false);
m_tmpfile->open();
}
// put all the data we have in it
QString stmp;
bool readData = false;
QTextStream textStream ( m_tmpfile );
while ( p->readln( stmp, false ) > -1 )
{
textStream << stmp << endl;
readData = true;
}
textStream.flush();
// dominik: only ackRead(), when we *really* read data, otherwise, this slot
// is called infinity times, which leads to a crash (#123887)
if (readData)
p->ackRead();
}
void KateMwModOnHdDialog::slotPDone( KProcess *p )
{
setCursor( Qt::ArrowCursor );
// dominik: whitespace changes lead to diff with 0 bytes, so that slotPRead is
// never called. Thus, m_tmpfile can be NULL
if( m_tmpfile )
m_tmpfile->close();
if ( ! p->normalExit() /*|| p->exitStatus()*/ )
{
KMessageBox::sorry( this,
i18n("The diff command failed. Please make sure that "
"diff(1) is installed and in your PATH."),
i18n("Error Creating Diff") );
delete m_tmpfile;
m_tmpfile = 0;
return;
}
if ( ! m_tmpfile )
{
KMessageBox::information( this,
i18n("Besides white space changes, the files are identical."),
i18n("Diff Output") );
return;
}
KRun::runUrl( m_tmpfile->fileName(), "text/x-patch", this, true );
delete m_tmpfile;
m_tmpfile = 0;
}
// kate: space-indent on; indent-width 2; replace-tabs on;
<|endoftext|> |
<commit_before>#include <Halide.h>
#include <tiramisu/tiramisu.h>
#include <iostream>
#include "generated_copy.o.h"
#include "benchmarks.h"
#include <tiramisu/utils.h>
int copy_ref(int n,
Halide::Buffer<float> a,
Halide::Buffer<float> x)
{
for (int i = 0; i < n; ++i)
a(i) = x(i);
return 0;
}
int main(int argc, char** argv)
{
std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;
bool run_ref = false, run_tiramisu = false;
const char* env_ref = std::getenv("RUN_REF");
if (env_ref != NULL && env_ref[0] == '1')
run_ref = true;
const char* env_tiramisu = std::getenv("RUN_TIRAMISU");
if (env_tiramisu != NULL && env_tiramisu[0] == '1')
run_tiramisu = true;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
Halide::Buffer<float> b_x(N), b_a(N), b_a_ref(N);
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
//REFERENCE
{
for (int i = 0; i < NB_TESTS; ++i)
{
init_buffer(b_x, (float) i);
auto start = std::chrono::high_resolution_clock::now();
if (run_ref)
copy_ref(N, b_a_ref, b_x );
auto end = std::chrono::high_resolution_clock::now();
duration_vector_1.push_back(end - start);
}
}
//TIRAMISU
{
for (int i = 0; i < NB_TESTS; ++i)
{
init_buffer(b_x, (float) i);
auto start = std::chrono::high_resolution_clock::now();
if (run_tiramisu)
copy(b_a.raw_buffer(), b_x.raw_buffer());
auto end = std::chrono::high_resolution_clock::now();
duration_vector_2.push_back(end - start);
}
}
print_time("performance_cpu.csv", "copy",
{"Ref", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS && run_ref && run_tiramisu)
compare_buffers("copy", b_a_ref, b_a);
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu " << std::endl;
print_buffer(b_a);
std::cout << "Reference " << std::endl;
print_buffer(b_a_ref);
}
return 0;
}
<commit_msg>Update copy_wrapper.cpp<commit_after>#include <Halide.h>
#include <tiramisu/tiramisu.h>
#include <iostream>
#include "generated_copy.o.h"
#include "benchmarks.h"
#include <tiramisu/utils.h>
int copy_ref(int n, Halide::Buffer<float> a, Halide::Buffer<float> x)
{
for (int i = 0; i < n; ++i)
a(i) = x(i);
return 0;
}
int main(int argc, char** argv)
{
std::vector<std::chrono::duration<double, std::milli>> duration_vector_1, duration_vector_2;
bool run_ref = false, run_tiramisu = false;
const char* env_ref = std::getenv("RUN_REF");
if (env_ref != NULL && env_ref[0] == '1')
run_ref = true;
const char* env_tiramisu = std::getenv("RUN_TIRAMISU");
if (env_tiramisu != NULL && env_tiramisu[0] == '1')
run_tiramisu = true;
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
Halide::Buffer<float> b_x(N), b_a(N), b_a_ref(N);
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
// ---------------------------------------------------------------------
//REFERENCE
{
for (int i = 0; i < NB_TESTS; ++i)
{
init_buffer(b_x, (float) i);
auto start = std::chrono::high_resolution_clock::now();
if (run_ref)
copy_ref(N, b_a_ref, b_x );
auto end = std::chrono::high_resolution_clock::now();
duration_vector_1.push_back(end - start);
}
}
//TIRAMISU
{
for (int i = 0; i < NB_TESTS; ++i)
{
init_buffer(b_x, (float) i);
auto start = std::chrono::high_resolution_clock::now();
if (run_tiramisu)
copy(b_a.raw_buffer(), b_x.raw_buffer());
auto end = std::chrono::high_resolution_clock::now();
duration_vector_2.push_back(end - start);
}
}
print_time("performance_cpu.csv", "copy",
{"Ref", "Tiramisu"},
{median(duration_vector_1), median(duration_vector_2)});
if (CHECK_CORRECTNESS && run_ref && run_tiramisu)
compare_buffers("copy", b_a_ref, b_a);
if (PRINT_OUTPUT)
{
std::cout << "Tiramisu " << std::endl;
print_buffer(b_a);
std::cout << "Reference " << std::endl;
print_buffer(b_a_ref);
}
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>One more convertColor fix<commit_after><|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* 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 copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef BIVARIATE_POLYNOMIAL_HPP
#define BIVARIATE_POLYNOMIAL_HPP
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::BivariatePolynomialT (int new_degree) :
degree(0), parameters(NULL), gradient_x(NULL), gradient_y(NULL)
{
setDegree(new_degree);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::BivariatePolynomialT (const BivariatePolynomialT& other) :
degree(0), parameters(NULL), gradient_x(NULL), gradient_y(NULL)
{
deepCopy (other);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::~BivariatePolynomialT ()
{
memoryCleanUp ();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::setDegree (int newDegree)
{
if (newDegree <= 0)
{
degree = -1;
memoryCleanUp();
return;
}
int oldDegree = degree;
degree = newDegree;
if (oldDegree != degree)
{
delete[] parameters;
parameters = new real[getNoOfParameters ()];
}
delete gradient_x; gradient_x = NULL;
delete gradient_y; gradient_y = NULL;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::memoryCleanUp ()
{
delete[] parameters; parameters = NULL;
delete gradient_x; gradient_x = NULL;
delete gradient_y; gradient_y = NULL;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::deepCopy (const pcl::BivariatePolynomialT<real>& other)
{
if (this == &other) return;
if (degree != other.degree)
{
memoryCleanUp ();
degree = other.degree;
parameters = new real[getNoOfParameters ()];
}
if (other.gradient_x == NULL)
{
delete gradient_x; gradient_x=NULL;
delete gradient_y; gradient_y=NULL;
}
else if (gradient_x==NULL)
{
gradient_x = new pcl::BivariatePolynomialT<real> ();
gradient_y = new pcl::BivariatePolynomialT<real> ();
}
real* tmpParameters1 = parameters;
const real* tmpParameters2 = other.parameters;
unsigned int noOfParameters = getNoOfParameters ();
for (unsigned int i=0; i<noOfParameters; i++)
*tmpParameters1++ = *tmpParameters2++;
if (other.gradient_x != NULL)
{
gradient_x->deepCopy (*other.gradient_x);
gradient_y->deepCopy (*other.gradient_y);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::calculateGradient (bool forceRecalc)
{
if (gradient_x!=NULL && !forceRecalc)
if (gradient_x == NULL)
gradient_x = new pcl::BivariatePolynomialT<real> (degree-1);
if (gradient_y == NULL)
gradient_y = new pcl::BivariatePolynomialT<real> (degree-1);
unsigned int parameterPosDx=0, parameterPosDy=0;
for (int xDegree=degree; xDegree>=0; xDegree--)
{
for (int yDegree=degree-xDegree; yDegree>=0; yDegree--)
{
if (xDegree > 0)
{
gradient_x->parameters[parameterPosDx] = xDegree * parameters[parameterPosDx];
parameterPosDx++;
}
if (yDegree > 0)
{
gradient_y->parameters[parameterPosDy] = yDegree * parameters[ ( (degree+2-xDegree)* (degree+1-xDegree))/2 -
yDegree - 1];
parameterPosDy++;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> real
pcl::BivariatePolynomialT<real>::getValue (real x, real y) const
{
unsigned int parametersSize = getNoOfParameters ();
real* tmpParameter = ¶meters[parametersSize-1];
real tmpX=1.0, tmpY, ret=0;
for (int xDegree=0; xDegree<=degree; xDegree++)
{
tmpY = 1.0;
for (int yDegree=0; yDegree<=degree-xDegree; yDegree++)
{
ret += (*tmpParameter)*tmpX*tmpY;
tmpY *= y;
tmpParameter--;
}
tmpX *= x;
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::getValueOfGradient (real x, real y, real& gradX, real& gradY)
{
calculateGradient ();
gradX = gradient_x->getValue (x, y);
gradY = gradient_y->getValue (x, y);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::findCriticalPoints (std::vector<real>& x_values, std::vector<real>& y_values,
std::vector<int>& types) const
{
x_values.clear ();
y_values.clear ();
types.clear ();
if (degree == 2)
{
real x = (real(2)*parameters[2]*parameters[3] - parameters[1]*parameters[4]) /
(parameters[1]*parameters[1] - real(4)*parameters[0]*parameters[3]),
y = (real(-2)*parameters[0]*x - parameters[2]) / parameters[1];
if (!pcl_isfinite(x) || !pcl_isfinite(y))
return;
int type = 2;
real det_H = real(4)*parameters[0]*parameters[3] - parameters[1]*parameters[1];
//std::cout << "det(H) = "<<det_H<<"\n";
if (det_H > real(0)) // Check Hessian determinant
{
if (parameters[0]+parameters[3] < real(0)) // Check Hessian trace
type = 0;
else
type = 1;
}
x_values.push_back(x);
y_values.push_back(y);
types.push_back(type);
}
else
{
std::cerr << __PRETTY_FUNCTION__ << " is not implemented for polynomials of degree "<<degree<<". Sorry.\n";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> std::ostream&
pcl::operator<< (std::ostream& os, const pcl::BivariatePolynomialT<real>& p)
{
real* tmpParameter = p.parameters;
bool first = true;
real currentParameter;
for (int xDegree=p.degree; xDegree>=0; xDegree--)
{
for (int yDegree=p.degree-xDegree; yDegree>=0; yDegree--)
{
currentParameter = *tmpParameter;
if (!first)
{
os << (currentParameter<0.0?" - ":" + ");
currentParameter = fabs (currentParameter);
}
os << currentParameter;
if (xDegree>0)
{
os << "x";
if (xDegree>1)
os<<"^"<<xDegree;
}
if (yDegree>0)
{
os << "y";
if (yDegree>1)
os<<"^"<<yDegree;
}
first = false;
tmpParameter++;
}
}
return (os);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::writeBinary (std::ostream& os) const
{
os.write (reinterpret_cast<char*> (°ree), sizeof (int));
unsigned int paramCnt = getNoOfParametersFromDegree (this->degree);
os.write (reinterpret_cast<char*> (this->parameters), paramCnt * sizeof (real));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::writeBinary (const char* filename) const
{
std::ofstream fout (filename);
writeBinary (fout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::readBinary (std::istream& os)
{
memoryCleanUp ();
os.read (reinterpret_cast<char*> (&this->degree), sizeof (int));
unsigned int paramCnt = getNoOfParametersFromDegree (this->degree);
parameters = new real[paramCnt];
os.read (reinterpret_cast<char*> (&(*this->parameters)), paramCnt * sizeof (real));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::readBinary (const char* filename)
{
std::ifstream fin (filename);
readBinary (fin);
}
#endif
<commit_msg>fix issue #2478.<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2010-2012, Willow Garage, Inc.
*
* 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 copyright holder(s) 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.
*
* $Id$
*
*/
#ifndef BIVARIATE_POLYNOMIAL_HPP
#define BIVARIATE_POLYNOMIAL_HPP
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::BivariatePolynomialT (int new_degree) :
degree(0), parameters(NULL), gradient_x(NULL), gradient_y(NULL)
{
setDegree(new_degree);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::BivariatePolynomialT (const BivariatePolynomialT& other) :
degree(0), parameters(NULL), gradient_x(NULL), gradient_y(NULL)
{
deepCopy (other);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real>
pcl::BivariatePolynomialT<real>::~BivariatePolynomialT ()
{
memoryCleanUp ();
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::setDegree (int newDegree)
{
if (newDegree <= 0)
{
degree = -1;
memoryCleanUp();
return;
}
int oldDegree = degree;
degree = newDegree;
if (oldDegree != degree)
{
delete[] parameters;
parameters = new real[getNoOfParameters ()];
}
delete gradient_x; gradient_x = NULL;
delete gradient_y; gradient_y = NULL;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::memoryCleanUp ()
{
delete[] parameters; parameters = NULL;
delete gradient_x; gradient_x = NULL;
delete gradient_y; gradient_y = NULL;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::deepCopy (const pcl::BivariatePolynomialT<real>& other)
{
if (this == &other) return;
if (degree != other.degree)
{
memoryCleanUp ();
degree = other.degree;
parameters = new real[getNoOfParameters ()];
}
if (other.gradient_x == NULL)
{
delete gradient_x; gradient_x=NULL;
delete gradient_y; gradient_y=NULL;
}
else if (gradient_x==NULL)
{
gradient_x = new pcl::BivariatePolynomialT<real> ();
gradient_y = new pcl::BivariatePolynomialT<real> ();
}
real* tmpParameters1 = parameters;
const real* tmpParameters2 = other.parameters;
unsigned int noOfParameters = getNoOfParameters ();
for (unsigned int i=0; i<noOfParameters; i++)
*tmpParameters1++ = *tmpParameters2++;
if (other.gradient_x != NULL)
{
gradient_x->deepCopy (*other.gradient_x);
gradient_y->deepCopy (*other.gradient_y);
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::calculateGradient (bool forceRecalc)
{
if (gradient_x!=NULL && !forceRecalc) return;
if (gradient_x == NULL)
gradient_x = new pcl::BivariatePolynomialT<real> (degree-1);
if (gradient_y == NULL)
gradient_y = new pcl::BivariatePolynomialT<real> (degree-1);
unsigned int parameterPosDx=0, parameterPosDy=0;
for (int xDegree=degree; xDegree>=0; xDegree--)
{
for (int yDegree=degree-xDegree; yDegree>=0; yDegree--)
{
if (xDegree > 0)
{
gradient_x->parameters[parameterPosDx] = xDegree * parameters[parameterPosDx];
parameterPosDx++;
}
if (yDegree > 0)
{
gradient_y->parameters[parameterPosDy] = yDegree * parameters[ ( (degree+2-xDegree)* (degree+1-xDegree))/2 -
yDegree - 1];
parameterPosDy++;
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> real
pcl::BivariatePolynomialT<real>::getValue (real x, real y) const
{
unsigned int parametersSize = getNoOfParameters ();
real* tmpParameter = ¶meters[parametersSize-1];
real tmpX=1.0, tmpY, ret=0;
for (int xDegree=0; xDegree<=degree; xDegree++)
{
tmpY = 1.0;
for (int yDegree=0; yDegree<=degree-xDegree; yDegree++)
{
ret += (*tmpParameter)*tmpX*tmpY;
tmpY *= y;
tmpParameter--;
}
tmpX *= x;
}
return ret;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::getValueOfGradient (real x, real y, real& gradX, real& gradY)
{
calculateGradient ();
gradX = gradient_x->getValue (x, y);
gradY = gradient_y->getValue (x, y);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::findCriticalPoints (std::vector<real>& x_values, std::vector<real>& y_values,
std::vector<int>& types) const
{
x_values.clear ();
y_values.clear ();
types.clear ();
if (degree == 2)
{
real x = (real(2)*parameters[2]*parameters[3] - parameters[1]*parameters[4]) /
(parameters[1]*parameters[1] - real(4)*parameters[0]*parameters[3]),
y = (real(-2)*parameters[0]*x - parameters[2]) / parameters[1];
if (!pcl_isfinite(x) || !pcl_isfinite(y))
return;
int type = 2;
real det_H = real(4)*parameters[0]*parameters[3] - parameters[1]*parameters[1];
//std::cout << "det(H) = "<<det_H<<"\n";
if (det_H > real(0)) // Check Hessian determinant
{
if (parameters[0]+parameters[3] < real(0)) // Check Hessian trace
type = 0;
else
type = 1;
}
x_values.push_back(x);
y_values.push_back(y);
types.push_back(type);
}
else
{
std::cerr << __PRETTY_FUNCTION__ << " is not implemented for polynomials of degree "<<degree<<". Sorry.\n";
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> std::ostream&
pcl::operator<< (std::ostream& os, const pcl::BivariatePolynomialT<real>& p)
{
real* tmpParameter = p.parameters;
bool first = true;
real currentParameter;
for (int xDegree=p.degree; xDegree>=0; xDegree--)
{
for (int yDegree=p.degree-xDegree; yDegree>=0; yDegree--)
{
currentParameter = *tmpParameter;
if (!first)
{
os << (currentParameter<0.0?" - ":" + ");
currentParameter = fabs (currentParameter);
}
os << currentParameter;
if (xDegree>0)
{
os << "x";
if (xDegree>1)
os<<"^"<<xDegree;
}
if (yDegree>0)
{
os << "y";
if (yDegree>1)
os<<"^"<<yDegree;
}
first = false;
tmpParameter++;
}
}
return (os);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::writeBinary (std::ostream& os) const
{
os.write (reinterpret_cast<char*> (°ree), sizeof (int));
unsigned int paramCnt = getNoOfParametersFromDegree (this->degree);
os.write (reinterpret_cast<char*> (this->parameters), paramCnt * sizeof (real));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::writeBinary (const char* filename) const
{
std::ofstream fout (filename);
writeBinary (fout);
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::readBinary (std::istream& os)
{
memoryCleanUp ();
os.read (reinterpret_cast<char*> (&this->degree), sizeof (int));
unsigned int paramCnt = getNoOfParametersFromDegree (this->degree);
parameters = new real[paramCnt];
os.read (reinterpret_cast<char*> (&(*this->parameters)), paramCnt * sizeof (real));
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
template<typename real> void
pcl::BivariatePolynomialT<real>::readBinary (const char* filename)
{
std::ifstream fin (filename);
readBinary (fin);
}
#endif
<|endoftext|> |
<commit_before>//
// Copyright 2012 Josh Blum
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef INCLUDED_APOLOGY_WORKER_HPP
#define INCLUDED_APOLOGY_WORKER_HPP
#include <Apology/Config.hpp>
#include <Apology/Port.hpp>
#include <Theron/Actor.h>
#include <vector>
APOLOGY_EXTERN template class APOLOGY_API std::vector<Apology::Worker *>;
APOLOGY_EXTERN template class APOLOGY_API std::vector<std::vector<Apology::Port> >;
namespace Apology
{
/*!
* A derived worker should register a message handler
* for this message to get an update about topology.
*/
struct APOLOGY_API WorkerTopologyMessage
{
//empty
};
/*!
* A worker represents a unit of computation.
* As part of being in a topology:
* Arbitrary messages may be accepted from upstream ports
* and arbitrary messages may be posted to downstream ports.
*/
struct APOLOGY_API Worker : Base, Theron::Actor
{
public:
//! Create a new worker actor
Worker(Theron::Framework &framework);
//! Destroy the worker actor
virtual ~Worker(void);
//! Get the number of input ports
size_t get_num_inputs(void) const;
//! Get the number of output ports
size_t get_num_outputs(void) const;
/*!
* Send a message to all downstream blocks on this output port.
* \param index the output port index
* \msg the message (must have index member)
*/
template <typename Message>
void post_downstream(const size_t index, const Message &msg) const;
/*!
* Send a message to all upstream blocks on this input port.
* \param index the input port index
* \msg the message (must have index member)
*/
template <typename Message>
void post_upstream(const size_t index, const Message &msg) const;
std::vector<std::vector<Port> > _inputs;
std::vector<std::vector<Port> > _outputs;
};
THERON_FORCEINLINE size_t Worker::get_num_inputs(void) const
{
return _inputs.size();
}
THERON_FORCEINLINE size_t Worker::get_num_outputs(void) const
{
return _outputs.size();
}
template <typename Message>
THERON_FORCEINLINE void Worker::post_downstream(const size_t index, const Message &msg) const
{
Message message = msg;
for (size_t i = 0; i < _outputs[index].size(); i++)
{
const Port &port = _outputs[index][i];
message.index = port.index;
reinterpret_cast<Worker *>(port.elem)->Push(message, Theron::Address());
}
}
template <typename Message>
THERON_FORCEINLINE void Worker::post_upstream(const size_t index, const Message &msg) const
{
Message message = msg;
for (size_t i = 0; i < _inputs[index].size(); i++)
{
const Port &port = _inputs[index][i];
message.index = port.index;
reinterpret_cast<Worker *>(port.elem)->Push(message, Theron::Address());
}
}
} //namespace Apology
#endif /*INCLUDED_APOLOGY_WORKER_HPP*/
<commit_msg>dont need public in Worker, its a struct<commit_after>//
// Copyright 2012 Josh Blum
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef INCLUDED_APOLOGY_WORKER_HPP
#define INCLUDED_APOLOGY_WORKER_HPP
#include <Apology/Config.hpp>
#include <Apology/Port.hpp>
#include <Theron/Actor.h>
#include <vector>
APOLOGY_EXTERN template class APOLOGY_API std::vector<Apology::Worker *>;
APOLOGY_EXTERN template class APOLOGY_API std::vector<std::vector<Apology::Port> >;
namespace Apology
{
/*!
* A derived worker should register a message handler
* for this message to get an update about topology.
*/
struct APOLOGY_API WorkerTopologyMessage
{
//empty
};
/*!
* A worker represents a unit of computation.
* As part of being in a topology:
* Arbitrary messages may be accepted from upstream ports
* and arbitrary messages may be posted to downstream ports.
*/
struct APOLOGY_API Worker : Base, Theron::Actor
{
//! Create a new worker actor
Worker(Theron::Framework &framework);
//! Destroy the worker actor
virtual ~Worker(void);
//! Get the number of input ports
size_t get_num_inputs(void) const;
//! Get the number of output ports
size_t get_num_outputs(void) const;
/*!
* Send a message to all downstream blocks on this output port.
* \param index the output port index
* \msg the message (must have index member)
*/
template <typename Message>
void post_downstream(const size_t index, const Message &msg) const;
/*!
* Send a message to all upstream blocks on this input port.
* \param index the input port index
* \msg the message (must have index member)
*/
template <typename Message>
void post_upstream(const size_t index, const Message &msg) const;
std::vector<std::vector<Port> > _inputs;
std::vector<std::vector<Port> > _outputs;
};
THERON_FORCEINLINE size_t Worker::get_num_inputs(void) const
{
return _inputs.size();
}
THERON_FORCEINLINE size_t Worker::get_num_outputs(void) const
{
return _outputs.size();
}
template <typename Message>
THERON_FORCEINLINE void Worker::post_downstream(const size_t index, const Message &msg) const
{
Message message = msg;
for (size_t i = 0; i < _outputs[index].size(); i++)
{
const Port &port = _outputs[index][i];
message.index = port.index;
reinterpret_cast<Worker *>(port.elem)->Push(message, Theron::Address());
}
}
template <typename Message>
THERON_FORCEINLINE void Worker::post_upstream(const size_t index, const Message &msg) const
{
Message message = msg;
for (size_t i = 0; i < _inputs[index].size(); i++)
{
const Port &port = _inputs[index][i];
message.index = port.index;
reinterpret_cast<Worker *>(port.elem)->Push(message, Theron::Address());
}
}
} //namespace Apology
#endif /*INCLUDED_APOLOGY_WORKER_HPP*/
<|endoftext|> |
<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
#include <iostream>
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
// ignore the "Global" namespace, which contains the QtMsgType enum
if (meta_class->name().startsWith("Global")) return false;
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
if (type->isEnum() && (options & ProtectedEnumAsInts)) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)te);
if (enumType && enumType->wasProtected()) {
s << "int";
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName)) {
if (option & UseIndexedName) {
s << " " << arg->indexedName();
}
else {
s << " " << arg->argumentName();
}
}
if ((option & IncludeDefaultExpression) && !arg->defaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->defaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "py_set_";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "py_get_";
s << name_prefix << function_name;
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
if (!meta_function->exception().isEmpty())
s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);
bool ShellGenerator::functionHasNonConstReferences(const AbstractMetaFunction* function)
{
foreach(const AbstractMetaArgument* arg, function->arguments())
{
if (!arg->type()->isConstant() && arg->type()->isReference()) {
QString s;
QTextStream t(&s);
t << function->implementingClass()->qualifiedCppName() << "::";
writeFunctionSignature(t, function, 0, "",
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
std::cout << s.toLatin1().constData() << std::endl;
return true;
}
}
return false;
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
bool hasPromoter = meta_class->typeEntry()->shouldCreatePromoter();
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
if (hasPromoter || func->wasPublic()) {
resultFunctions << func;
}
}
}
qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
// | AbstractMetaClass::NotRemovedFromTargetLang
);
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (func->wasProtected() || func->isVirtual()) {
functions << func;
}
}
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QByteArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<commit_msg>remove virtual functions that are removed from the target language (why was this commented?)<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation ([email protected])
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at [email protected].
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "shellgenerator.h"
#include "reporthandler.h"
#include "metaqtscript.h"
#include <iostream>
bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
uint cg = meta_class->typeEntry()->codeGeneration();
// ignore the "Global" namespace, which contains the QtMsgType enum
if (meta_class->name().startsWith("Global")) return false;
return ((cg & TypeEntry::GenerateCode) != 0);
}
void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
s << type->originalTypeDescription();
return;
}
if (type->isArray()) {
writeTypeInfo(s, type->arrayElementType(), options);
if (options & ArrayAsPointer) {
s << "*";
} else {
s << "[" << type->arrayElementCount() << "]";
}
return;
}
const TypeEntry *te = type->typeEntry();
if (type->isConstant() && !(options & ExcludeConst))
s << "const ";
if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
s << "int";
} else if (te->isFlags()) {
s << ((FlagsTypeEntry *) te)->originalName();
} else {
if (type->isEnum() && (options & ProtectedEnumAsInts)) {
AbstractMetaEnum* enumType = m_classes.findEnum((EnumTypeEntry *)te);
if (enumType && enumType->wasProtected()) {
s << "int";
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
} else {
s << fixCppTypeName(te->qualifiedCppName());
}
}
if (type->instantiations().size() > 0
&& (!type->isContainer()
|| (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
s << '<';
QList<AbstractMetaType *> args = type->instantiations();
bool nested_template = false;
for (int i=0; i<args.size(); ++i) {
if (i != 0)
s << ", ";
nested_template |= args.at(i)->isContainer();
writeTypeInfo(s, args.at(i));
}
if (nested_template)
s << ' ';
s << '>';
}
s << QString(type->indirections(), '*');
if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
s << "&";
if (type->isReference() && (options & ConvertReferenceToPtr)) {
s << "*";
}
if (!(options & SkipName))
s << ' ';
}
void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
const AbstractMetaArgumentList &arguments,
Option option,
int numArguments)
{
if (numArguments < 0) numArguments = arguments.size();
for (int i=0; i<numArguments; ++i) {
if (i != 0)
s << ", ";
AbstractMetaArgument *arg = arguments.at(i);
writeTypeInfo(s, arg->type(), option);
if (!(option & SkipName)) {
if (option & UseIndexedName) {
s << " " << arg->indexedName();
}
else {
s << " " << arg->argumentName();
}
}
if ((option & IncludeDefaultExpression) && !arg->defaultValueExpression().isEmpty()) {
s << " = ";
QString expr = arg->defaultValueExpression();
if (expr != "0") {
QString qualifier;
if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
} else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
}
if (!qualifier.isEmpty()) {
s << qualifier << "::";
}
}
s << expr;
}
}
}
/*!
* Writes the function \a meta_function signature to the textstream \a s.
*
* The \a name_prefix can be used to give the function name a prefix,
* like "__public_" or "__override_" and \a classname_prefix can
* be used to give the class name a prefix.
*
* The \a option flags can be used to tweak various parameters, such as
* showing static, original vs renamed name, underscores for space etc.
*
* The \a extra_arguments list is a list of extra arguments on the
* form "bool static_call".
*/
void ShellGenerator::writeFunctionSignature(QTextStream &s,
const AbstractMetaFunction *meta_function,
const AbstractMetaClass *implementor,
const QString &name_prefix,
Option option,
const QString &classname_prefix,
const QStringList &extra_arguments,
int numArguments)
{
// ### remove the implementor
AbstractMetaType *function_type = meta_function->type();
if ((option & SkipReturnType) == 0) {
if (function_type) {
writeTypeInfo(s, function_type, option);
s << " ";
} else if (!meta_function->isConstructor()) {
s << "void ";
}
}
if (implementor) {
if (classname_prefix.isEmpty())
s << wrapperClassName(implementor) << "::";
else
s << classname_prefix << implementor->name() << "::";
}
QString function_name;
if (option & OriginalName)
function_name = meta_function->originalName();
else
function_name = meta_function->name();
if (option & UnderscoreSpaces)
function_name = function_name.replace(' ', '_');
if (meta_function->isConstructor())
function_name = meta_function->ownerClass()->name();
if (meta_function->isStatic() && (option & ShowStatic)) {
function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
}
if (function_name.startsWith("operator")) {
function_name = meta_function->name();
}
if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
s << "py_set_";
else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
s << "py_get_";
s << name_prefix << function_name;
s << "(";
if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
if (meta_function->arguments().size() != 0) {
s << ", ";
}
}
writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);
// The extra arguments...
for (int i=0; i<extra_arguments.size(); ++i) {
if (i > 0 || meta_function->arguments().size() != 0)
s << ", ";
s << extra_arguments.at(i);
}
s << ")";
if (meta_function->isConstant())
s << " const";
if (!meta_function->exception().isEmpty())
s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);
bool ShellGenerator::functionHasNonConstReferences(const AbstractMetaFunction* function)
{
foreach(const AbstractMetaArgument* arg, function->arguments())
{
if (!arg->type()->isConstant() && arg->type()->isReference()) {
QString s;
QTextStream t(&s);
t << function->implementingClass()->qualifiedCppName() << "::";
writeFunctionSignature(t, function, 0, "",
Option(ConvertReferenceToPtr | FirstArgIsWrappedObject | IncludeDefaultExpression | OriginalName | ShowStatic | UnderscoreSpaces | ProtectedEnumAsInts));
std::cout << s.toLatin1().constData() << std::endl;
return true;
}
}
return false;
}
AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
);
QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
foreach(AbstractMetaFunction* func, functions2) {
set1.insert(func);
}
AbstractMetaFunctionList resultFunctions;
bool hasPromoter = meta_class->typeEntry()->shouldCreatePromoter();
foreach(AbstractMetaFunction* func, set1.toList()) {
if (!func->isAbstract() && func->implementingClass()==meta_class) {
if (hasPromoter || func->wasPublic()) {
resultFunctions << func;
}
}
}
qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
return resultFunctions;
}
AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions = meta_class->queryFunctions(
AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
| AbstractMetaClass::NotRemovedFromTargetLang
);
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
AbstractMetaFunctionList functions;
AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
foreach(AbstractMetaFunction* func, functions1) {
if (func->wasProtected() || func->isVirtual()) {
functions << func;
}
}
qSort(functions.begin(), functions.end(), function_sorter);
return functions;
}
/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
if (inc.name.isEmpty())
return;
if (inc.type == Include::TargetLangImport)
return;
stream << "#include ";
if (inc.type == Include::IncludePath)
stream << "<";
else
stream << "\"";
stream << inc.name;
if (inc.type == Include::IncludePath)
stream << ">";
else
stream << "\"";
stream << endl;
}
/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
&& (fun->arguments().size() == 1)
&& (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
|| ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}
bool ShellGenerator::isBuiltIn(const QString& name) {
static QSet<QString> builtIn;
if (builtIn.isEmpty()) {
builtIn.insert("Qt");
builtIn.insert("QFont");
builtIn.insert("QPixmap");
builtIn.insert("QBrush");
builtIn.insert("QBitArray");
builtIn.insert("QByteArray");
builtIn.insert("QPalette");
builtIn.insert("QPen");
builtIn.insert("QIcon");
builtIn.insert("QImage");
builtIn.insert("QPolygon");
builtIn.insert("QRegion");
builtIn.insert("QBitmap");
builtIn.insert("QCursor");
builtIn.insert("QColor");
builtIn.insert("QSizePolicy");
builtIn.insert("QKeySequence");
builtIn.insert("QTextLength");
builtIn.insert("QTextFormat");
builtIn.insert("QMatrix");
builtIn.insert("QDate");
builtIn.insert("QTime");
builtIn.insert("QDateTime");
builtIn.insert("QUrl");
builtIn.insert("QLocale");
builtIn.insert("QRect");
builtIn.insert("QRectF");
builtIn.insert("QSize");
builtIn.insert("QSizeF");
builtIn.insert("QLine");
builtIn.insert("QLineF");
builtIn.insert("QPoint");
builtIn.insert("QPointF");
builtIn.insert("QRegExp");
}
return builtIn.contains(name);
}
<|endoftext|> |
<commit_before>#include "RenderTexture.hpp"
namespace MPACK
{
namespace Graphics
{
RenderTexture::RenderTexture()
: m_fboId(0), m_depthTex(NULL), m_colorTex(NULL)
{
}
RenderTexture::~RenderTexture()
{
GL_CHECK( glDeleteFramebuffers(1,&m_fboId) );
if(m_colorTex)
{
delete m_colorTex;
m_colorTex = NULL;
}
if(m_depthTex)
{
delete m_depthTex;
m_depthTex = NULL;
}
}
void RenderTexture::Init(GLuint width, GLuint height)
{
GL_CHECK( glDeleteFramebuffers(1,&m_fboId) );
if(m_colorTex)
{
GL_CHECK( glDeleteTextures(1,&m_colorTex->m_texId) );
}
else
{
m_colorTex=new Texture2D();
}
GL_CHECK( glGenTextures(1, &m_colorTex->m_texId) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, m_colorTex->m_texId) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, 0) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, 0) );
if(m_depthTex)
{
GL_CHECK( glDeleteTextures(1,&m_depthTex->m_texId) );
}
else
{
m_depthTex=new Texture2D();
}
GL_CHECK( glGenTextures(1, &m_depthTex->m_texId) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, m_depthTex->m_texId) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, 0) );
GL_CHECK( glGenFramebuffers(1, &m_fboId) );
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, m_fboId) );
GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, m_colorTex->m_texId, 0) );
GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
GL_TEXTURE_2D, m_depthTex->m_texId, 0) );
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, 0) );
GLenum status;
GL_CHECK( status = glCheckFramebufferStatus(GL_FRAMEBUFFER) );
if ( status == GL_FRAMEBUFFER_COMPLETE )
{
LOGI("FBO successfully created!");
}
else
{
LOGE("ERROR: Failed to init FBO");
}
}
void RenderTexture::Bind()
{
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, m_fboId) );
}
void RenderTexture::Unbind()
{
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, 0) );
}
}
}
<commit_msg>Fixed framebuffer bug (crash on Nexus 7)<commit_after>#include "RenderTexture.hpp"
namespace MPACK
{
namespace Graphics
{
RenderTexture::RenderTexture()
: m_fboId(0), m_depthTex(NULL), m_colorTex(NULL)
{
}
RenderTexture::~RenderTexture()
{
GL_CHECK( glDeleteFramebuffers(1,&m_fboId) );
if(m_colorTex)
{
delete m_colorTex;
m_colorTex = NULL;
}
if(m_depthTex)
{
delete m_depthTex;
m_depthTex = NULL;
}
}
void RenderTexture::Init(GLuint width, GLuint height)
{
GL_CHECK( glDeleteFramebuffers(1,&m_fboId) );
if(m_colorTex)
{
GL_CHECK( glDeleteTextures(1,&m_colorTex->m_texId) );
}
else
{
m_colorTex=new Texture2D();
}
GL_CHECK( glGenTextures(1, &m_colorTex->m_texId) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, m_colorTex->m_texId) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0,
GL_RGBA, GL_UNSIGNED_BYTE, 0) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, 0) );
if(m_depthTex)
{
GL_CHECK( glDeleteTextures(1,&m_depthTex->m_texId) );
}
else
{
m_depthTex=new Texture2D();
}
/*
GL_CHECK( glGenTextures(1, &m_depthTex->m_texId) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, m_depthTex->m_texId) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) );
GL_CHECK( glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, width, height, 0,
GL_DEPTH_COMPONENT, GL_UNSIGNED_SHORT, NULL) );
GL_CHECK( glBindTexture(GL_TEXTURE_2D, 0) );
*/
GLuint depthRenderbuffer;
GL_CHECK( glGenRenderbuffers(1, &depthRenderbuffer) );
GL_CHECK( glBindRenderbuffer(GL_RENDERBUFFER, depthRenderbuffer) );
GL_CHECK( glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT16, width, height) );
GL_CHECK( glGenFramebuffers(1, &m_fboId) );
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, m_fboId) );
GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
GL_TEXTURE_2D, m_colorTex->m_texId, 0) );
//GL_CHECK( glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
// GL_TEXTURE_2D, m_depthTex->m_texId, 0) );
GL_CHECK ( glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthRenderbuffer) );
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, 0) );
GLenum status;
GL_CHECK( status = glCheckFramebufferStatus(GL_FRAMEBUFFER) );
if ( status == GL_FRAMEBUFFER_COMPLETE )
{
LOGI("FBO successfully created!");
}
else
{
LOGE("ERROR: Failed to init FBO");
}
}
void RenderTexture::Bind()
{
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, m_fboId) );
}
void RenderTexture::Unbind()
{
GL_CHECK( glBindFramebuffer(GL_FRAMEBUFFER, 0) );
}
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_DEFINE_HPP
#define LIBBITCOIN_DEFINE_HPP
// See http://gcc.gnu.org/wiki/Visibility
// Generic helper definitions for shared library support
#if defined _WIN32 || defined __CYGWIN__
#define BC_HELPER_DLL_IMPORT __declspec(dllimport)
#define BC_HELPER_DLL_EXPORT __declspec(dllexport)
#define BC_HELPER_DLL_LOCAL
#else
#if __GNUC__ >= 4
#define BC_HELPER_DLL_IMPORT __attribute__ ((visibility ("default")))
#define BC_HELPER_DLL_EXPORT __attribute__ ((visibility ("default")))
#define BC_HELPER_DLL_LOCAL __attribute__ ((visibility ("internal")))
#else
#define BC_HELPER_DLL_IMPORT
#define BC_HELPER_DLL_EXPORT
#define BC_HELPER_DLL_LOCAL
#endif
#endif
// Now we use the generic helper definitions above to
// define BC_API and BC_INTERNAL.
// BC_API is used for the public API symbols. It either DLL imports or
// DLL exports (or does nothing for static build)
// BC_INTERNAL is used for non-api symbols.
#if defined BC_STATIC
#define BC_API
#define BC_INTERNAL
#elif defined BC_DLL
#define BC_API BC_HELPER_DLL_EXPORT
#define BC_INTERNAL BC_HELPER_DLL_LOCAL
#else
#define BC_API BC_HELPER_DLL_IMPORT
#define BC_INTERNAL BC_HELPER_DLL_LOCAL
#endif
// Remove this when cURL dependency is fully removed.
#define NO_CURL
// Tag to deprecate functions and methods.
// Gives a compiler warning when they are used.
#if defined _WIN32 || defined __CYGWIN__
#define BC_DEPRECATED
#else
#if __GNUC__ >= 4
#define BC_DEPRECATED __attribute__((deprecated))
#else
#define BC_DEPRECATED
#endif
#endif
#endif
<commit_msg>Implement deprecated attribute for msvc12.<commit_after>/*
* Copyright (c) 2011-2013 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef LIBBITCOIN_DEFINE_HPP
#define LIBBITCOIN_DEFINE_HPP
// See http://gcc.gnu.org/wiki/Visibility
// Generic helper definitions for shared library support
#if defined _WIN32 || defined __CYGWIN__
#define BC_HELPER_DLL_IMPORT __declspec(dllimport)
#define BC_HELPER_DLL_EXPORT __declspec(dllexport)
#define BC_HELPER_DLL_LOCAL
#else
#if __GNUC__ >= 4
#define BC_HELPER_DLL_IMPORT __attribute__ ((visibility ("default")))
#define BC_HELPER_DLL_EXPORT __attribute__ ((visibility ("default")))
#define BC_HELPER_DLL_LOCAL __attribute__ ((visibility ("internal")))
#else
#define BC_HELPER_DLL_IMPORT
#define BC_HELPER_DLL_EXPORT
#define BC_HELPER_DLL_LOCAL
#endif
#endif
// Now we use the generic helper definitions above to
// define BC_API and BC_INTERNAL.
// BC_API is used for the public API symbols. It either DLL imports or
// DLL exports (or does nothing for static build)
// BC_INTERNAL is used for non-api symbols.
#if defined BC_STATIC
#define BC_API
#define BC_INTERNAL
#elif defined BC_DLL
#define BC_API BC_HELPER_DLL_EXPORT
#define BC_INTERNAL BC_HELPER_DLL_LOCAL
#else
#define BC_API BC_HELPER_DLL_IMPORT
#define BC_INTERNAL BC_HELPER_DLL_LOCAL
#endif
// Remove this when cURL dependency is fully removed.
#define NO_CURL
// Tag to deprecate functions and methods.
// Gives a compiler warning when they are used.
#if defined _MSC_VER || defined __CYGWIN__
#define BC_DEPRECATED __declspec(deprecated)
#else
#if __GNUC__ >= 4
#define BC_DEPRECATED __attribute__((deprecated))
#else
#define BC_DEPRECATED
#endif
#endif
#endif
<|endoftext|> |
<commit_before>#pragma once
#define BRYNET_VERSION 1011001
<commit_msg>Update Version.hpp<commit_after>#pragma once
#define BRYNET_VERSION 1011002
<|endoftext|> |
<commit_before>#ifndef __CALCULATE_NODE_HPP__
#define __CALCULATE_NODE_HPP__
#include <iterator>
#include <memory>
#include <ostream>
#include <stack>
#include <sstream>
#include "symbol.hpp"
#include "util.hpp"
namespace calculate {
template<typename Parser>
class Node {
public:
using Type = typename Parser::Type;
using Lexer = typename Parser::Lexer;
using Symbol = Symbol<Node>;
using SymbolType = typename Symbol::SymbolType;
template<typename BaseType> friend class BaseParser;
friend struct std::hash<Node>;
public:
using const_iterator = typename std::vector<Node>::const_iterator;
class Variables {
public:
const std::vector<std::string> variables;
private:
std::size_t _size;
std::unique_ptr<Type[]> _values;
void _update(std::size_t) const {}
template<typename Last>
void _update(std::size_t n, Last last) { _values[n] = last; }
template<typename Head, typename... Args>
void _update(std::size_t n, Head head, Args... args) {
_values[n] = head;
_update(n + 1, args...);
}
public:
explicit Variables(
const std::shared_ptr<Lexer>& lexer,
const std::vector<std::string>& keys={}
) :
variables{keys},
_size{keys.size()},
_values{std::make_unique<Type[]>(_size)}
{
std::unordered_set<std::string> singles{keys.begin(), keys.end()};
for (const auto &variable : keys) {
if (!std::regex_match(variable, lexer->name_regex))
throw UnsuitableName{variable};
else if (singles.erase(variable) == 0)
throw RepeatedSymbol{variable};
}
}
std::size_t index(const std::string& token) const {
auto found = std::find(variables.begin(), variables.end(), token);
if (found != variables.end())
return found - variables.begin();
throw UndefinedSymbol{token};
}
Type& at(const std::string& token) const {
return _values[index(token)];
}
void update(const std::vector<Type>& values) {
if (_size != values.size())
throw ArgumentsMismatch{_size, values.size()};
for (std::size_t i = 0; i < _size; i++)
_values[i] = values[i];
}
template<typename... Args>
void update(Args... args) {
if (_size != sizeof...(args))
throw ArgumentsMismatch{_size, sizeof...(args)};
_update(0, args...);
}
};
private:
std::shared_ptr<Lexer> _lexer;
std::string _token;
std::shared_ptr<Variables> _variables;
std::shared_ptr<Symbol> _symbol;
std::vector<Node> _nodes;
std::size_t _hash;
Node() = delete;
explicit Node(
const std::shared_ptr<Lexer>& _lexer,
const std::string& token,
const std::shared_ptr<Variables>& variables,
const std::shared_ptr<Symbol>& symbol,
std::vector<Node>&& nodes,
std::size_t hash
) :
_lexer{_lexer},
_token{token},
_variables{variables},
_symbol{symbol},
_nodes{std::move(nodes)},
_hash{hash}
{
if (_nodes.size() != _symbol->arguments())
throw ArgumentsMismatch{
_token,
_nodes.size(),
_symbol->arguments()
};
}
std::vector<std::string> _pruned() const noexcept {
std::istringstream extractor{postfix()};
std::vector<std::string> tokens{
std::istream_iterator<std::string>{extractor},
std::istream_iterator<std::string>{}
};
std::vector<std::string> pruned{};
for (const auto& variable : variables())
if (
std::find(tokens.begin(), tokens.end(), variable) !=
tokens.end()
)
pruned.push_back(variable);
pruned.erase(std::unique(pruned.begin(), pruned.end()), pruned.end());
return pruned;
}
void _rebind(const std::shared_ptr<Variables>& context) noexcept {
_variables = context;
for (auto& node : _nodes)
node._rebind(context);
}
public:
Node(const Node& other) noexcept :
_lexer{other._lexer},
_token{other._token},
_variables{},
_symbol{other._symbol},
_nodes{other._nodes},
_hash{other._hash}
{ _rebind(std::make_shared<Variables>(_lexer, other._pruned())); }
Node(Node&& other) noexcept :
_lexer{std::move(other._lexer)},
_token{std::move(other._token)},
_variables{std::move(other._variables)},
_symbol{std::move(other._symbol)},
_nodes{std::move(other._nodes)},
_hash{std::move(other._hash)}
{}
const Node& operator=(Node other) noexcept {
swap(*this, other);
return *this;
}
friend void swap(Node& one, Node& another) noexcept {
using std::swap;
swap(one._lexer, another._lexer);
swap(one._token, another._token);
swap(one._variables, another._variables);
swap(one._symbol, another._symbol);
swap(one._nodes, another._nodes);
}
std::shared_ptr<Lexer> lexer() const noexcept { return _lexer; }
static Type evaluate(const Node& node) {
return node._symbol->evaluate(node._nodes);
}
explicit operator Type() const {
if (variables().size() > 0)
throw ArgumentsMismatch{variables().size(), 0};
return _symbol->evaluate(_nodes);
}
Type operator()(const std::vector<Type>& values) const {
_variables->update(values);
return _symbol->evaluate(_nodes);
}
template<typename... Args>
Type operator()(Args&&... args) const {
_variables->update(std::forward<Args>(args)...);
return _symbol->evaluate(_nodes);
}
bool operator==(const Node& other) const noexcept {
std::stack<std::pair<const_iterator, const_iterator>> these{};
std::stack<const_iterator> those{};
auto equal = [&](auto left, auto right) {
try {
return
left->_variables->index(left->_token) ==
right->_variables->index(right->_token);
}
catch (const UndefinedSymbol&) {
if (left->_symbol == right->_symbol)
return true;
return *(left->_symbol) == *(right->_symbol);
}
};
if (!equal(this, &other))
return false;
these.push({this->begin(), this->end()});
those.push(other.begin());
while(!these.empty()) {
auto one = these.top();
auto another = those.top();
these.pop();
those.pop();
if (one.first != one.second) {
if (!equal(one.first, another))
return false;
these.push({one.first->begin(), one.first->end()});
these.push({one.first + 1, one.second});
those.push(another->begin());
those.push(another + 1);
}
}
return true;
}
const Node& operator[](std::size_t index) const { return _nodes[index]; }
const Node& at(std::size_t index) const { return _nodes.at(index); }
const_iterator begin() const noexcept { return _nodes.begin(); }
const_iterator end() const noexcept { return _nodes.end(); }
const_iterator rbegin() const noexcept { return _nodes.rbegin(); }
const_iterator rend() const noexcept { return _nodes.rend(); }
friend std::ostream& operator<<(
std::ostream& ostream,
const Node& node
) noexcept {
ostream << node.infix();
return ostream;
}
const std::string& token() const noexcept { return _token; }
std::size_t branches() const noexcept { return _nodes.size(); }
std::string infix() const noexcept {
using Operator = Operator<Node>;
using Associativity = typename Operator::Associativity;
std::string infix{};
auto brace = [&](std::size_t i) {
const auto& node = _nodes[i];
if (node._symbol->symbol() == SymbolType::OPERATOR) {
auto po = static_cast<Operator*>(_symbol.get());
auto co = static_cast<Operator*>(node._symbol.get());
auto pp = po->precedence();
auto cp = co->precedence();
auto pa = !i ?
po->associativity() != Associativity::RIGHT :
po->associativity() != Associativity::LEFT;
if ((pa && cp < pp) || (!pa && cp <= pp))
return _lexer->left + node.infix() + _lexer->right;
}
return node.infix();
};
switch (_symbol->symbol()) {
case (SymbolType::FUNCTION):
infix += _token + _lexer->left;
for (const auto& node : _nodes)
infix += node.infix() + _lexer->separator;
infix.back() = _lexer->right.front();
return infix;
case (SymbolType::OPERATOR):
infix += brace(0) + _token + brace(1);
return infix;
default:
return _token;
}
}
std::string postfix() const noexcept {
std::string postfix{};
for (const auto& node : _nodes)
postfix += node.postfix() + " ";
return postfix + _token;
}
std::vector<std::string> variables() const noexcept {
return _variables->variables;
}
};
}
namespace std {
template<typename Parser>
struct hash<calculate::Node<Parser>> {
size_t operator()(const calculate::Node<Parser>& node) const {
return node._hash;
}
};
}
#endif
<commit_msg>Remove reverse iterators<commit_after>#ifndef __CALCULATE_NODE_HPP__
#define __CALCULATE_NODE_HPP__
#include <iterator>
#include <memory>
#include <ostream>
#include <stack>
#include <sstream>
#include "symbol.hpp"
#include "util.hpp"
namespace calculate {
template<typename Parser>
class Node {
public:
using Type = typename Parser::Type;
using Lexer = typename Parser::Lexer;
using Symbol = Symbol<Node>;
using SymbolType = typename Symbol::SymbolType;
template<typename BaseType> friend class BaseParser;
friend struct std::hash<Node>;
public:
using const_iterator = typename std::vector<Node>::const_iterator;
class Variables {
public:
const std::vector<std::string> variables;
private:
std::size_t _size;
std::unique_ptr<Type[]> _values;
void _update(std::size_t) const {}
template<typename Last>
void _update(std::size_t n, Last last) { _values[n] = last; }
template<typename Head, typename... Args>
void _update(std::size_t n, Head head, Args... args) {
_values[n] = head;
_update(n + 1, args...);
}
public:
explicit Variables(
const std::shared_ptr<Lexer>& lexer,
const std::vector<std::string>& keys={}
) :
variables{keys},
_size{keys.size()},
_values{std::make_unique<Type[]>(_size)}
{
std::unordered_set<std::string> singles{keys.begin(), keys.end()};
for (const auto &variable : keys) {
if (!std::regex_match(variable, lexer->name_regex))
throw UnsuitableName{variable};
else if (singles.erase(variable) == 0)
throw RepeatedSymbol{variable};
}
}
std::size_t index(const std::string& token) const {
auto found = std::find(variables.begin(), variables.end(), token);
if (found != variables.end())
return found - variables.begin();
throw UndefinedSymbol{token};
}
Type& at(const std::string& token) const {
return _values[index(token)];
}
void update(const std::vector<Type>& values) {
if (_size != values.size())
throw ArgumentsMismatch{_size, values.size()};
for (std::size_t i = 0; i < _size; i++)
_values[i] = values[i];
}
template<typename... Args>
void update(Args... args) {
if (_size != sizeof...(args))
throw ArgumentsMismatch{_size, sizeof...(args)};
_update(0, args...);
}
};
private:
std::shared_ptr<Lexer> _lexer;
std::string _token;
std::shared_ptr<Variables> _variables;
std::shared_ptr<Symbol> _symbol;
std::vector<Node> _nodes;
std::size_t _hash;
Node() = delete;
explicit Node(
const std::shared_ptr<Lexer>& _lexer,
const std::string& token,
const std::shared_ptr<Variables>& variables,
const std::shared_ptr<Symbol>& symbol,
std::vector<Node>&& nodes,
std::size_t hash
) :
_lexer{_lexer},
_token{token},
_variables{variables},
_symbol{symbol},
_nodes{std::move(nodes)},
_hash{hash}
{
if (_nodes.size() != _symbol->arguments())
throw ArgumentsMismatch{
_token,
_nodes.size(),
_symbol->arguments()
};
}
std::vector<std::string> _pruned() const noexcept {
std::istringstream extractor{postfix()};
std::vector<std::string> tokens{
std::istream_iterator<std::string>{extractor},
std::istream_iterator<std::string>{}
};
std::vector<std::string> pruned{};
for (const auto& variable : variables())
if (
std::find(tokens.begin(), tokens.end(), variable) !=
tokens.end()
)
pruned.push_back(variable);
pruned.erase(std::unique(pruned.begin(), pruned.end()), pruned.end());
return pruned;
}
void _rebind(const std::shared_ptr<Variables>& context) noexcept {
_variables = context;
for (auto& node : _nodes)
node._rebind(context);
}
public:
Node(const Node& other) noexcept :
_lexer{other._lexer},
_token{other._token},
_variables{},
_symbol{other._symbol},
_nodes{other._nodes},
_hash{other._hash}
{ _rebind(std::make_shared<Variables>(_lexer, other._pruned())); }
Node(Node&& other) noexcept :
_lexer{std::move(other._lexer)},
_token{std::move(other._token)},
_variables{std::move(other._variables)},
_symbol{std::move(other._symbol)},
_nodes{std::move(other._nodes)},
_hash{std::move(other._hash)}
{}
const Node& operator=(Node other) noexcept {
swap(*this, other);
return *this;
}
friend void swap(Node& one, Node& another) noexcept {
using std::swap;
swap(one._lexer, another._lexer);
swap(one._token, another._token);
swap(one._variables, another._variables);
swap(one._symbol, another._symbol);
swap(one._nodes, another._nodes);
}
std::shared_ptr<Lexer> lexer() const noexcept { return _lexer; }
static Type evaluate(const Node& node) {
return node._symbol->evaluate(node._nodes);
}
explicit operator Type() const {
if (variables().size() > 0)
throw ArgumentsMismatch{variables().size(), 0};
return _symbol->evaluate(_nodes);
}
Type operator()(const std::vector<Type>& values) const {
_variables->update(values);
return _symbol->evaluate(_nodes);
}
template<typename... Args>
Type operator()(Args&&... args) const {
_variables->update(std::forward<Args>(args)...);
return _symbol->evaluate(_nodes);
}
bool operator==(const Node& other) const noexcept {
std::stack<std::pair<const_iterator, const_iterator>> these{};
std::stack<const_iterator> those{};
auto equal = [&](auto left, auto right) {
try {
return
left->_variables->index(left->_token) ==
right->_variables->index(right->_token);
}
catch (const UndefinedSymbol&) {
if (left->_symbol == right->_symbol)
return true;
return *(left->_symbol) == *(right->_symbol);
}
};
if (!equal(this, &other))
return false;
these.push({this->begin(), this->end()});
those.push(other.begin());
while(!these.empty()) {
auto one = these.top();
auto another = those.top();
these.pop();
those.pop();
if (one.first != one.second) {
if (!equal(one.first, another))
return false;
these.push({one.first->begin(), one.first->end()});
these.push({one.first + 1, one.second});
those.push(another->begin());
those.push(another + 1);
}
}
return true;
}
const Node& operator[](std::size_t index) const { return _nodes[index]; }
const Node& at(std::size_t index) const { return _nodes.at(index); }
const_iterator begin() const noexcept { return _nodes.begin(); }
const_iterator end() const noexcept { return _nodes.end(); }
friend std::ostream& operator<<(
std::ostream& ostream,
const Node& node
) noexcept {
ostream << node.infix();
return ostream;
}
const std::string& token() const noexcept { return _token; }
std::size_t branches() const noexcept { return _nodes.size(); }
std::string infix() const noexcept {
using Operator = Operator<Node>;
using Associativity = typename Operator::Associativity;
std::string infix{};
auto brace = [&](std::size_t i) {
const auto& node = _nodes[i];
if (node._symbol->symbol() == SymbolType::OPERATOR) {
auto po = static_cast<Operator*>(_symbol.get());
auto co = static_cast<Operator*>(node._symbol.get());
auto pp = po->precedence();
auto cp = co->precedence();
auto pa = !i ?
po->associativity() != Associativity::RIGHT :
po->associativity() != Associativity::LEFT;
if ((pa && cp < pp) || (!pa && cp <= pp))
return _lexer->left + node.infix() + _lexer->right;
}
return node.infix();
};
switch (_symbol->symbol()) {
case (SymbolType::FUNCTION):
infix += _token + _lexer->left;
for (const auto& node : _nodes)
infix += node.infix() + _lexer->separator;
infix.back() = _lexer->right.front();
return infix;
case (SymbolType::OPERATOR):
infix += brace(0) + _token + brace(1);
return infix;
default:
return _token;
}
}
std::string postfix() const noexcept {
std::string postfix{};
for (const auto& node : _nodes)
postfix += node.postfix() + " ";
return postfix + _token;
}
std::vector<std::string> variables() const noexcept {
return _variables->variables;
}
};
}
namespace std {
template<typename Parser>
struct hash<calculate::Node<Parser>> {
size_t operator()(const calculate::Node<Parser>& node) const {
return node._hash;
}
};
}
#endif
<|endoftext|> |
<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <exception>
#include <string>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "ngsi/Request.h"
#include "ngsi/ParseData.h"
#include "jsonParse/JsonNode.h"
#include "jsonParse/jsonParse.h"
#include "jsonParse/jsonRequest.h"
#include "jsonParse/jsonRegisterContextRequest.h"
#include "jsonParse/jsonDiscoverContextAvailabilityRequest.h"
#include "jsonParse/jsonSubscribeContextAvailabilityRequest.h"
#include "jsonParse/jsonNotifyContextAvailabilityRequest.h"
#include "jsonParse/jsonUnsubscribeContextAvailabilityRequest.h"
#include "jsonParse/jsonUpdateContextAvailabilitySubscriptionRequest.h"
#include "jsonParse/jsonQueryContextRequest.h"
#include "jsonParse/jsonUpdateContextRequest.h"
#include "jsonParse/jsonSubscribeContextRequest.h"
#include "jsonParse/jsonUnsubscribeContextRequest.h"
#include "jsonParse/jsonNotifyContextRequest.h"
#include "jsonParse/jsonUpdateContextSubscriptionRequest.h"
#include "jsonParse/jsonRegisterProviderRequest.h"
#include "jsonParse/jsonUpdateContextElementRequest.h"
#include "jsonParse/jsonAppendContextElementRequest.h"
#include "jsonParse/jsonUpdateContextAttributeRequest.h"
#include "rest/restReply.h"
/* ****************************************************************************
*
* jsonRequest -
*/
static JsonRequest jsonRequest[] =
{
// NGSI9
{ RegisterContext, "POST", "registerContextRequest", jsonRcrParseVector, jsonRcrInit, jsonRcrCheck, jsonRcrPresent, jsonRcrRelease },
{ DiscoverContextAvailability, "POST", "discoverContextAvailabilityRequest", jsonDcarParseVector, jsonDcarInit, jsonDcarCheck, jsonDcarPresent, jsonDcarRelease },
{ SubscribeContextAvailability, "POST", "subscribeContextAvailabilityRequest", jsonScarParseVector, jsonScarInit, jsonScarCheck, jsonScarPresent, jsonScarRelease },
{ UnsubscribeContextAvailability, "POST", "unsubscribeContextAvailabilityRequest", jsonUcarParseVector, jsonUcarInit, jsonUcarCheck, jsonUcarPresent, jsonUcarRelease },
{ NotifyContextAvailability, "POST", "notifyContextRequestAvailability", jsonNcarParseVector, jsonNcarInit, jsonNcarCheck, jsonNcarPresent, jsonNcarRelease },
{ UpdateContextAvailabilitySubscription, "POST", "updateContextAvailabilitySubscriptionRequest", jsonUcasParseVector, jsonUcasInit, jsonUcasCheck, jsonUcasPresent, jsonUcasRelease },
// NGSI10
{ QueryContext, "POST", "queryContextRequest", jsonQcrParseVector, jsonQcrInit, jsonQcrCheck, jsonQcrPresent, jsonQcrRelease },
{ UpdateContext, "POST", "updateContextRequest", jsonUpcrParseVector, jsonUpcrInit, jsonUpcrCheck, jsonUpcrPresent, jsonUpcrRelease },
{ SubscribeContext, "POST", "subscribeContextRequest", jsonScrParseVector, jsonScrInit, jsonScrCheck, jsonScrPresent, jsonScrRelease },
{ NotifyContext, "POST", "notifyContextRequest", jsonNcrParseVector, jsonNcrInit, jsonNcrCheck, jsonNcrPresent, jsonNcrRelease },
{ UnsubscribeContext, "POST", "unsubscribeContextRequest", jsonUncrParseVector, jsonUncrInit, jsonUncrCheck, jsonUncrPresent, jsonUncrRelease },
{ UpdateContextSubscription, "POST", "updateContextSubscriptionRequest", jsonUcsrParseVector, jsonUcsrInit, jsonUcsrCheck, jsonUcsrPresent, jsonUcsrRelease },
// Convenience NGSI9
{ ContextEntitiesByEntityId, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ EntityByIdAttributeByName, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ ContextEntityTypes, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ ContextEntityTypeAttribute, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ Ngsi9SubscriptionsConvOp, "PUT", "updateContextAvailabilitySubscriptionRequest", jsonUcasParseVector, jsonUcasInit, jsonUcasCheck, jsonUcasPresent, jsonUcasRelease },
// Convenience NGSI10
{ IndividualContextEntity, "PUT", "updateContextElementRequest", jsonUcerParseVector, jsonUcerInit, jsonUcerCheck, jsonUcerPresent, jsonUcerRelease },
{ IndividualContextEntity, "POST", "appendContextElementRequest", jsonAcerParseVector, jsonAcerInit, jsonAcerCheck, jsonAcerPresent, jsonAcerRelease },
{ IndividualContextEntityAttribute, "POST", "updateContextAttributeRequest", jsonUpcarParseVector,jsonUpcarInit,jsonUpcarCheck, jsonUpcarPresent,jsonUpcarRelease},
{ IndividualContextEntityAttributes, "POST", "appendContextElementRequest", jsonAcerParseVector, jsonAcerInit, jsonAcerCheck, jsonAcerPresent, jsonAcerRelease },
{ IndividualContextEntityAttributes, "PUT", "updateContextElementRequest", jsonUcerParseVector, jsonUcerInit, jsonUcerCheck, jsonUcerPresent, jsonUcerRelease },
{ AttributeValueInstance, "PUT", "updateContextAttributeRequest", jsonUpcarParseVector,jsonUpcarInit,jsonUpcarCheck, jsonUpcarPresent,jsonUpcarRelease},
{ Ngsi10SubscriptionsConvOp, "PUT", "updateContextSubscriptionRequest", jsonUcsrParseVector, jsonUcsrInit, jsonUcsrCheck, jsonUcsrPresent, jsonUcsrRelease }
};
/* ****************************************************************************
*
* jsonRequestGet -
*/
static JsonRequest* jsonRequestGet(RequestType request, std::string method)
{
for (unsigned int ix = 0; ix < sizeof(jsonRequest) / sizeof(jsonRequest[0]); ++ix)
{
if ((request == jsonRequest[ix].type) && (jsonRequest[ix].method == method))
{
if (jsonRequest[ix].parseVector != NULL)
LM_V2(("Found xmlRequest of type %d, method '%s' - index %d (%s)", request, method.c_str(), ix, jsonRequest[ix].parseVector[0].path.c_str()));
return &jsonRequest[ix];
}
}
LM_E(("No request found for RequestType '%s', method '%s'", requestType(request), method.c_str()));
return NULL;
}
/* ****************************************************************************
*
* jsonTreat -
*/
std::string jsonTreat(const char* content, ConnectionInfo* ciP, ParseData* parseDataP, RequestType request, std::string payloadWord, JsonRequest** reqPP)
{
std::string res = "OK";
JsonRequest* reqP = jsonRequestGet(request, ciP->method);
LM_T(LmtParse, ("Treating a JSON request: '%s'", content));
if (reqP == NULL)
{
std::string errorReply = restErrorReplyGet(ciP, ciP->outFormat, "", requestType(request), SccBadRequest,
std::string("Sorry, no request treating object found for RequestType '") + requestType(request) + "'");
LM_RE(errorReply, ("Sorry, no request treating object found for RequestType %d (%s)", request, requestType(request)));
}
LM_T(LmtParse, ("Treating '%s' request", reqP->keyword.c_str()));
reqP->init(parseDataP);
try
{
jsonParse(content, reqP->keyword, reqP->parseVector, parseDataP);
}
catch (std::exception &e)
{
res = std::string("JSON parse error: ") + e.what();
std::string errorReply = restErrorReplyGet(ciP, ciP->outFormat, "", reqP->keyword, SccBadRequest, std::string("JSON Parse Error: ") + res);
LM_E(("JSON Parse Error: '%s'", e.what()));
LM_RE(errorReply, (res.c_str()));
}
reqP->present(parseDataP);
res = reqP->check(parseDataP, ciP);
reqP->present(parseDataP);
if (reqPP != NULL)
*reqPP = reqP;
return res;
}
<commit_msg>Typo fixed<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <exception>
#include <string>
#include "logMsg/logMsg.h"
#include "logMsg/traceLevels.h"
#include "ngsi/Request.h"
#include "ngsi/ParseData.h"
#include "jsonParse/JsonNode.h"
#include "jsonParse/jsonParse.h"
#include "jsonParse/jsonRequest.h"
#include "jsonParse/jsonRegisterContextRequest.h"
#include "jsonParse/jsonDiscoverContextAvailabilityRequest.h"
#include "jsonParse/jsonSubscribeContextAvailabilityRequest.h"
#include "jsonParse/jsonNotifyContextAvailabilityRequest.h"
#include "jsonParse/jsonUnsubscribeContextAvailabilityRequest.h"
#include "jsonParse/jsonUpdateContextAvailabilitySubscriptionRequest.h"
#include "jsonParse/jsonQueryContextRequest.h"
#include "jsonParse/jsonUpdateContextRequest.h"
#include "jsonParse/jsonSubscribeContextRequest.h"
#include "jsonParse/jsonUnsubscribeContextRequest.h"
#include "jsonParse/jsonNotifyContextRequest.h"
#include "jsonParse/jsonUpdateContextSubscriptionRequest.h"
#include "jsonParse/jsonRegisterProviderRequest.h"
#include "jsonParse/jsonUpdateContextElementRequest.h"
#include "jsonParse/jsonAppendContextElementRequest.h"
#include "jsonParse/jsonUpdateContextAttributeRequest.h"
#include "rest/restReply.h"
/* ****************************************************************************
*
* jsonRequest -
*/
static JsonRequest jsonRequest[] =
{
// NGSI9
{ RegisterContext, "POST", "registerContextRequest", jsonRcrParseVector, jsonRcrInit, jsonRcrCheck, jsonRcrPresent, jsonRcrRelease },
{ DiscoverContextAvailability, "POST", "discoverContextAvailabilityRequest", jsonDcarParseVector, jsonDcarInit, jsonDcarCheck, jsonDcarPresent, jsonDcarRelease },
{ SubscribeContextAvailability, "POST", "subscribeContextAvailabilityRequest", jsonScarParseVector, jsonScarInit, jsonScarCheck, jsonScarPresent, jsonScarRelease },
{ UnsubscribeContextAvailability, "POST", "unsubscribeContextAvailabilityRequest", jsonUcarParseVector, jsonUcarInit, jsonUcarCheck, jsonUcarPresent, jsonUcarRelease },
{ NotifyContextAvailability, "POST", "notifyContextRequestAvailability", jsonNcarParseVector, jsonNcarInit, jsonNcarCheck, jsonNcarPresent, jsonNcarRelease },
{ UpdateContextAvailabilitySubscription, "POST", "updateContextAvailabilitySubscriptionRequest", jsonUcasParseVector, jsonUcasInit, jsonUcasCheck, jsonUcasPresent, jsonUcasRelease },
// NGSI10
{ QueryContext, "POST", "queryContextRequest", jsonQcrParseVector, jsonQcrInit, jsonQcrCheck, jsonQcrPresent, jsonQcrRelease },
{ UpdateContext, "POST", "updateContextRequest", jsonUpcrParseVector, jsonUpcrInit, jsonUpcrCheck, jsonUpcrPresent, jsonUpcrRelease },
{ SubscribeContext, "POST", "subscribeContextRequest", jsonScrParseVector, jsonScrInit, jsonScrCheck, jsonScrPresent, jsonScrRelease },
{ NotifyContext, "POST", "notifyContextRequest", jsonNcrParseVector, jsonNcrInit, jsonNcrCheck, jsonNcrPresent, jsonNcrRelease },
{ UnsubscribeContext, "POST", "unsubscribeContextRequest", jsonUncrParseVector, jsonUncrInit, jsonUncrCheck, jsonUncrPresent, jsonUncrRelease },
{ UpdateContextSubscription, "POST", "updateContextSubscriptionRequest", jsonUcsrParseVector, jsonUcsrInit, jsonUcsrCheck, jsonUcsrPresent, jsonUcsrRelease },
// Convenience NGSI9
{ ContextEntitiesByEntityId, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ EntityByIdAttributeByName, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ ContextEntityTypes, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ ContextEntityTypeAttribute, "POST", "registerProviderRequest", jsonRprParseVector, jsonRprInit, jsonRprCheck, jsonRprPresent, jsonRprRelease },
{ Ngsi9SubscriptionsConvOp, "PUT", "updateContextAvailabilitySubscriptionRequest", jsonUcasParseVector, jsonUcasInit, jsonUcasCheck, jsonUcasPresent, jsonUcasRelease },
// Convenience NGSI10
{ IndividualContextEntity, "PUT", "updateContextElementRequest", jsonUcerParseVector, jsonUcerInit, jsonUcerCheck, jsonUcerPresent, jsonUcerRelease },
{ IndividualContextEntity, "POST", "appendContextElementRequest", jsonAcerParseVector, jsonAcerInit, jsonAcerCheck, jsonAcerPresent, jsonAcerRelease },
{ IndividualContextEntityAttribute, "POST", "updateContextAttributeRequest", jsonUpcarParseVector,jsonUpcarInit,jsonUpcarCheck, jsonUpcarPresent,jsonUpcarRelease},
{ IndividualContextEntityAttributes, "POST", "appendContextElementRequest", jsonAcerParseVector, jsonAcerInit, jsonAcerCheck, jsonAcerPresent, jsonAcerRelease },
{ IndividualContextEntityAttributes, "PUT", "updateContextElementRequest", jsonUcerParseVector, jsonUcerInit, jsonUcerCheck, jsonUcerPresent, jsonUcerRelease },
{ AttributeValueInstance, "PUT", "updateContextAttributeRequest", jsonUpcarParseVector,jsonUpcarInit,jsonUpcarCheck, jsonUpcarPresent,jsonUpcarRelease},
{ Ngsi10SubscriptionsConvOp, "PUT", "updateContextSubscriptionRequest", jsonUcsrParseVector, jsonUcsrInit, jsonUcsrCheck, jsonUcsrPresent, jsonUcsrRelease }
};
/* ****************************************************************************
*
* jsonRequestGet -
*/
static JsonRequest* jsonRequestGet(RequestType request, std::string method)
{
for (unsigned int ix = 0; ix < sizeof(jsonRequest) / sizeof(jsonRequest[0]); ++ix)
{
if ((request == jsonRequest[ix].type) && (jsonRequest[ix].method == method))
{
if (jsonRequest[ix].parseVector != NULL)
LM_V2(("Found jsonRequest of type %d, method '%s' - index %d (%s)", request, method.c_str(), ix, jsonRequest[ix].parseVector[0].path.c_str()));
return &jsonRequest[ix];
}
}
LM_E(("No request found for RequestType '%s', method '%s'", requestType(request), method.c_str()));
return NULL;
}
/* ****************************************************************************
*
* jsonTreat -
*/
std::string jsonTreat(const char* content, ConnectionInfo* ciP, ParseData* parseDataP, RequestType request, std::string payloadWord, JsonRequest** reqPP)
{
std::string res = "OK";
JsonRequest* reqP = jsonRequestGet(request, ciP->method);
LM_T(LmtParse, ("Treating a JSON request: '%s'", content));
if (reqP == NULL)
{
std::string errorReply = restErrorReplyGet(ciP, ciP->outFormat, "", requestType(request), SccBadRequest,
std::string("Sorry, no request treating object found for RequestType '") + requestType(request) + "'");
LM_RE(errorReply, ("Sorry, no request treating object found for RequestType %d (%s)", request, requestType(request)));
}
LM_T(LmtParse, ("Treating '%s' request", reqP->keyword.c_str()));
reqP->init(parseDataP);
try
{
jsonParse(content, reqP->keyword, reqP->parseVector, parseDataP);
}
catch (std::exception &e)
{
res = std::string("JSON parse error: ") + e.what();
std::string errorReply = restErrorReplyGet(ciP, ciP->outFormat, "", reqP->keyword, SccBadRequest, std::string("JSON Parse Error: ") + res);
LM_E(("JSON Parse Error: '%s'", e.what()));
LM_RE(errorReply, (res.c_str()));
}
reqP->present(parseDataP);
res = reqP->check(parseDataP, ciP);
reqP->present(parseDataP);
if (reqPP != NULL)
*reqPP = reqP;
return res;
}
<|endoftext|> |
<commit_before>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. */
/* See the License for the specific language governing permissions */
/* and limitations under the License. */
/**********************************************************************/
#ifndef TCC_GRAPH_FLOW_ARC_DEFINED
#define TCC_GRAPH_FLOW_ARC_DEFINED
// Default libraries
#include <iomanip>
// Libraries
#include "Vertex.tcc"
#include "graph/Arc.tcc"
#include "Properties.tcc"
namespace graph {
namespace flow
{
template<
typename Properties = graph::no_property,
typename Cost = unsigned int,
typename Flux = unsigned int,
typename Capacity = unsigned int,
typename Requirement = unsigned int
>struct Arc_flow
{
Cost cost;
Flux flux;
Capacity capacity;
Requirement requirement;
Properties properties;
Arc_flow(
Cost k = Cost{}, Flux f = Flux{}, Capacity c = Capacity{},
Requirement r = Requirement{}, Properties p = Properties{})
: cost{k}, flux{f}, capacity{c},
requirement{r}, properties{p} {}
bool operator==(const Arc_flow& f) const
{
return this->cost == f.cost
&& this->flux == f.flux
&& this->capacity == f.capacity
&& this->requirement == f.requirement
&& this->properties == f.properties;
}
bool operator!=(const Arc_flow& f) const
{
return !operator==(f);
}
friend std::ostream&
operator<<(std::ostream& os, const Arc_flow& f)
{
os << "{ ";
os << "cost:" << f.cost;
os << "flux:" << f.flux;
if(f.capacity) os << ", capacity:" << f.capacity;
if(f.flux) os << ", requirement:" << f.flux;
os << ", properties:" << f.properties;
os << " }";
return os;
}
};
template<
typename Vertex = graph::flow::Vertex<>::type,
typename Properties = graph::no_property,
typename Directed = graph::directed
>struct Arc
{ typedef graph::Arc<Vertex,Arc_flow<Properties>,Directed> type; };
}}
#endif
<commit_msg>Correcting minor typo when printing flux<commit_after>/**********************************************************************/
/* Copyright 2014 RCF */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); */
/* you may not use this file except in compliance with the License. */
/* You may obtain a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, */
/* software distributed under the License is distributed on an */
/* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, */
/* either express or implied. */
/* See the License for the specific language governing permissions */
/* and limitations under the License. */
/**********************************************************************/
#ifndef TCC_GRAPH_FLOW_ARC_DEFINED
#define TCC_GRAPH_FLOW_ARC_DEFINED
// Default libraries
#include <iomanip>
// Libraries
#include "Vertex.tcc"
#include "graph/Arc.tcc"
#include "Properties.tcc"
namespace graph {
namespace flow
{
template<
typename Properties = graph::no_property,
typename Cost = unsigned int,
typename Flux = unsigned int,
typename Capacity = unsigned int,
typename Requirement = unsigned int
>struct Arc_flow
{
Cost cost;
Flux flux;
Capacity capacity;
Requirement requirement;
Properties properties;
Arc_flow(
Cost k = Cost{}, Flux f = Flux{}, Capacity c = Capacity{},
Requirement r = Requirement{}, Properties p = Properties{})
: cost{k}, flux{f}, capacity{c},
requirement{r}, properties{p} {}
bool operator==(const Arc_flow& f) const
{
return this->cost == f.cost
&& this->flux == f.flux
&& this->capacity == f.capacity
&& this->requirement == f.requirement
&& this->properties == f.properties;
}
bool operator!=(const Arc_flow& f) const
{
return !operator==(f);
}
friend std::ostream&
operator<<(std::ostream& os, const Arc_flow& f)
{
os << "{ ";
os << "cost:" << f.cost;
os << ", flux:" << f.flux;
if(f.capacity) os << ", capacity:" << f.capacity;
if(f.flux) os << ", requirement:" << f.flux;
os << ", properties:" << f.properties;
os << " }";
return os;
}
};
template<
typename Vertex = graph::flow::Vertex<>::type,
typename Properties = graph::no_property,
typename Directed = graph::directed
>struct Arc
{ typedef graph::Arc<Vertex,Arc_flow<Properties>,Directed> type; };
}}
#endif
<|endoftext|> |
<commit_before>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef UNICODE_HPP
#define UNICODE_HPP
#include <string>
#include <boost/utility.hpp>
#ifdef USE_FRIBIDI
#include <fribidi/fribidi.h>
#endif
#include <iconv.h>
namespace mapnik {
/*
** Use FRIBIDI to encode the string.
** The return value must be freed by the caller.
*/
#ifdef USE_FRIBIDI
inline wchar_t* bidi_string(const wchar_t *logical)
{
FriBidiCharType base = FRIBIDI_TYPE_ON;
size_t len;
len = wcslen(logical);
FriBidiChar *visual;
FriBidiStrIndex *ltov, *vtol;
FriBidiLevel *levels;
FriBidiStrIndex new_len;
fribidi_boolean log2vis;
visual = (FriBidiChar *) malloc (sizeof (FriBidiChar) * (len + 1));
ltov = 0;
vtol = 0;
levels = 0;
/* Create a bidi string. */
log2vis = fribidi_log2vis ((FriBidiChar *)logical, len, &base,
/* output */
visual, ltov, vtol, levels);
if (!log2vis) {
return 0;
}
new_len = len;
return (wchar_t *)visual;
}
#endif
inline std::wstring to_unicode(std::string const& text)
{
std::wstring out;
unsigned long code = 0;
int expect = 0;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
if ( p >= 0xc0)
{
if ( p < 0xe0) // U+0080 - U+07ff
{
expect = 1;
code = p & 0x1f;
}
else if ( p < 0xf0) // U+0800 - U+ffff
{
expect = 2;
code = p & 0x0f;
}
else if ( p < 0xf8) // U+1000 - U+10ffff
{
expect = 3;
code = p & 0x07;
}
continue;
}
else if (p >= 0x80)
{
--expect;
if (expect >= 0)
{
code <<= 6;
code += p & 0x3f;
}
if (expect > 0)
continue;
expect = 0;
}
else
{
code = p; // U+0000 - U+007f (ascii)
}
out.push_back(wchar_t(code));
}
#ifdef USE_FRIBIDI
wchar_t *bidi_text = bidi_string(out.c_str());
out = bidi_text;
free(bidi_text);
#endif
return out;
}
inline std::wstring latin1_to_unicode(std::string const& text)
{
std::wstring out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
out.push_back(wchar_t(p));
}
return out;
}
inline std::string latin1_to_unicode2(std::string const& text)
{
std::string out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
out.push_back(0x00);
out.push_back(*itr++);
}
return out;
}
class transcoder : private boost::noncopyable
{
public:
explicit transcoder (std::string const& encoding)
{
//desc_ = iconv_open("UCS-2",encoding.c_str());
}
std::wstring transcode(std::string const& input) const
{
//return to_unicode(input);
return to_unicode(input);
/*
std::string buf(input.size() * 2,0);
size_t inleft = input.size();
const char * in = input.data();
size_t outleft = buf.size();
char * out = const_cast<char*>(buf.data());
iconv(desc_,&in,&inleft,&out,&outleft);
std::string::const_iterator itr = buf.begin();
std::string::const_iterator end = buf.end();
wchar_t wch = 0;
bool state = false;
std::wstring unicode;
size_t num_char = buf.size() - outleft;
for ( ; itr != end; ++itr)
{
if (!state)
{
wch = (*itr & 0xff);
state = true;
}
else
{
wch |= *itr << 8 ;
unicode.push_back(wchar_t(wch));
state = false;
}
if (!num_char--) break;
}
#ifdef USE_FRIBIDI
if (unicode.length() > 0)
{
wchar_t *bidi_text = bidi_string(unicode.c_str());
unicode = bidi_text;
free(bidi_text);
}
#endif
return unicode;
*/
}
~transcoder()
{
//iconv_close(desc_);
}
private:
iconv_t desc_;
};
}
#endif // UNICODE_HPP
<commit_msg>applied patch from jonb to use calloc instead of malloc (allocating fribidi buffer)<commit_after>/*****************************************************************************
*
* This file is part of Mapnik (c++ mapping toolkit)
*
* Copyright (C) 2006 Artem Pavlenko
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*****************************************************************************/
//$Id$
#ifndef UNICODE_HPP
#define UNICODE_HPP
#include <string>
#include <boost/utility.hpp>
#ifdef USE_FRIBIDI
#include <fribidi/fribidi.h>
#endif
#include <iconv.h>
namespace mapnik {
/*
** Use FRIBIDI to encode the string.
** The return value must be freed by the caller.
*/
#ifdef USE_FRIBIDI
inline wchar_t* bidi_string(const wchar_t *logical)
{
FriBidiCharType base = FRIBIDI_TYPE_ON;
size_t len;
len = wcslen(logical);
FriBidiChar *visual;
FriBidiStrIndex *ltov, *vtol;
FriBidiLevel *levels;
FriBidiStrIndex new_len;
fribidi_boolean log2vis;
visual = (FriBidiChar *) calloc (sizeof (FriBidiChar), len + 1);
ltov = 0;
vtol = 0;
levels = 0;
/* Create a bidi string. */
log2vis = fribidi_log2vis ((FriBidiChar *)logical, len, &base,
/* output */
visual, ltov, vtol, levels);
if (!log2vis) {
return 0;
}
new_len = len;
return (wchar_t *)visual;
}
#endif
inline std::wstring to_unicode(std::string const& text)
{
std::wstring out;
unsigned long code = 0;
int expect = 0;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
if ( p >= 0xc0)
{
if ( p < 0xe0) // U+0080 - U+07ff
{
expect = 1;
code = p & 0x1f;
}
else if ( p < 0xf0) // U+0800 - U+ffff
{
expect = 2;
code = p & 0x0f;
}
else if ( p < 0xf8) // U+1000 - U+10ffff
{
expect = 3;
code = p & 0x07;
}
continue;
}
else if (p >= 0x80)
{
--expect;
if (expect >= 0)
{
code <<= 6;
code += p & 0x3f;
}
if (expect > 0)
continue;
expect = 0;
}
else
{
code = p; // U+0000 - U+007f (ascii)
}
out.push_back(wchar_t(code));
}
#ifdef USE_FRIBIDI
wchar_t *bidi_text = bidi_string(out.c_str());
out = bidi_text;
free(bidi_text);
#endif
return out;
}
inline std::wstring latin1_to_unicode(std::string const& text)
{
std::wstring out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
unsigned p = (*itr++) & 0xff;
out.push_back(wchar_t(p));
}
return out;
}
inline std::string latin1_to_unicode2(std::string const& text)
{
std::string out;
std::string::const_iterator itr=text.begin();
std::string::const_iterator end=text.end();
while ( itr != end)
{
out.push_back(0x00);
out.push_back(*itr++);
}
return out;
}
class transcoder : private boost::noncopyable
{
public:
explicit transcoder (std::string const& encoding)
{
//desc_ = iconv_open("UCS-2",encoding.c_str());
}
std::wstring transcode(std::string const& input) const
{
//return to_unicode(input);
return to_unicode(input);
/*
std::string buf(input.size() * 2,0);
size_t inleft = input.size();
const char * in = input.data();
size_t outleft = buf.size();
char * out = const_cast<char*>(buf.data());
iconv(desc_,&in,&inleft,&out,&outleft);
std::string::const_iterator itr = buf.begin();
std::string::const_iterator end = buf.end();
wchar_t wch = 0;
bool state = false;
std::wstring unicode;
size_t num_char = buf.size() - outleft;
for ( ; itr != end; ++itr)
{
if (!state)
{
wch = (*itr & 0xff);
state = true;
}
else
{
wch |= *itr << 8 ;
unicode.push_back(wchar_t(wch));
state = false;
}
if (!num_char--) break;
}
#ifdef USE_FRIBIDI
if (unicode.length() > 0)
{
wchar_t *bidi_text = bidi_string(unicode.c_str());
unicode = bidi_text;
free(bidi_text);
}
#endif
return unicode;
*/
}
~transcoder()
{
//iconv_close(desc_);
}
private:
iconv_t desc_;
};
}
#endif // UNICODE_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Sony Corporation. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** Exception throwing utilities.
*/
#ifndef __NBLA_EXCEPTION_HPP__
#define __NBLA_EXCEPTION_HPP__
#if defined(_MSC_VER)
///< definition of __func__
#define __func__ __FUNCTION__
#endif
#include <nbla/defs.hpp>
#include <cstdio>
#include <stdexcept>
#include <string>
#include <vector>
namespace nbla {
using std::string;
using std::snprintf;
using std::vector;
/** In NNabla, exceptions are thrown through this macro. Error codes are
defined in enum class nbla::error_code. See also NBLA_CHECK.
Example: `NBLA_ERROR(error_code::cuda_error, "Error size %d", size);`
*/
#define NBLA_ERROR(code, msg, ...) \
throw Exception(code, format_string(msg, ##__VA_ARGS__), __func__, __FILE__, \
__LINE__);
/** You can check whether the specified condition is met, or raise error with
specified message.
Example: `NBLA_CHECK(size == 2,
error_code::cuda_error, "Error size %d", size);`
*/
#define NBLA_CHECK(condition, code, msg, ...) \
if (!(condition)) { \
NBLA_ERROR(code, string("Failed `" #condition "`: ") + msg, \
##__VA_ARGS__); \
}
/** Enum of error codes throwing in NNabla
Note: Developers must add a line `CASE_ERROR_STRING({code name});` into
get_error_string function in src/nbla/exception.cpp, if a new code is added.
*/
enum class error_code {
unclassified,
not_implemented,
value,
type,
memory,
io,
os,
target_specific,
target_specific_async
};
string get_error_string(error_code code);
/** Exception class of NNabla
Error codes are enumerated in enum class error_code you can find above.
It is not expected that developers/users throw this exception directly.
Instead, use NBLA_ERROR macro.
*/
// https://github.com/Itseez/opencv/blob/c3ad8af42a85a3d03c6dd5727c8b5f4f7585d1d2/modules/core/src/system.cpp
// https://github.com/Itseez/opencv/blob/9aeb8c8d5a35bf7ed5208459d46fdb6822c5692c/modules/core/include/opencv2/core/base.hpp
// https://github.com/Itseez/opencv/blob/b2d44663fdd90e4c50d4a06435492b5cb0f1021d/modules/core/include/opencv2/core.hpp
class NBLA_API Exception : public std::exception {
protected:
error_code code_; ///< error code
string full_msg_; ///< Buffer of full message to be shown
string msg_; ///< error message
string func_; ///< function name
string file_; ///< file name
int line_; ///< line no.
public:
Exception(error_code code, const string &msg, const string &func,
const string &file, int line);
virtual ~Exception() throw();
virtual const char *what() const throw();
};
/** String formatter.
TODO: Remove warning. Maybe a bit tricky.
*/
template <typename T, typename... Args>
string format_string(const string &format, T first, Args... rest) {
int size = snprintf(nullptr, 0, format.c_str(), first, rest...);
vector<char> buffer(size + 1);
snprintf(buffer.data(), size + 1, format.c_str(), first, rest...);
return string(buffer.data(), buffer.data() + size);
}
/** String formatter without format.
*/
inline string format_string(const string &format) {
for (auto itr = format.begin(); itr != format.end(); itr++) {
if (*itr == '%') {
if (*(itr + 1) == '%') {
itr++;
} else {
NBLA_ERROR(error_code::unclassified, "Invalid format string %s",
format.c_str());
}
}
}
return format;
}
}
#endif
<commit_msg>Eliminate the null destination pointer [-Wformat-truncation=] warning.<commit_after>// Copyright (c) 2017 Sony Corporation. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/** Exception throwing utilities.
*/
#ifndef __NBLA_EXCEPTION_HPP__
#define __NBLA_EXCEPTION_HPP__
#if defined(_MSC_VER)
///< definition of __func__
#define __func__ __FUNCTION__
#endif
#include <nbla/defs.hpp>
#include <cstdio>
#include <cstdlib>
#include <stdexcept>
#include <string>
#include <vector>
namespace nbla {
using std::string;
using std::snprintf;
using std::vector;
/** In NNabla, exceptions are thrown through this macro. Error codes are
defined in enum class nbla::error_code. See also NBLA_CHECK.
Example: `NBLA_ERROR(error_code::cuda_error, "Error size %d", size);`
*/
#define NBLA_ERROR(code, msg, ...) \
throw Exception(code, format_string(msg, ##__VA_ARGS__), __func__, __FILE__, \
__LINE__);
/** You can check whether the specified condition is met, or raise error with
specified message.
Example: `NBLA_CHECK(size == 2,
error_code::cuda_error, "Error size %d", size);`
*/
#define NBLA_CHECK(condition, code, msg, ...) \
if (!(condition)) { \
NBLA_ERROR(code, string("Failed `" #condition "`: ") + msg, \
##__VA_ARGS__); \
}
/** Enum of error codes throwing in NNabla
Note: Developers must add a line `CASE_ERROR_STRING({code name});` into
get_error_string function in src/nbla/exception.cpp, if a new code is added.
*/
enum class error_code {
unclassified,
not_implemented,
value,
type,
memory,
io,
os,
target_specific,
target_specific_async
};
string get_error_string(error_code code);
/** Exception class of NNabla
Error codes are enumerated in enum class error_code you can find above.
It is not expected that developers/users throw this exception directly.
Instead, use NBLA_ERROR macro.
*/
// https://github.com/Itseez/opencv/blob/c3ad8af42a85a3d03c6dd5727c8b5f4f7585d1d2/modules/core/src/system.cpp
// https://github.com/Itseez/opencv/blob/9aeb8c8d5a35bf7ed5208459d46fdb6822c5692c/modules/core/include/opencv2/core/base.hpp
// https://github.com/Itseez/opencv/blob/b2d44663fdd90e4c50d4a06435492b5cb0f1021d/modules/core/include/opencv2/core.hpp
class NBLA_API Exception : public std::exception {
protected:
error_code code_; ///< error code
string full_msg_; ///< Buffer of full message to be shown
string msg_; ///< error message
string func_; ///< function name
string file_; ///< file name
int line_; ///< line no.
public:
Exception(error_code code, const string &msg, const string &func,
const string &file, int line);
virtual ~Exception() throw();
virtual const char *what() const throw();
};
/** String formatter.
*/
template <typename T, typename... Args>
string format_string(const string &format, T first, Args... rest) {
int size = snprintf(nullptr, 0, format.c_str(), first, rest...);
if (size < 0) {
std::printf("fatal error in format_string function: snprintf failed\n");
std::abort();
}
vector<char> buffer(size + 1);
snprintf(buffer.data(), size + 1, format.c_str(), first, rest...);
return string(buffer.data(), buffer.data() + size);
}
/** String formatter without format.
*/
inline string format_string(const string &format) {
for (auto itr = format.begin(); itr != format.end(); itr++) {
if (*itr == '%') {
if (*(itr + 1) == '%') {
itr++;
} else {
NBLA_ERROR(error_code::unclassified, "Invalid format string %s",
format.c_str());
}
}
}
return format;
}
}
#endif
<|endoftext|> |
<commit_before>/******************************************************************************
* Copyright (c) 2014, Hobu Inc., [email protected]
*
* 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 Hobu, Inc. Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* Copyright (C) 1996, 1997 Theodore Ts'o.
*
* %Begin-Header%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 NOT ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
* %End-Header%
****************************************************************************/
// This is a C++ification of the libuuid code, less the code that actually
// creates UUIDs, which is most of it and we don't need at this time.
#pragma once
#include <string>
#include "pdal_util_export.hpp"
#include "Inserter.hpp"
#include "Extractor.hpp"
namespace pdal
{
#pragma pack(push)
#pragma pack(1)
struct uuid
{
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint16_t clock_seq;
uint8_t node[6];
};
#pragma pack(pop)
inline bool operator < (const uuid& u1, const uuid& u2)
{
if (u1.time_low != u2.time_low)
return u1.time_low < u2.time_low;
if (u1.time_mid != u2.time_mid)
return u1.time_mid < u2.time_mid;
if (u1.time_hi_and_version != u2.time_hi_and_version)
return u1.time_hi_and_version < u2.time_hi_and_version;
for (size_t i = 0; i < sizeof(u1.node); ++i)
if (u1.node[i] != u2.node[i])
return u1.node[i] < u2.node[i];
return false;
}
PDAL_DLL class Uuid
{
friend inline bool operator < (const Uuid& u1, const Uuid& u2);
public:
Uuid()
{ clear(); }
Uuid(const char *c)
{ unpack(c); }
Uuid(const std::string& s)
{ parse(s); }
void clear()
{ memset(&m_data, 0, sizeof(m_data)); }
void unpack(const char *c)
{
BeExtractor e(c, 10);
e >> m_data.time_low >> m_data.time_mid >>
m_data.time_hi_and_version >> m_data.clock_seq;
c += 10;
std::copy(c, c + 6, m_data.node);
}
void pack(char *c) const
{
BeInserter i(c, 10);
i << m_data.time_low << m_data.time_mid <<
m_data.time_hi_and_version << m_data.clock_seq;
c += 10;
std::copy(m_data.node, m_data.node + 6, c);
}
bool parse(const std::string& s)
{
if (s.length() != 36)
return false;
// Format validation.
const char *cp = s.data();
for (size_t i = 0; i < 36; i++) {
if ((i == 8) || (i == 13) || (i == 18) || (i == 23))
{
if (*cp != '-')
return false;
}
else if (!isxdigit(*cp))
return false;
++cp;
}
cp = s.data();
m_data.time_low = strtoul(cp, NULL, 16);
m_data.time_mid = strtoul(cp + 9, NULL, 16);
m_data.time_hi_and_version = strtoul(cp + 14, NULL, 16);
m_data.clock_seq = strtoul(cp + 19, NULL, 16);
// Extract bytes as pairs of hex digits.
cp = s.data() + 24;
char buf[3];
buf[2] = 0;
for (size_t i = 0; i < 6; i++) {
buf[0] = *cp++;
buf[1] = *cp++;
m_data.node[i] = strtoul(buf, NULL, 16);
}
return true;
}
std::string unparse() const
{
std::vector<char> buf(36);
const char fmt[] = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X";
sprintf(buf.data(), fmt,
m_data.time_low, m_data.time_mid, m_data.time_hi_and_version,
m_data.clock_seq >> 8, m_data.clock_seq & 0xFF,
m_data.node[0], m_data.node[1], m_data.node[2],
m_data.node[3], m_data.node[4], m_data.node[5]);
return std::string(buf.data());
}
std::string toString() const
{ return unparse(); }
bool empty() const
{ return isNull(); }
bool isNull() const
{
const char *c = (const char *)&m_data;
for (size_t i = 0; i < sizeof(m_data); ++i)
if (*c++ != 0)
return false;
return true;
}
/**
// Sadly, MS doesn't do constexpr.
static constexpr size_t size()
{ return sizeof(m_data); }
**/
static const int size = sizeof(uuid);
private:
uuid m_data;
};
inline bool operator == (const Uuid& u1, const Uuid& u2)
{
return !(u1 < u2) && !(u2 < u1);
}
inline bool operator < (const Uuid& u1, const Uuid& u2)
{
return u1.m_data < u2.m_data;
}
inline std::ostream& operator << (std::ostream& out, const Uuid& u)
{
out << u.toString();
return out;
}
inline std::istream& operator >> (std::istream& in, Uuid& u)
{
std::string s;
in >> s;
if (!u.parse(s))
in.setstate(std::ios::failbit);
return in;
}
} // namespace pdal
<commit_msg>Add stdint.<commit_after>/******************************************************************************
* Copyright (c) 2014, Hobu Inc., [email protected]
*
* 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 Hobu, Inc. Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* Copyright (C) 1996, 1997 Theodore Ts'o.
*
* %Begin-Header%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, and the entire permission notice in its entirety,
* including the disclaimer of warranties.
* 2. 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.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, ALL OF
* WHICH ARE HEREBY DISCLAIMED. IN NO EVENT SHALL THE AUTHOR 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 NOT ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
* %End-Header%
****************************************************************************/
// This is a C++ification of the libuuid code, less the code that actually
// creates UUIDs, which is most of it and we don't need at this time.
#pragma once
#include <cstdint>
#include <string>
#include "pdal_util_export.hpp"
#include "Inserter.hpp"
#include "Extractor.hpp"
namespace pdal
{
#pragma pack(push)
#pragma pack(1)
struct uuid
{
uint32_t time_low;
uint16_t time_mid;
uint16_t time_hi_and_version;
uint16_t clock_seq;
uint8_t node[6];
};
#pragma pack(pop)
inline bool operator < (const uuid& u1, const uuid& u2)
{
if (u1.time_low != u2.time_low)
return u1.time_low < u2.time_low;
if (u1.time_mid != u2.time_mid)
return u1.time_mid < u2.time_mid;
if (u1.time_hi_and_version != u2.time_hi_and_version)
return u1.time_hi_and_version < u2.time_hi_and_version;
for (size_t i = 0; i < sizeof(u1.node); ++i)
if (u1.node[i] != u2.node[i])
return u1.node[i] < u2.node[i];
return false;
}
PDAL_DLL class Uuid
{
friend inline bool operator < (const Uuid& u1, const Uuid& u2);
public:
Uuid()
{ clear(); }
Uuid(const char *c)
{ unpack(c); }
Uuid(const std::string& s)
{ parse(s); }
void clear()
{ memset(&m_data, 0, sizeof(m_data)); }
void unpack(const char *c)
{
BeExtractor e(c, 10);
e >> m_data.time_low >> m_data.time_mid >>
m_data.time_hi_and_version >> m_data.clock_seq;
c += 10;
std::copy(c, c + 6, m_data.node);
}
void pack(char *c) const
{
BeInserter i(c, 10);
i << m_data.time_low << m_data.time_mid <<
m_data.time_hi_and_version << m_data.clock_seq;
c += 10;
std::copy(m_data.node, m_data.node + 6, c);
}
bool parse(const std::string& s)
{
if (s.length() != 36)
return false;
// Format validation.
const char *cp = s.data();
for (size_t i = 0; i < 36; i++) {
if ((i == 8) || (i == 13) || (i == 18) || (i == 23))
{
if (*cp != '-')
return false;
}
else if (!isxdigit(*cp))
return false;
++cp;
}
cp = s.data();
m_data.time_low = strtoul(cp, NULL, 16);
m_data.time_mid = strtoul(cp + 9, NULL, 16);
m_data.time_hi_and_version = strtoul(cp + 14, NULL, 16);
m_data.clock_seq = strtoul(cp + 19, NULL, 16);
// Extract bytes as pairs of hex digits.
cp = s.data() + 24;
char buf[3];
buf[2] = 0;
for (size_t i = 0; i < 6; i++) {
buf[0] = *cp++;
buf[1] = *cp++;
m_data.node[i] = strtoul(buf, NULL, 16);
}
return true;
}
std::string unparse() const
{
std::vector<char> buf(36);
const char fmt[] = "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X";
sprintf(buf.data(), fmt,
m_data.time_low, m_data.time_mid, m_data.time_hi_and_version,
m_data.clock_seq >> 8, m_data.clock_seq & 0xFF,
m_data.node[0], m_data.node[1], m_data.node[2],
m_data.node[3], m_data.node[4], m_data.node[5]);
return std::string(buf.data());
}
std::string toString() const
{ return unparse(); }
bool empty() const
{ return isNull(); }
bool isNull() const
{
const char *c = (const char *)&m_data;
for (size_t i = 0; i < sizeof(m_data); ++i)
if (*c++ != 0)
return false;
return true;
}
/**
// Sadly, MS doesn't do constexpr.
static constexpr size_t size()
{ return sizeof(m_data); }
**/
static const int size = sizeof(uuid);
private:
uuid m_data;
};
inline bool operator == (const Uuid& u1, const Uuid& u2)
{
return !(u1 < u2) && !(u2 < u1);
}
inline bool operator < (const Uuid& u1, const Uuid& u2)
{
return u1.m_data < u2.m_data;
}
inline std::ostream& operator << (std::ostream& out, const Uuid& u)
{
out << u.toString();
return out;
}
inline std::istream& operator >> (std::istream& in, Uuid& u)
{
std::string s;
in >> s;
if (!u.parse(s))
in.setstate(std::ios::failbit);
return in;
}
} // namespace pdal
<|endoftext|> |
<commit_before>#ifndef _PFASST__LOGGING_HPP_
#define _PFASST__LOGGING_HPP_
#include "pfasst/site_config.hpp"
#include <string>
using namespace std;
#include <boost/algorithm/string.hpp>
struct OUT
{
public:
static const string black;
static const string red;
static const string green;
static const string yellow;
static const string blue;
static const string magenta;
static const string cyan;
static const string white;
static const string bold;
static const string underline;
static const string reset;
};
const string OUT::black = "\033[30m";
const string OUT::red = "\033[31m";
const string OUT::green = "\033[32m";
const string OUT::yellow = "\033[33m";
const string OUT::blue = "\033[34m";
const string OUT::magenta = "\033[35m";
const string OUT::cyan = "\033[36m";
const string OUT::white = "\033[37m";
const string OUT::bold = "\033[1m";
const string OUT::underline = "\033[4m";
const string OUT::reset = "\033[0m";
#include "config.hpp"
// enable easy logging of STL containers
#define _ELPP_STL_LOGGING
// disable creation of default log file
#define _ELPP_NO_DEFAULT_LOG_FILE
// enable passing `--logging-flags` via command line
#define _ELPP_LOGGING_FLAGS_FROM_ARG
#ifndef NDEBUG
#define _ELPP_DEBUG_ASSERT_FAILURE
#define _ELPP_STACKTRACE_ON_CRASH
#endif
#ifdef PFASST_NO_LOGGING
#define _ELPP_DISABLE_LOGS
#endif
#include <pfasst/easylogging++.h>
#ifndef PFASST_LOGGER_INITIALIZED
// initialize easyloggingpp
// FIXME: this might already be called by code using PFASST++
_INITIALIZE_EASYLOGGINGPP
/**
* guard symbol to ensure easylogging++ is only initialized once
*
* When this symbol is defined, it is expected that `_INITIALIZE_EASYLOGGINGPP` has been called once to initialize
* easylogging++.
*
* \note In case the executable using PFASST++ is also using easylogging++ as its logging library and initializing it
* prior to including the PFASST++ headers, please define this symbol prior including any of the PFASST++ headers.
*/
#define PFASST_LOGGER_INITIALIZED
#endif
#ifndef PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH
//! precision of milliseconds to be printed
#define PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH "4"
#endif
#ifndef VLOG_FUNC_START
#define VLOG_FUNC_START(scope) \
pfasst::log::stack_position++; \
VLOG(9) << std::string((pfasst::log::stack_position - 1) * 2, ' ') << "START: " << std::string(scope) << "::" << std::string(__func__) << "()"
#endif
#ifndef VLOG_FUNC_END
#define VLOG_FUNC_END(scope) \
pfasst::log::stack_position--; \
VLOG(9) << std::string(pfasst::log::stack_position * 2, ' ') << "DONE: " << std::string(scope) << "::" << std::string(__func__) << "()";
#endif
#ifndef LOG_PRECISION
#define LOG_PRECISION 5
#endif
#define LOG_INDENT string(pfasst::log::stack_position * 2, ' ')
//! length of logger ID to print
#define LOGGER_ID_LENGTH 8
namespace pfasst
{
/**
* Logging Facilities for PFASST++
*
* As PFASST++ is using easylogging++ as the logging backend, there are six distinced logging levels plus ten
* additional verbose logging levels.
*
* To achieve consistent logging throughout PFASST++ and its examples, we agree on the following conventions for using
* the different levels:
*
* - `INFO` is used for general important messages to the user
* - `DEBUG` is ment for developping purposes and is only active when compiled without `-DNDEBUG`
* - `VLOG` - the verbose logging levels are used as follows:
* - 0 to 8
* - 9 for function enter and exit messages (\see VLOG_FUNC_START and \see VLOG_FUNC_END )
*/
namespace log
{
static size_t stack_position;
/**
* \brief provides convenient way of adding additional named loggers
* \details With this function one can easily create additional named loggers distinctable by the `id`.
* The first \ref LOGGER_ID_LENGTH characters of the ID (as uppercase) will be included in every line of the log.
* The ID is used in the actual logging calls.
*
* \code{.cpp}
* add_custom_logger("MyCustomLogger")
* // somewhere else in the code
* CLOG(INFO, "MyCustomLogger") << "a logging message";
* \endcode
*
* This results in the log line (for the default value of \ref LOGGER_ID_LENGTH):
*
* <TIME> [MYCUSTOM, INFO ] a logging message
* \note Please make sure to use `CLOG` (and `CVLOG` for verbose logging) to be able to specify a specific logger.
* Otherwise the default logger will be used.
* \param[in] id The ID of the logger. This is used in logging calls.
*/
inline static void add_custom_logger(const string& id)
{
const string TIMESTAMP = OUT::white + "%datetime{%H:%m:%s,%g}" + OUT::reset + " ";
const string LEVEL = "%level]";
const string VLEVEL = "VERB%vlevel]";
const string POSITION = "%fbase:%line";
const string MESSAGE = "%msg";
const string INFO_COLOR = OUT::blue;
const string DEBG_COLOR = "";
const string WARN_COLOR = OUT::magenta;
const string ERRO_COLOR = OUT::red;
const string FATA_COLOR = OUT::red + OUT::bold;
const string VERB_COLOR = OUT::white;
const size_t id_length = id.size();
string id2print = id.substr(0, LOGGER_ID_LENGTH);
boost::to_upper(id2print);
if (id_length < LOGGER_ID_LENGTH) {
id2print.append(LOGGER_ID_LENGTH - id_length, ' ');
}
el::Logger* logger = el::Loggers::getLogger(id);
el::Configurations* conf = logger->configurations();
conf->setGlobally(el::ConfigurationType::MillisecondsWidth,
PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH);
conf->set(el::Level::Info, el::ConfigurationType::Format,
TIMESTAMP + INFO_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Debug, el::ConfigurationType::Format,
TIMESTAMP + DEBG_COLOR + "[" + id2print + ", " + LEVEL + " " + POSITION + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Warning, el::ConfigurationType::Format,
TIMESTAMP + WARN_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Error, el::ConfigurationType::Format,
TIMESTAMP + ERRO_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Fatal, el::ConfigurationType::Format,
TIMESTAMP + FATA_COLOR + "[" + id2print + ", " + LEVEL + " " + POSITION + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Verbose, el::ConfigurationType::Format,
TIMESTAMP + VERB_COLOR + "[" + id2print + ", " + VLEVEL + " " + MESSAGE + OUT::reset);
el::Loggers::reconfigureLogger(logger, *conf);
}
/**
* sets default configuration for default loggers
*/
inline static void load_default_config()
{
el::Configurations defaultConf;
defaultConf.setToDefault();
defaultConf.setGlobally(el::ConfigurationType::ToFile, "false");
defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
defaultConf.setGlobally(el::ConfigurationType::MillisecondsWidth, PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH);
el::Loggers::reconfigureAllLoggers(defaultConf);
add_custom_logger("default");
add_custom_logger("Controller");
add_custom_logger("Sweeper");
add_custom_logger("Encap");
add_custom_logger("Quadrature");
add_custom_logger("User");
}
/**
* sets some default flags for easylogging++
*
* Current defaults are:
*
* - LogDetailedCrashReason
* - DisableApplicationAbortOnFatalLog
* - ColoredTerminalOutput
* - MultiLoggerSupport
*
* \see https://github.com/easylogging/easyloggingpp#logging-flags
*/
inline static void set_logging_flags()
{
el::Loggers::addFlag(el::LoggingFlag::LogDetailedCrashReason);
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
el::Loggers::addFlag(el::LoggingFlag::MultiLoggerSupport);
el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically);
}
#ifdef NDEBUG
inline static void test_logging_levels() {}
#else
inline static void test_logging_levels()
{
cout << "### Example of different Logging Levels:" << endl;
LOG(INFO) << "info";
LOG(DEBUG) << "debug";
LOG(WARNING) << "warning";
LOG(ERROR) << "error";
LOG(FATAL) << "fatal error";
LOG(TRACE) << "trace";
for (size_t level = 0; level <= 9; ++level) {
VLOG(level) << "verbosity level " << level;
}
cout << "### End Example Logging Levels" << endl << endl;
}
#endif
/**
* starts easylogging++ with given arguments and loads configuration
*
* Usually, you want to pass the command line arguments given to `main()` in here and let easylogging++ figure
* out what it needs.
*
* \param[in] argc number of command line arguments
* \param[in] argv command line arguments
*/
inline static void start_log(int argc, char** argv)
{
_START_EASYLOGGINGPP(argc, argv);
set_logging_flags();
load_default_config();
pfasst::log::stack_position = 0;
}
} // ::pfasst::log
} // ::pfasst
#endif // _PFASST__LOGGING_HPP_
<commit_msg>logging: adjust easylogging API<commit_after>#ifndef _PFASST__LOGGING_HPP_
#define _PFASST__LOGGING_HPP_
#include "pfasst/site_config.hpp"
#include <string>
using namespace std;
#include <boost/algorithm/string.hpp>
struct OUT
{
public:
static const string black;
static const string red;
static const string green;
static const string yellow;
static const string blue;
static const string magenta;
static const string cyan;
static const string white;
static const string bold;
static const string underline;
static const string reset;
};
const string OUT::black = "\033[30m";
const string OUT::red = "\033[31m";
const string OUT::green = "\033[32m";
const string OUT::yellow = "\033[33m";
const string OUT::blue = "\033[34m";
const string OUT::magenta = "\033[35m";
const string OUT::cyan = "\033[36m";
const string OUT::white = "\033[37m";
const string OUT::bold = "\033[1m";
const string OUT::underline = "\033[4m";
const string OUT::reset = "\033[0m";
#include "config.hpp"
// enable easy logging of STL containers
#define ELPP_STL_LOGGING
// disable creation of default log file
#define ELPP_NO_DEFAULT_LOG_FILE
// enable passing `--logging-flags` via command line
#define ELPP_LOGGING_FLAGS_FROM_ARG
#ifndef NDEBUG
#define ELPP_DEBUG_ASSERT_FAILURE
#define ELPP_STACKTRACE_ON_CRASH
#endif
#ifdef PFASST_NO_LOGGING
#define ELPP_DISABLE_LOGS
#endif
#include <pfasst/easylogging++.h>
#ifndef PFASST_LOGGER_INITIALIZED
// initialize easyloggingpp
// FIXME: this might already be called by code using PFASST++
INITIALIZE_EASYLOGGINGPP
/**
* guard symbol to ensure easylogging++ is only initialized once
*
* When this symbol is defined, it is expected that `_INITIALIZE_EASYLOGGINGPP` has been called once to initialize
* easylogging++.
*
* \note In case the executable using PFASST++ is also using easylogging++ as its logging library and initializing it
* prior to including the PFASST++ headers, please define this symbol prior including any of the PFASST++ headers.
*/
#define PFASST_LOGGER_INITIALIZED
#endif
#ifndef PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH
//! precision of milliseconds to be printed
#define PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH "4"
#endif
#ifndef VLOG_FUNC_START
#define VLOG_FUNC_START(scope) \
pfasst::log::stack_position++; \
VLOG(9) << std::string((pfasst::log::stack_position - 1) * 2, ' ') << "START: " << std::string(scope) << "::" << std::string(__func__) << "()"
#endif
#ifndef VLOG_FUNC_END
#define VLOG_FUNC_END(scope) \
pfasst::log::stack_position--; \
VLOG(9) << std::string(pfasst::log::stack_position * 2, ' ') << "DONE: " << std::string(scope) << "::" << std::string(__func__) << "()";
#endif
#ifndef LOG_PRECISION
#define LOG_PRECISION 5
#endif
#define LOG_INDENT string(pfasst::log::stack_position * 2, ' ')
//! length of logger ID to print
#define LOGGER_ID_LENGTH 8
namespace pfasst
{
/**
* Logging Facilities for PFASST++
*
* As PFASST++ is using easylogging++ as the logging backend, there are six distinced logging levels plus ten
* additional verbose logging levels.
*
* To achieve consistent logging throughout PFASST++ and its examples, we agree on the following conventions for using
* the different levels:
*
* - `INFO` is used for general important messages to the user
* - `DEBUG` is ment for developping purposes and is only active when compiled without `-DNDEBUG`
* - `VLOG` - the verbose logging levels are used as follows:
* - 0 to 8
* - 9 for function enter and exit messages (\see VLOG_FUNC_START and \see VLOG_FUNC_END )
*/
namespace log
{
static size_t stack_position;
/**
* \brief provides convenient way of adding additional named loggers
* \details With this function one can easily create additional named loggers distinctable by the `id`.
* The first \ref LOGGER_ID_LENGTH characters of the ID (as uppercase) will be included in every line of the log.
* The ID is used in the actual logging calls.
*
* \code{.cpp}
* add_custom_logger("MyCustomLogger")
* // somewhere else in the code
* CLOG(INFO, "MyCustomLogger") << "a logging message";
* \endcode
*
* This results in the log line (for the default value of \ref LOGGER_ID_LENGTH):
*
* <TIME> [MYCUSTOM, INFO ] a logging message
* \note Please make sure to use `CLOG` (and `CVLOG` for verbose logging) to be able to specify a specific logger.
* Otherwise the default logger will be used.
* \param[in] id The ID of the logger. This is used in logging calls.
*/
inline static void add_custom_logger(const string& id)
{
const string TIMESTAMP = OUT::white + "%datetime{%H:%m:%s,%g}" + OUT::reset + " ";
const string LEVEL = "%level]";
const string VLEVEL = "VERB%vlevel]";
const string POSITION = "%fbase:%line";
const string MESSAGE = "%msg";
const string INFO_COLOR = OUT::blue;
const string DEBG_COLOR = "";
const string WARN_COLOR = OUT::magenta;
const string ERRO_COLOR = OUT::red;
const string FATA_COLOR = OUT::red + OUT::bold;
const string VERB_COLOR = OUT::white;
const size_t id_length = id.size();
string id2print = id.substr(0, LOGGER_ID_LENGTH);
boost::to_upper(id2print);
if (id_length < LOGGER_ID_LENGTH) {
id2print.append(LOGGER_ID_LENGTH - id_length, ' ');
}
el::Logger* logger = el::Loggers::getLogger(id);
el::Configurations* conf = logger->configurations();
conf->setGlobally(el::ConfigurationType::MillisecondsWidth,
PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH);
conf->set(el::Level::Info, el::ConfigurationType::Format,
TIMESTAMP + INFO_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Debug, el::ConfigurationType::Format,
TIMESTAMP + DEBG_COLOR + "[" + id2print + ", " + LEVEL + " " + POSITION + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Warning, el::ConfigurationType::Format,
TIMESTAMP + WARN_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Error, el::ConfigurationType::Format,
TIMESTAMP + ERRO_COLOR + "[" + id2print + ", " + LEVEL + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Fatal, el::ConfigurationType::Format,
TIMESTAMP + FATA_COLOR + "[" + id2print + ", " + LEVEL + " " + POSITION + " " + MESSAGE + OUT::reset);
conf->set(el::Level::Verbose, el::ConfigurationType::Format,
TIMESTAMP + VERB_COLOR + "[" + id2print + ", " + VLEVEL + " " + MESSAGE + OUT::reset);
el::Loggers::reconfigureLogger(logger, *conf);
}
/**
* sets default configuration for default loggers
*/
inline static void load_default_config()
{
el::Configurations defaultConf;
defaultConf.setToDefault();
defaultConf.setGlobally(el::ConfigurationType::ToFile, "false");
defaultConf.setGlobally(el::ConfigurationType::ToStandardOutput, "true");
defaultConf.setGlobally(el::ConfigurationType::MillisecondsWidth, PFASST_LOGGER_DEFAULT_GLOBAL_MILLISECOND_WIDTH);
el::Loggers::reconfigureAllLoggers(defaultConf);
add_custom_logger("default");
add_custom_logger("Controller");
add_custom_logger("Sweeper");
add_custom_logger("Encap");
add_custom_logger("Quadrature");
add_custom_logger("User");
}
/**
* sets some default flags for easylogging++
*
* Current defaults are:
*
* - LogDetailedCrashReason
* - DisableApplicationAbortOnFatalLog
* - ColoredTerminalOutput
* - MultiLoggerSupport
*
* \see https://github.com/easylogging/easyloggingpp#logging-flags
*/
inline static void set_logging_flags()
{
el::Loggers::addFlag(el::LoggingFlag::LogDetailedCrashReason);
el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog);
el::Loggers::addFlag(el::LoggingFlag::ColoredTerminalOutput);
el::Loggers::addFlag(el::LoggingFlag::MultiLoggerSupport);
el::Loggers::addFlag(el::LoggingFlag::CreateLoggerAutomatically);
}
#ifdef NDEBUG
inline static void test_logging_levels() {}
#else
inline static void test_logging_levels()
{
cout << "### Example of different Logging Levels:" << endl;
LOG(INFO) << "info";
LOG(DEBUG) << "debug";
LOG(WARNING) << "warning";
LOG(ERROR) << "error";
LOG(FATAL) << "fatal error";
LOG(TRACE) << "trace";
for (size_t level = 0; level <= 9; ++level) {
VLOG(level) << "verbosity level " << level;
}
cout << "### End Example Logging Levels" << endl << endl;
}
#endif
/**
* starts easylogging++ with given arguments and loads configuration
*
* Usually, you want to pass the command line arguments given to `main()` in here and let easylogging++ figure
* out what it needs.
*
* \param[in] argc number of command line arguments
* \param[in] argv command line arguments
*/
inline static void start_log(int argc, char** argv)
{
START_EASYLOGGINGPP(argc, argv);
set_logging_flags();
load_default_config();
pfasst::log::stack_position = 0;
}
} // ::pfasst::log
} // ::pfasst
#endif // _PFASST__LOGGING_HPP_
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
\mainpage R2D2-NXT
\section intro_sec Introduction
r2d2-nxt is a C++ library for programming Lego NXT robots using either the USB or the Bluetooth interfaces. It supports
Linux, Microsoft Windows (tested on 7) and Mac OS X.
\section requirements Requirements
CMake (http://cmake.org) is required for building from sources. r2d2-nxt uses certain C++11 features, so you'll need a relatively recent C++ compiler.
r2d2-nxt has been tested on the following platforms:
- GCC 4.6 on Linux
- Clang 3.2 on Linux
- Clang 4.2 on Mac OSX
- MSVC 10.0 on Microsoft Windows 7.
\section install_sec Installation
Run <tt>cmake .</tt> to generate the build rules for your platform (make on Linux and Mac OSX, nmake on Windows), afterwards you may use <tt>make install</tt>
on Linux and Mac OSX, or <tt>nmake install</tt> on Microsoft Windows, to install r2d2-nxt to its proper location. You can configure the destination path
(\c CMAKE_INSTALL_PREFIX) with <tt>ccmake .</tt> or <tt>cmake-gui</tt>
*/
#ifndef R2D2_BASE_HPP
#define R2D2_BASE_HPP
#include <cstdint>
#include <sstream>
#include <vector>
#include <r2d2/comm.hpp>
#include <r2d2/motors.hpp>
#include <r2d2/sensors.hpp>
#define NXT_BLUETOOTH_ADDRESS "00:16:53"
//! R2D2-NXT namespace
namespace r2d2 {
enum class Opcode : uint8_t {
SET_INPUT_MODE = 0x05,
LOWSPEED_9V = 0x0B,
LS_GET_STATUS = 0x0E,
LS_WRITE = 0x0F,
LS_READ = 0x10,
GET_VALUE = 0x07,
TOUCH = 0x01,
START_MOTOR = 0x04,
STOP_MOTOR = 0x04,
RESET_ROTATION_COUNT = 0x0A,
GET_ROTATION_COUNT = 0x06,
PLAY_TONE = 0x03,
STOP_SOUND = 0x0C,
ACTIVE_LIGHT = 0x05,
PASSIVE_LIGHT = 0x06,
GET_FIRMWARE_VERSION = 0x88,
GET_DEVICE_INFO = 0x9B
};
class Message {
private:
std::stringstream sstream_;
bool requiresResponse_;
bool isDirect_;
uint8_t type_;
uint8_t opcode_;
public:
Message(bool isDirect, bool requiresResponse);
Message(const std::string &s);
bool requiresResponse() const;
bool isDirect() const;
void add_u8(uint8_t v);
void add_s8(int8_t v);
void add_u16(uint16_t v);
void add_s16(int16_t v);
void add_u32(uint32_t v);
void add_s32(int32_t v);
void add_string(size_t n_bytes, const std::string& v);
std::string get_value();
uint32_t parse_u32();
int32_t parse_s32();
uint16_t parse_u16();
int16_t parse_s16();
uint8_t parse_u8();
int8_t parse_s8();
};
/**
A configured NXT brick, with the sensors and motors layout already set up.
*/
class NXT;
/**
An unconfigured NXT brick, without any sensors or motors attached.
An unconfigured NXT brick can issue system commands such as Brick::getFirmware
or Brick::getDeviceInfo, but it doesn't have any sensors or motors attached,
instead use Brick::configure to setup an NXT layout.
*/
class Brick {
private:
Comm *comm_;
bool halted;
SensorFactory sensorFactory;
MotorFactory motorFactory;
public:
Brick(Comm *comm);
/**
Open the underlying transport.
@return A bool whether the transport was successfully opened.
*/
bool open();
/**
Obtain the NXT brick name.
@return std::string A std::string with the name of the NXT brick.
*/
std::string getName();
/**
Obtain the NXT firmware version.
@return A double with the firmware version of the NXT brick.
*/
double getFirmwareVersion();
/**
Obtain information about the NXT brick.
@param uint8_t* A uint8_t* buffer to store the device information.
@param size_t A size_t with the size of the buffer.
*/
void getDeviceInfo(uint8_t*, size_t);
/**
Stop all motors, use it to guarantee that the brick will be in a safe
state.
*/
void halt();
/**
Whether the NXT brick is stopped.
@return A bool with whether the NXT is stopped.
*/
bool isHalted() const;
/**
Make the NXT brick play a sound.
@param frequency The frequency in Hz to play in the NXT brick.
@param duration The duration in milliseconds to play the tone.
*/
void playTone(uint16_t frequency, uint16_t duration);
/**
Interrupt any sound currently playing in the NXT brick.
*/
void stopSound();
/**
Configure a Brick with a Sensor and Motor layout.
@param sensor1 The Sensor in the port 1.
@param sensor2 The Sensor in the port 2.
@param sensor3 The Sensor in the port 3.
@param sensor4 The Sensor in the port 4.
@param motorA The Motor in the port A.
@param motorB The Motor in the port B.
@param motorC The Motor in the port C.
@return A fully configured NXT object.
*/
NXT* configure(SensorType sensor1, SensorType sensor2,
SensorType sensor3, SensorType sensor4,
MotorType motorA, MotorType motorB, MotorType motorC);
};
class NXT {
private:
Brick *brick_;
Comm *comm_;
bool halted;
Sensor *sensorPort1;
Sensor *sensorPort2;
Sensor *sensorPort3;
Sensor *sensorPort4;
Motor *motorPortA;
Motor *motorPortB;
Motor *motorPortC;
public:
NXT(Brick *, Comm *, Sensor *, Sensor *, Sensor *, Sensor *, Motor *, Motor *, Motor *);
/**
Return the Sensor object at the given port.
@param port One of the SensorPort enum values.
@return A Sensor instance.
*/
Sensor * sensorPort(SensorPort port) {
switch(port) {
case SensorPort::IN_1:
return sensorPort1;
case SensorPort::IN_2:
return sensorPort2;
case SensorPort::IN_3:
return sensorPort3;
case SensorPort::IN_4:
return sensorPort4;
default:
return nullptr;
}
};
/**
Return the Motor object at the given port.
@param port One of the MotorPort enum values.
@return A Motor instance.
*/
Motor *motorPort(MotorPort port) {
switch(port) {
case MotorPort::OUT_A:
return motorPortA;
case MotorPort::OUT_B:
return motorPortB;
case MotorPort::OUT_C:
return motorPortC;
default:
return nullptr;
}
};
/**
@see Brick::getName()
*/
std::string getName();
/**
@see Brick::getName()
*/
double getFirmwareVersion();
/**
@see Brick::getDeviceInfo()
*/
void getDeviceInfo(uint8_t*, size_t);
/**
@see Brick::halt()
*/
void halt();
/**
@see Brick::isHalted()
*/
bool isHalted() const;
/**
@see Brick::playTone()
*/
void playTone(uint16_t frequency, uint16_t duration);
/**
@see Brick::stopSound()
*/
void stopSound();
};
class BrickManager {
public:
/**
Find all the NXT bricks in the underlying transport.
@return A std::vector of Brick.
*/
virtual std::vector<Brick *>* list() = 0;
};
}
#endif
<commit_msg>Update requirements and add examples section<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/**
\mainpage R2D2-NXT
\section intro_sec Introduction
r2d2-nxt is a C++ library for programming Lego NXT robots using either the USB or the Bluetooth interfaces. It supports
Linux, Microsoft Windows (tested on 7) and Mac OS X.
\section requirements Requirements
CMake (http://cmake.org) is required for building from sources. r2d2-nxt uses certain C++11 features, so you'll need a relatively recent C++ compiler.
r2d2-nxt has been tested on the following platforms:
- GCC 4.6 on Linux
- Clang 3.2 on Linux
- Clang 4.2 on Mac OSX
- MSVC 10.0 on Microsoft Windows 7.
You will also need to have libusb-1.0 installed (http://libusb.org). If you want to generate the documentation, you'll also have to install Doxygen
(http://doxygen.org) and Graphviz (http://graphviz.org)
\section install_sec Installation
Run <tt>cmake .</tt> to generate the build rules for your platform (make on Linux and Mac OSX, nmake on Windows), afterwards you may use <tt>make install</tt>
on Linux and Mac OSX, or <tt>nmake install</tt> on Microsoft Windows, to install r2d2-nxt to its proper location. You can configure the destination path
(\c CMAKE_INSTALL_PREFIX) with <tt>ccmake .</tt> or <tt>cmake-gui</tt>
\section examples Examples
You may find several examples in the \c examples/ directory, that use both USB and Bluetooth.
*/
#ifndef R2D2_BASE_HPP
#define R2D2_BASE_HPP
#include <cstdint>
#include <sstream>
#include <vector>
#include <r2d2/comm.hpp>
#include <r2d2/motors.hpp>
#include <r2d2/sensors.hpp>
#define NXT_BLUETOOTH_ADDRESS "00:16:53"
//! R2D2-NXT namespace
namespace r2d2 {
enum class Opcode : uint8_t {
SET_INPUT_MODE = 0x05,
LOWSPEED_9V = 0x0B,
LS_GET_STATUS = 0x0E,
LS_WRITE = 0x0F,
LS_READ = 0x10,
GET_VALUE = 0x07,
TOUCH = 0x01,
START_MOTOR = 0x04,
STOP_MOTOR = 0x04,
RESET_ROTATION_COUNT = 0x0A,
GET_ROTATION_COUNT = 0x06,
PLAY_TONE = 0x03,
STOP_SOUND = 0x0C,
ACTIVE_LIGHT = 0x05,
PASSIVE_LIGHT = 0x06,
GET_FIRMWARE_VERSION = 0x88,
GET_DEVICE_INFO = 0x9B
};
class Message {
private:
std::stringstream sstream_;
bool requiresResponse_;
bool isDirect_;
uint8_t type_;
uint8_t opcode_;
public:
Message(bool isDirect, bool requiresResponse);
Message(const std::string &s);
bool requiresResponse() const;
bool isDirect() const;
void add_u8(uint8_t v);
void add_s8(int8_t v);
void add_u16(uint16_t v);
void add_s16(int16_t v);
void add_u32(uint32_t v);
void add_s32(int32_t v);
void add_string(size_t n_bytes, const std::string& v);
std::string get_value();
uint32_t parse_u32();
int32_t parse_s32();
uint16_t parse_u16();
int16_t parse_s16();
uint8_t parse_u8();
int8_t parse_s8();
};
/**
A configured NXT brick, with the sensors and motors layout already set up.
*/
class NXT;
/**
An unconfigured NXT brick, without any sensors or motors attached.
An unconfigured NXT brick can issue system commands such as Brick::getFirmware
or Brick::getDeviceInfo, but it doesn't have any sensors or motors attached,
instead use Brick::configure to setup an NXT layout.
*/
class Brick {
private:
Comm *comm_;
bool halted;
SensorFactory sensorFactory;
MotorFactory motorFactory;
public:
Brick(Comm *comm);
/**
Open the underlying transport.
@return A bool whether the transport was successfully opened.
*/
bool open();
/**
Obtain the NXT brick name.
@return std::string A std::string with the name of the NXT brick.
*/
std::string getName();
/**
Obtain the NXT firmware version.
@return A double with the firmware version of the NXT brick.
*/
double getFirmwareVersion();
/**
Obtain information about the NXT brick.
@param uint8_t* A uint8_t* buffer to store the device information.
@param size_t A size_t with the size of the buffer.
*/
void getDeviceInfo(uint8_t*, size_t);
/**
Stop all motors, use it to guarantee that the brick will be in a safe
state.
*/
void halt();
/**
Whether the NXT brick is stopped.
@return A bool with whether the NXT is stopped.
*/
bool isHalted() const;
/**
Make the NXT brick play a sound.
@param frequency The frequency in Hz to play in the NXT brick.
@param duration The duration in milliseconds to play the tone.
*/
void playTone(uint16_t frequency, uint16_t duration);
/**
Interrupt any sound currently playing in the NXT brick.
*/
void stopSound();
/**
Configure a Brick with a Sensor and Motor layout.
@param sensor1 The Sensor in the port 1.
@param sensor2 The Sensor in the port 2.
@param sensor3 The Sensor in the port 3.
@param sensor4 The Sensor in the port 4.
@param motorA The Motor in the port A.
@param motorB The Motor in the port B.
@param motorC The Motor in the port C.
@return A fully configured NXT object.
*/
NXT* configure(SensorType sensor1, SensorType sensor2,
SensorType sensor3, SensorType sensor4,
MotorType motorA, MotorType motorB, MotorType motorC);
};
class NXT {
private:
Brick *brick_;
Comm *comm_;
bool halted;
Sensor *sensorPort1;
Sensor *sensorPort2;
Sensor *sensorPort3;
Sensor *sensorPort4;
Motor *motorPortA;
Motor *motorPortB;
Motor *motorPortC;
public:
NXT(Brick *, Comm *, Sensor *, Sensor *, Sensor *, Sensor *, Motor *, Motor *, Motor *);
/**
Return the Sensor object at the given port.
@param port One of the SensorPort enum values.
@return A Sensor instance.
*/
Sensor * sensorPort(SensorPort port) {
switch(port) {
case SensorPort::IN_1:
return sensorPort1;
case SensorPort::IN_2:
return sensorPort2;
case SensorPort::IN_3:
return sensorPort3;
case SensorPort::IN_4:
return sensorPort4;
default:
return nullptr;
}
};
/**
Return the Motor object at the given port.
@param port One of the MotorPort enum values.
@return A Motor instance.
*/
Motor *motorPort(MotorPort port) {
switch(port) {
case MotorPort::OUT_A:
return motorPortA;
case MotorPort::OUT_B:
return motorPortB;
case MotorPort::OUT_C:
return motorPortC;
default:
return nullptr;
}
};
/**
@see Brick::getName()
*/
std::string getName();
/**
@see Brick::getName()
*/
double getFirmwareVersion();
/**
@see Brick::getDeviceInfo()
*/
void getDeviceInfo(uint8_t*, size_t);
/**
@see Brick::halt()
*/
void halt();
/**
@see Brick::isHalted()
*/
bool isHalted() const;
/**
@see Brick::playTone()
*/
void playTone(uint16_t frequency, uint16_t duration);
/**
@see Brick::stopSound()
*/
void stopSound();
};
class BrickManager {
public:
/**
Find all the NXT bricks in the underlying transport.
@return A std::vector of Brick.
*/
virtual std::vector<Brick *>* list() = 0;
};
}
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SVX_RUBYDLG_HXX_
#define _SVX_RUBYDLG_HXX_
#include <sfx2/childwin.hxx>
#include <sfx2/basedlgs.hxx>
#include <vcl/layout.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/edit.hxx>
#include <vcl/scrbar.hxx>
#include <com/sun/star/uno/Reference.h>
#include "svx/svxdllapi.h"
namespace com{namespace sun{namespace star{
namespace view{
class XSelectionChangeListener;
}
}}}
class SvxRubyDialog;
class RubyPreview : public Window
{
protected:
virtual void Paint( const Rectangle& rRect );
SvxRubyDialog* m_pParentDlg;
public:
RubyPreview(Window *pParent);
void setRubyDialog(SvxRubyDialog* pParentDlg)
{
m_pParentDlg = pParentDlg;
}
virtual Size GetOptimalSize() const;
};
class SVX_DLLPUBLIC SvxRubyChildWindow : public SfxChildWindow
{
public:
SvxRubyChildWindow( Window*, sal_uInt16, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxRubyChildWindow );
};
class SvxRubyData_Impl;
class RubyEdit : public Edit
{
Link aScrollHdl;
Link aJumpHdl;
virtual void GetFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
public:
RubyEdit(Window* pParent, const ResId& rResId)
: Edit(pParent, rResId)
{
}
RubyEdit(Window* pParent)
: Edit(pParent, WB_BORDER)
{
}
void SetScrollHdl(Link& rLink) {aScrollHdl = rLink;}
void SetJumpHdl(Link& rLink) {aJumpHdl = rLink;}
};
class SvxRubyDialog : public SfxModelessDialog
{
using Window::SetText;
using Window::GetText;
friend class RubyPreview;
FixedText* m_pLeftFT;
FixedText* m_pRightFT;
RubyEdit* m_pLeft1ED;
RubyEdit* m_pRight1ED;
RubyEdit* m_pLeft2ED;
RubyEdit* m_pRight2ED;
RubyEdit* m_pLeft3ED;
RubyEdit* m_pRight3ED;
RubyEdit* m_pLeft4ED;
RubyEdit* m_pRight4ED;
RubyEdit* aEditArr[8];
VclScrolledWindow* m_pScrolledWindow;
ScrollBar* m_pScrollSB;
ListBox* m_pAdjustLB;
ListBox* m_pPositionLB;
FixedText* m_pCharStyleFT;
ListBox* m_pCharStyleLB;
PushButton* m_pStylistPB;
RubyPreview* m_pPreviewWin;
PushButton* m_pApplyPB;
PushButton* m_pClosePB;
long nLastPos;
long nCurrentEdit;
sal_Bool bModified;
com::sun::star::uno::Reference<com::sun::star::view::XSelectionChangeListener> xImpl;
SfxBindings* pBindings;
SvxRubyData_Impl* pImpl;
DECL_LINK(ApplyHdl_Impl, void *);
DECL_LINK(CloseHdl_Impl, void *);
DECL_LINK(StylistHdl_Impl, void *);
DECL_LINK(ScrollHdl_Impl, ScrollBar*);
DECL_LINK(PositionHdl_Impl, ListBox*);
DECL_LINK(AdjustHdl_Impl, ListBox*);
DECL_LINK(CharStyleHdl_Impl, void *);
DECL_LINK(EditModifyHdl_Impl, Edit*);
DECL_LINK(EditScrollHdl_Impl, sal_Int32*);
DECL_LINK(EditJumpHdl_Impl, sal_Int32*);
void SetText(sal_Int32 nPos, Edit& rLeft, Edit& rRight);
void GetText();
void ClearCharStyleList();
void AssertOneEntry();
void Update();
virtual sal_Bool Close();
long GetLastPos() const {return nLastPos;}
void SetLastPos(long nSet) {nLastPos = nSet;}
sal_Bool IsModified() const {return bModified;}
void SetModified(sal_Bool bSet) {bModified = bSet;}
void EnableControls(bool bEnable);
void GetCurrentText(String& rBase, String& rRuby);
void UpdateColors( void );
protected:
virtual void DataChanged( const DataChangedEvent& rDCEvt );
public:
SvxRubyDialog(SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent);
virtual ~SvxRubyDialog();
virtual void Activate();
virtual void Deactivate();
};
#endif // _SVX_RUBYDLG_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>adjust usings, really should just rename ruby's get/set text<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*
* This file incorporates work covered by the following license notice:
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed
* with this work for additional information regarding copyright
* ownership. The ASF licenses this file to you under the Apache
* License, Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.apache.org/licenses/LICENSE-2.0 .
*/
#ifndef _SVX_RUBYDLG_HXX_
#define _SVX_RUBYDLG_HXX_
#include <sfx2/childwin.hxx>
#include <sfx2/basedlgs.hxx>
#include <vcl/layout.hxx>
#include <vcl/lstbox.hxx>
#include <vcl/fixed.hxx>
#include <vcl/button.hxx>
#include <vcl/edit.hxx>
#include <vcl/scrbar.hxx>
#include <com/sun/star/uno/Reference.h>
#include "svx/svxdllapi.h"
namespace com{namespace sun{namespace star{
namespace view{
class XSelectionChangeListener;
}
}}}
class SvxRubyDialog;
class RubyPreview : public Window
{
protected:
virtual void Paint( const Rectangle& rRect );
SvxRubyDialog* m_pParentDlg;
public:
RubyPreview(Window *pParent);
void setRubyDialog(SvxRubyDialog* pParentDlg)
{
m_pParentDlg = pParentDlg;
}
virtual Size GetOptimalSize() const;
};
class SVX_DLLPUBLIC SvxRubyChildWindow : public SfxChildWindow
{
public:
SvxRubyChildWindow( Window*, sal_uInt16, SfxBindings*, SfxChildWinInfo* );
SFX_DECL_CHILDWINDOW( SvxRubyChildWindow );
};
class SvxRubyData_Impl;
class RubyEdit : public Edit
{
Link aScrollHdl;
Link aJumpHdl;
virtual void GetFocus();
virtual long PreNotify( NotifyEvent& rNEvt );
public:
RubyEdit(Window* pParent, const ResId& rResId)
: Edit(pParent, rResId)
{
}
RubyEdit(Window* pParent)
: Edit(pParent, WB_BORDER)
{
}
void SetScrollHdl(Link& rLink) {aScrollHdl = rLink;}
void SetJumpHdl(Link& rLink) {aJumpHdl = rLink;}
};
class SvxRubyDialog : public SfxModelessDialog
{
using Dialog::SetText;
using Dialog::GetText;
friend class RubyPreview;
FixedText* m_pLeftFT;
FixedText* m_pRightFT;
RubyEdit* m_pLeft1ED;
RubyEdit* m_pRight1ED;
RubyEdit* m_pLeft2ED;
RubyEdit* m_pRight2ED;
RubyEdit* m_pLeft3ED;
RubyEdit* m_pRight3ED;
RubyEdit* m_pLeft4ED;
RubyEdit* m_pRight4ED;
RubyEdit* aEditArr[8];
VclScrolledWindow* m_pScrolledWindow;
ScrollBar* m_pScrollSB;
ListBox* m_pAdjustLB;
ListBox* m_pPositionLB;
FixedText* m_pCharStyleFT;
ListBox* m_pCharStyleLB;
PushButton* m_pStylistPB;
RubyPreview* m_pPreviewWin;
PushButton* m_pApplyPB;
PushButton* m_pClosePB;
long nLastPos;
long nCurrentEdit;
sal_Bool bModified;
com::sun::star::uno::Reference<com::sun::star::view::XSelectionChangeListener> xImpl;
SfxBindings* pBindings;
SvxRubyData_Impl* pImpl;
DECL_LINK(ApplyHdl_Impl, void *);
DECL_LINK(CloseHdl_Impl, void *);
DECL_LINK(StylistHdl_Impl, void *);
DECL_LINK(ScrollHdl_Impl, ScrollBar*);
DECL_LINK(PositionHdl_Impl, ListBox*);
DECL_LINK(AdjustHdl_Impl, ListBox*);
DECL_LINK(CharStyleHdl_Impl, void *);
DECL_LINK(EditModifyHdl_Impl, Edit*);
DECL_LINK(EditScrollHdl_Impl, sal_Int32*);
DECL_LINK(EditJumpHdl_Impl, sal_Int32*);
void SetText(sal_Int32 nPos, Edit& rLeft, Edit& rRight);
void GetText();
void ClearCharStyleList();
void AssertOneEntry();
void Update();
virtual sal_Bool Close();
long GetLastPos() const {return nLastPos;}
void SetLastPos(long nSet) {nLastPos = nSet;}
sal_Bool IsModified() const {return bModified;}
void SetModified(sal_Bool bSet) {bModified = bSet;}
void EnableControls(bool bEnable);
void GetCurrentText(String& rBase, String& rRuby);
void UpdateColors( void );
protected:
virtual void DataChanged( const DataChangedEvent& rDCEvt );
public:
SvxRubyDialog(SfxBindings *pBindings, SfxChildWindow *pCW,
Window* pParent);
virtual ~SvxRubyDialog();
virtual void Activate();
virtual void Deactivate();
};
#endif // _SVX_RUBYDLG_HXX_
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*******************************************************************************
* include/util/file_util.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <fstream>
#include <vector>
#include "type_for_bytes.hpp"
template <uint8_t BytesPerWord>
static std::vector<typename type_for_bytes<BytesPerWord>::type> file_to_vector(
const std::string& file_name) {
std::ifstream stream(file_name.c_str(), std::ios::in | std::ios::binary);
stream.seekg(0, std::ios::end);
uint64_t size = stream.tellg() / BytesPerWord;
stream.seekg(0);
std::vector<typename type_for_bytes<BytesPerWord>::type> result(size);
stream.read(reinterpret_cast<char*>(result.data()), size);
stream.close();
return result;
}
/******************************************************************************/
<commit_msg>Write vector to file<commit_after>/*******************************************************************************
* include/util/file_util.hpp
*
* Copyright (C) 2017 Florian Kurpicz <[email protected]>
*
* All rights reserved. Published under the BSD-2 license in the LICENSE file.
******************************************************************************/
#pragma once
#include <fstream>
#include <vector>
#include "type_for_bytes.hpp"
template <uint8_t BytesPerWord>
static std::vector<typename type_for_bytes<BytesPerWord>::type> file_to_vector(
const std::string& file_name) {
std::ifstream stream(file_name.c_str(), std::ios::in | std::ios::binary);
stream.seekg(0, std::ios::end);
uint64_t size = stream.tellg() / BytesPerWord;
stream.seekg(0);
std::vector<typename type_for_bytes<BytesPerWord>::type> result(size);
stream.read(reinterpret_cast<char*>(result.data()), size);
stream.close();
return result;
}
template <typename Type>
static void vector_to_file(const std::vector<Type>& vec,
const std::string& file_name) {
std::ofstream stream(file_name.c_str(), std::ios::binary | std::ios::out);
stream.write(reinterpret_cast<char*>(vec.data()), sizeof(Type) * vec.size());
stream.close();
}
/******************************************************************************/
<|endoftext|> |
<commit_before>//============================================================================
// include/vsmc/core/path.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_CORE_PATH_HPP
#define VSMC_CORE_PATH_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/cxx11/functional.hpp>
#include <vsmc/integrate/nintegrate_newton_cotes.hpp>
#include <cmath>
#include <vector>
#define VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(func) \
VSMC_RUNTIME_ASSERT((iter < this->iter_size()), \
("**Path::"#func"** INVALID ITERATION NUMBER ARGUMENT"))
#define VSMC_RUNTIME_ASSERT_CORE_PATH_FUNCTOR(func, caller, name) \
VSMC_RUNTIME_ASSERT(static_cast<bool>(func), \
("**Path::"#caller"** INVALID "#name" OBJECT")) \
namespace vsmc {
/// \brief Monitor for Path sampling
/// \ingroup Core
template <typename T>
class Path
{
public :
typedef T value_type;
typedef cxx11::function<double (
std::size_t, const Particle<T> &, double *)> eval_type;
/// \brief Construct a Path with an evaluation object
///
/// \param eval The evaluation object of type Path::eval_type
///
/// A Path object is very similar to a Monitor object. It is a special case
/// for Path sampling Monitor. The dimension of the Monitor is always one.
/// In addition, the evaluation object returns the integration grid of the
/// Path sampling.
///
/// The evaluation object has the signature
/// ~~~{.cpp}
/// double eval (std::size_t iter, const Particle<T> &particle, double *integrand)
/// ~~~
/// where the first two arguments are passed in by the Sampler at the end
/// of each iteration. The evaluation occurs after the possible MCMC moves.
/// The output parameter `integrand` shall contains the results of the
/// Path sampling integrands. The return value shall be the Path sampling
/// integration grid.
///
/// For example, say the Path sampling is computed through integration of
/// \f$\lambda = \int_0^1 E[g_\alpha(X)]\,\mathrm{d}\alpha\f$. The integral
/// is approximated with numerical integration at point
/// \f$\alpha_0 = 0, \alpha_1, \dots, \alpha_T = 1\f$, then at iteration
/// \f$t\f$, the output parameter `integrand` contains
/// \f$(g_{\alpha_t}(X_0),\dots)\f$ and the return value is \f$\alpha_t\f$.
explicit Path (const eval_type &eval) :
eval_(eval), recording_(true), log_zconst_(0) {}
Path (const Path<T> &other) :
eval_(other.eval_), recording_(other.recording_),
log_zconst_(other.log_zconst_), index_(other.index_),
integrand_(other.integrand_), grid_(other.grid_) {}
Path<T> &operator= (const Path<T> &other)
{
if (this != &other) {
eval_ = other.eval_;
recording_ = other.recording_;
log_zconst_ = other.log_zconst_;
index_ = other.index_;
integrand_ = other.integrand_;
grid_ = other.grid_;
}
return *this;
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
Path (Path<T> &&other) :
eval_(cxx11::move(other.eval_)),
recording_(other.recording_), log_zconst_(other.log_zconst_),
index_(cxx11::move(other.index_)),
integrand_(cxx11::move(other.integrand_)),
grid_(cxx11::move(other.grid_)) {}
Path<T> &operator= (Path<T> &&other)
{
if (this != &other) {
eval_ = cxx11::move(other.eval_);
recording_ = other.recording_;
log_zconst_ = other.log_zconst_;
index_ = cxx11::move(other.index_);
integrand_ = cxx11::move(other.integrand_);
grid_ = cxx11::move(other.grid_);
}
return *this;
}
#endif
virtual ~Path () {}
/// \brief The number of iterations has been recorded
///
/// \sa Monitor::iter_size()
std::size_t iter_size () const {return index_.size();}
/// \brief Reserve space for a specified number of iterations
void reserve (std::size_t num)
{
index_.reserve(num);
integrand_.reserve(num);
grid_.reserve(num);
}
/// \brief Whether the evaluation object is valid
bool empty () const {return !static_cast<bool>(eval_);}
/// \brief Get the iteration index of the sampler of a given monitor
/// iteration
///
/// \sa Monitor::index()
std::size_t index (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(index);
return index_[iter];
}
/// \brief Get the Path sampling integrand of a given Path iteration
double integrand (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(integrand);
return integrand_[iter];
}
/// \brief Get the Path sampling grid value of a given Path iteration
double grid (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(grid);
return grid_[iter];
}
/// \brief Read the index history through an output iterator
///
/// \sa Monitor::read_index()
template <typename OutputIter>
OutputIter read_index (OutputIter first) const
{
const std::size_t N = index_.size();
const std::size_t *const iptr = &index_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = iptr[i];
return first;
}
/// \brief Read the integrand history through an output iterator
template <typename OutputIter>
OutputIter read_integrand (OutputIter first) const
{
const std::size_t N = integrand_.size();
const double *const iptr = &integrand_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = iptr[i];
return first;
}
/// \brief Read the grid history through an output iterator
template <typename OutputIter>
OutputIter read_grid (OutputIter first) const
{
const std::size_t N = grid_.size();
const double *const gptr = &grid_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = gptr[i];
return first;
}
/// \brief Set a new evaluation object of type eval_type
void set_eval (const eval_type &new_eval) {eval_ = new_eval;}
/// Perform the evaluation for a given iteration and a Particle<T> object
///
/// \sa Monitor::eval()
void eval (std::size_t iter, const Particle<T> &particle)
{
if (!recording_)
return;
VSMC_RUNTIME_ASSERT_CORE_PATH_FUNCTOR(eval_, eval, EVALUATION);
const std::size_t N = static_cast<std::size_t>(particle.size());
double *const buffer = malloc_eval_integrand(N);
double *const weight = malloc_weight(N);
particle.read_weight(weight);
index_.push_back(iter);
grid_.push_back(eval_(iter, particle, buffer));
double res = 0;
for (std::size_t i = 0; i != N; ++i)
res += buffer[i] * weight[i];
integrand_.push_back(res);
if (iter_size() > 1) {
std::size_t i = iter_size() - 1;
log_zconst_ += 0.5 * (grid_[i] - grid_[i - 1]) *
(integrand_[i] + integrand_[i - 1]);
}
}
/// \brief Get the nomralizing constants ratio estimates
double zconst () const {return std::exp(log_zconst_);}
/// \brief Get the logarithm nomralizing constants ratio estimates
double log_zconst () const {return log_zconst_;}
/// \brief Clear all records of the index and integrations
void clear ()
{
log_zconst_ = 0;
index_.clear();
integrand_.clear();
grid_.clear();
}
/// \brief Whether the Path is actively recording restuls
bool recording () const {return recording_;}
/// \brief Turn on the recording
void turnon () {recording_ = true;}
/// \brief Turn off the recording
void turnoff () {recording_ = false;}
protected :
virtual double *malloc_weight (std::size_t N)
{
weight_.resize(N);
return &weight_[0];
}
virtual double *malloc_eval_integrand (std::size_t N)
{
buffer_.resize(N);
return &buffer_[0];
}
private :
eval_type eval_;
bool recording_;
double log_zconst_;
std::vector<std::size_t> index_;
std::vector<double> integrand_;
std::vector<double> grid_;
std::vector<double> weight_;
std::vector<double> buffer_;
}; // class PathSampling
/// \brief Monitor for path sampling for SMC with geometry path
/// \ingroup Core
template <typename T>
class PathGeometry : public Path<T>
{
public :
typedef cxx11::function<double (
std::size_t, const Particle<T> &, double *)> eval_type;
PathGeometry (const eval_type &eval,
double abs_err = 1e-6, double rel_err = 1e-6) :
Path<T>(eval), abs_err_(abs_err), rel_err_(rel_err) {}
PathGeometry (const PathGeometry<T> &other) :
Path<T>(other), weight_history_(other.weight_history_),
integrand_history_(other.integrand_history_),
abs_err_(other.abs_err_), rel_err_(other.rel_err_) {}
PathGeometry<T> &operator= (const PathGeometry<T> &other)
{
if (this != &other) {
Path<T>::operator=(other);
weight_history_ = other.weight_history_;
integrand_history_ = other.integrand_history_;
abs_err_ = other.abs_err_;
rel_err_ = other.rel_err_;
}
return *this;
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
PathGeometry (PathGeometry<T> &&other) :
Path<T>(cxx11::move(other)),
weight_history_(cxx11::move(other.weight_history_)),
integrand_history_(cxx11::move(other.integrand_history_)),
abs_err_(other.abs_err_), rel_err_(other.rel_err_) {}
PathGeometry<T> &operator= (PathGeometry<T> &&other)
{
if (this != &other) {
Path<T>::operator=(cxx11::move(other));
weight_history_ = cxx11::move(other.weight_history_);
integrand_history_ = cxx11::move(other.integrand_history_);
abs_err_ = other.abs_err_;
rel_err_ = other.rel_err_;
}
return *this;
}
#endif
template <unsigned Degree>
double log_zconst_newton_cotes (unsigned insert_points = 0) const
{
if (this->iter_size() < 2)
return 0;
NIntegrateNewtonCotes<Degree> nintegrate;
if (insert_points == 0) {
std::vector<double> base_grid(this->iter_size());
for (std::size_t i = 0; i != this->iter_size(); ++i)
base_grid[i] = this->grid(i);
return nintegrate(static_cast<typename NIntegrateNewtonCotes<
Degree>:: size_type>(base_grid.size()),
&base_grid[0], f_alpha_(weight_size_, *this,
weight_history_, integrand_history_,
abs_err_, rel_err_));
}
std::vector<double> super_grid(insert_points * this->iter_size() -
insert_points + this->iter_size());
std::size_t offset = 0;
for (std::size_t i = 0; i != this->iter_size() - 1; ++i) {
double a = this->grid(i);
double b = this->grid(i + 1);
double h = (b - a) / (insert_points + 1);
super_grid[offset++] = a;
for (unsigned j = 0; j != insert_points; ++j)
super_grid[offset++] = a + h * (j + 1);
}
super_grid.back() = this->grid(this->iter_size() - 1);
return nintegrate(static_cast<typename NIntegrateNewtonCotes<
Degree>::size_type>(super_grid.size()),
&super_grid[0], f_alpha_(weight_size_, *this,
weight_history_, integrand_history_, abs_err_, rel_err_));
}
void clear ()
{
Path<T>::clear();
weight_history_.clear();
integrand_history_.clear();
}
protected :
double *malloc_weight (std::size_t N)
{
weight_size_ = static_cast<weight_size_type>(N);
weight_history_.push_back(std::vector<double>(N));
return &weight_history_.back()[0];
}
double *malloc_eval_integrand (std::size_t N)
{
integrand_history_.push_back(std::vector<double>(N));
return &integrand_history_.back()[0];
}
private :
typedef typename traits::SizeTypeTrait<
typename traits::WeightSetTypeTrait<T>::type>::type weight_size_type;
std::vector<std::vector<double> > weight_history_;
std::vector<std::vector<double> > integrand_history_;
double abs_err_;
double rel_err_;
weight_size_type weight_size_;
class f_alpha_
{
public :
f_alpha_(weight_size_type N,
const PathGeometry<T> &path,
const std::vector<std::vector<double> > &weight_history,
const std::vector<std::vector<double> > &integrand_history,
double abs_err, double rel_err) :
path_(path), weight_history_(weight_history),
integrand_history_(integrand_history), weight_set_(N), weight_(N),
abs_err_(abs_err), rel_err_(rel_err) {}
f_alpha_ (const f_alpha_ &other) :
path_(other.path_), weight_history_(other.weight_history_),
integrand_history_(other.integrand_history_),
weight_set_(other.weight_set_), weight_(other.weight_),
abs_err_(other.abs_err_), rel_err_(other.rel_err_) {}
double operator() (double alpha)
{
using std::exp;
if (path_.iter_size() == 0)
return 0;
std::size_t iter = 0;
while (iter != path_.iter_size() && path_.grid(iter) < alpha)
++iter;
double tol = alpha * rel_err_;
tol = tol < abs_err_ ? tol : abs_err_;
tol = tol > 0 ? tol : abs_err_;
if (iter != path_.iter_size() && path_.grid(iter) - alpha < tol)
return path_.integrand(iter);
if (iter == 0)
return 0;
--iter;
if (alpha - path_.grid(iter) < tol)
return path_.integrand(iter);
double alpha_inc = alpha - path_.grid(iter);
std::size_t size = weight_.size();
for (std::size_t i = 0; i != size; ++i)
weight_[i] = alpha_inc * integrand_history_[iter][i];
for (std::size_t i = 0; i != size; ++i)
weight_[i] = exp(weight_[i]);
for (std::size_t i = 0; i != size; ++i)
weight_[i] = weight_history_[iter][i] * weight_[i];
weight_set_.set_weight(&weight_[0]);
weight_set_.read_weight(&weight_[0]);
double res = 0;
const double *buffer = &integrand_history_[iter][0];
for (std::size_t i = 0; i != size; ++i)
res += buffer[i] * weight_[i];
return res;
}
private :
const PathGeometry<T> &path_;
const std::vector<std::vector<double> > &weight_history_;
const std::vector<std::vector<double> > &integrand_history_;
typename traits::WeightSetTypeTrait<T>::type weight_set_;
std::vector<double> weight_;
double abs_err_;
double rel_err_;
}; // class f_alpha_
}; // class PathGeometry
} // namespace vsmc
#endif // VSMC_CORE_PATH_HPP
<commit_msg>remove PathGeometry<commit_after>//============================================================================
// include/vsmc/core/path.hpp
//----------------------------------------------------------------------------
//
// vSMC: Scalable Monte Carlo
//
// This file is distribured under the 2-clauses BSD License.
// See LICENSE for details.
//============================================================================
#ifndef VSMC_CORE_PATH_HPP
#define VSMC_CORE_PATH_HPP
#include <vsmc/internal/common.hpp>
#include <vsmc/cxx11/functional.hpp>
#include <vsmc/integrate/nintegrate_newton_cotes.hpp>
#include <cmath>
#include <vector>
#define VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(func) \
VSMC_RUNTIME_ASSERT((iter < this->iter_size()), \
("**Path::"#func"** INVALID ITERATION NUMBER ARGUMENT"))
#define VSMC_RUNTIME_ASSERT_CORE_PATH_FUNCTOR(func, caller, name) \
VSMC_RUNTIME_ASSERT(static_cast<bool>(func), \
("**Path::"#caller"** INVALID "#name" OBJECT")) \
namespace vsmc {
/// \brief Monitor for Path sampling
/// \ingroup Core
template <typename T>
class Path
{
public :
typedef T value_type;
typedef cxx11::function<double (
std::size_t, const Particle<T> &, double *)> eval_type;
/// \brief Construct a Path with an evaluation object
///
/// \param eval The evaluation object of type Path::eval_type
///
/// A Path object is very similar to a Monitor object. It is a special case
/// for Path sampling Monitor. The dimension of the Monitor is always one.
/// In addition, the evaluation object returns the integration grid of the
/// Path sampling.
///
/// The evaluation object has the signature
/// ~~~{.cpp}
/// double eval (std::size_t iter, const Particle<T> &particle, double *integrand)
/// ~~~
/// where the first two arguments are passed in by the Sampler at the end
/// of each iteration. The evaluation occurs after the possible MCMC moves.
/// The output parameter `integrand` shall contains the results of the
/// Path sampling integrands. The return value shall be the Path sampling
/// integration grid.
///
/// For example, say the Path sampling is computed through integration of
/// \f$\lambda = \int_0^1 E[g_\alpha(X)]\,\mathrm{d}\alpha\f$. The integral
/// is approximated with numerical integration at point
/// \f$\alpha_0 = 0, \alpha_1, \dots, \alpha_T = 1\f$, then at iteration
/// \f$t\f$, the output parameter `integrand` contains
/// \f$(g_{\alpha_t}(X_0),\dots)\f$ and the return value is \f$\alpha_t\f$.
explicit Path (const eval_type &eval) :
eval_(eval), recording_(true), log_zconst_(0) {}
Path (const Path<T> &other) :
eval_(other.eval_), recording_(other.recording_),
log_zconst_(other.log_zconst_), index_(other.index_),
integrand_(other.integrand_), grid_(other.grid_) {}
Path<T> &operator= (const Path<T> &other)
{
if (this != &other) {
eval_ = other.eval_;
recording_ = other.recording_;
log_zconst_ = other.log_zconst_;
index_ = other.index_;
integrand_ = other.integrand_;
grid_ = other.grid_;
}
return *this;
}
#if VSMC_HAS_CXX11_RVALUE_REFERENCES
Path (Path<T> &&other) :
eval_(cxx11::move(other.eval_)),
recording_(other.recording_), log_zconst_(other.log_zconst_),
index_(cxx11::move(other.index_)),
integrand_(cxx11::move(other.integrand_)),
grid_(cxx11::move(other.grid_)) {}
Path<T> &operator= (Path<T> &&other)
{
if (this != &other) {
eval_ = cxx11::move(other.eval_);
recording_ = other.recording_;
log_zconst_ = other.log_zconst_;
index_ = cxx11::move(other.index_);
integrand_ = cxx11::move(other.integrand_);
grid_ = cxx11::move(other.grid_);
}
return *this;
}
#endif
virtual ~Path () {}
/// \brief The number of iterations has been recorded
///
/// \sa Monitor::iter_size()
std::size_t iter_size () const {return index_.size();}
/// \brief Reserve space for a specified number of iterations
void reserve (std::size_t num)
{
index_.reserve(num);
integrand_.reserve(num);
grid_.reserve(num);
}
/// \brief Whether the evaluation object is valid
bool empty () const {return !static_cast<bool>(eval_);}
/// \brief Get the iteration index of the sampler of a given monitor
/// iteration
///
/// \sa Monitor::index()
std::size_t index (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(index);
return index_[iter];
}
/// \brief Get the Path sampling integrand of a given Path iteration
double integrand (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(integrand);
return integrand_[iter];
}
/// \brief Get the Path sampling grid value of a given Path iteration
double grid (std::size_t iter) const
{
VSMC_RUNTIME_ASSERT_CORE_PATH_ITER(grid);
return grid_[iter];
}
/// \brief Read the index history through an output iterator
///
/// \sa Monitor::read_index()
template <typename OutputIter>
OutputIter read_index (OutputIter first) const
{
const std::size_t N = index_.size();
const std::size_t *const iptr = &index_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = iptr[i];
return first;
}
/// \brief Read the integrand history through an output iterator
template <typename OutputIter>
OutputIter read_integrand (OutputIter first) const
{
const std::size_t N = integrand_.size();
const double *const iptr = &integrand_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = iptr[i];
return first;
}
/// \brief Read the grid history through an output iterator
template <typename OutputIter>
OutputIter read_grid (OutputIter first) const
{
const std::size_t N = grid_.size();
const double *const gptr = &grid_[0];
for (std::size_t i = 0; i != N; ++i, ++first)
*first = gptr[i];
return first;
}
/// \brief Set a new evaluation object of type eval_type
void set_eval (const eval_type &new_eval) {eval_ = new_eval;}
/// Perform the evaluation for a given iteration and a Particle<T> object
///
/// \sa Monitor::eval()
void eval (std::size_t iter, const Particle<T> &particle)
{
if (!recording_)
return;
VSMC_RUNTIME_ASSERT_CORE_PATH_FUNCTOR(eval_, eval, EVALUATION);
const std::size_t N = static_cast<std::size_t>(particle.size());
double *const buffer = malloc_eval_integrand(N);
double *const weight = malloc_weight(N);
particle.read_weight(weight);
index_.push_back(iter);
grid_.push_back(eval_(iter, particle, buffer));
double res = 0;
for (std::size_t i = 0; i != N; ++i)
res += buffer[i] * weight[i];
integrand_.push_back(res);
if (iter_size() > 1) {
std::size_t i = iter_size() - 1;
log_zconst_ += 0.5 * (grid_[i] - grid_[i - 1]) *
(integrand_[i] + integrand_[i - 1]);
}
}
/// \brief Get the nomralizing constants ratio estimates
double zconst () const {return std::exp(log_zconst_);}
/// \brief Get the logarithm nomralizing constants ratio estimates
double log_zconst () const {return log_zconst_;}
/// \brief Clear all records of the index and integrations
void clear ()
{
log_zconst_ = 0;
index_.clear();
integrand_.clear();
grid_.clear();
}
/// \brief Whether the Path is actively recording restuls
bool recording () const {return recording_;}
/// \brief Turn on the recording
void turnon () {recording_ = true;}
/// \brief Turn off the recording
void turnoff () {recording_ = false;}
protected :
virtual double *malloc_weight (std::size_t N)
{
weight_.resize(N);
return &weight_[0];
}
virtual double *malloc_eval_integrand (std::size_t N)
{
buffer_.resize(N);
return &buffer_[0];
}
private :
eval_type eval_;
bool recording_;
double log_zconst_;
std::vector<std::size_t> index_;
std::vector<double> integrand_;
std::vector<double> grid_;
std::vector<double> weight_;
std::vector<double> buffer_;
}; // class PathSampling
} // namespace vsmc
#endif // VSMC_CORE_PATH_HPP
<|endoftext|> |
<commit_before>#ifndef XSCALAR_HPP
#define XSCALAR_HPP
#include <utility>
#include "xexpression.hpp"
#include "xindex.hpp"
namespace qs
{
/*************************
* xscalar
*************************/
// xscalar is a cheap wrapper for a scalar value as an xexpression.
template <class T>
class xscalar_stepper;
template <class T>
class xscalar : public xexpression<xscalar<T>>
{
public:
using value_type = T;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using size_type = size_t;
using difference_type = ptrdiff_t;
using self_type = xscalar<T>;
using shape_type = xshape<size_type>;
using strides_type = xstrides<size_type>;
using closure_type = const self_type;
using const_stepper = xscalar_stepper<T>;
xscalar(const T& value);
size_type size() const;
size_type dimension() const;
shape_type shape() const;
strides_type strides() const;
strides_type backstrides() const;
template <class... Args>
const_reference operator()(Args... args) const;
bool broadcast_shape(shape_type& shape) const;
bool is_trivial_broadcast(const strides_type& strides) const;
const_stepper stepper_begin(const shape_type& shape) const;
const_stepper stepper_end(const shape_type& shape) const;
private:
const T& m_value;
};
/*********************
* xscalar_stepper
*********************/
template <class T>
class xscalar_stepper
{
public:
using self_type = xscalar_stepper<T>;
using container_type = xscalar<T>;
using value_type = typename container_type::value_type;
using reference = typename container_type::const_reference;
using pointer = typename container_type::const_pointer;
using size_type = typename container_type::size_type;
using difference_type = typename container_type::difference_type;
xscalar_stepper(const container_type* c, bool end = false);
reference operator*() const;
void step(size_type i);
void reset(size_type i);
void to_end();
bool equal(const self_type& rhs) const;
private:
const container_type* p_c;
bool m_end;
};
template <class T>
bool operator==(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs);
template <class T>
bool operator!=(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs);
/****************************
* xscalar implementation
****************************/
template <class T>
inline xscalar<T>::xscalar(const T& value)
: m_value(value)
{
}
template <class T>
inline typename xscalar<T>::size_type xscalar<T>::size() const
{
return 1;
}
template <class T>
inline typename xscalar<T>::size_type xscalar<T>::dimension() const
{
return 0;
}
template <class T>
inline typename xscalar<T>::shape_type xscalar<T>::shape() const
{
return {};
}
template <class T>
inline typename xscalar<T>::strides_type xscalar<T>::strides() const
{
return {};
}
template <class T>
inline typename xscalar<T>::strides_type xscalar<T>::backstrides() const
{
return {};
}
template <class T>
template <class... Args>
inline typename xscalar<T>::const_reference xscalar<T>::operator()(Args... args) const
{
return m_value;
}
template <class T>
inline bool xscalar<T>::broadcast_shape(shape_type&) const
{
return true;
}
template <class T>
inline bool xscalar<T>::is_trivial_broadcast(const strides_type&) const
{
return true;
}
/************************************
* xscalar_stepper implementation
************************************/
template <class T>
inline xscalar_stepper<T>::xscalar_stepper(const container_type* c, bool end)
: p_c(c), m_end(end)
{
}
template <class T>
inline auto xscalar_stepper<T>::operator*() const -> reference
{
return p_c->operator()();
}
template <class T>
inline void xscalar_stepper<T>::step(size_type i)
{
}
template <class T>
inline void xscalar_stepper<T>::reset(size_type i)
{
}
template <class T>
inline void xscalar_stepper<T>::to_end()
{
m_end = true;
}
template <class T>
inline bool xscalar_stepper<T>::equal(const self_type& rhs) const
{
return p_c = rhs.p_c && m_end = rhs.m_end;
}
template <class T>
inline bool operator==(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs)
{
return lhs.equal(rhs);
}
template <class T>
inline bool operator!=(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs)
{
return !(lhs.equal(rhs));
}
}
#endif
<commit_msg>xscalar storage iterator<commit_after>#ifndef XSCALAR_HPP
#define XSCALAR_HPP
#include <utility>
#include "xexpression.hpp"
#include "xindex.hpp"
namespace qs
{
/*************************
* xscalar
*************************/
// xscalar is a cheap wrapper for a scalar value as an xexpression.
template <class T>
class xscalar_stepper;
template <class T>
class xscalar_iterator;
template <class T>
class xscalar : public xexpression<xscalar<T>>
{
public:
using value_type = T;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using size_type = size_t;
using difference_type = ptrdiff_t;
using self_type = xscalar<T>;
using shape_type = xshape<size_type>;
using strides_type = xstrides<size_type>;
using closure_type = const self_type;
using const_stepper = xscalar_stepper<T>;
using const_storage_iterator = xscalar_iterator<T>;
xscalar(const T& value);
size_type size() const;
size_type dimension() const;
shape_type shape() const;
strides_type strides() const;
strides_type backstrides() const;
template <class... Args>
const_reference operator()(Args... args) const;
bool broadcast_shape(shape_type& shape) const;
bool is_trivial_broadcast(const strides_type& strides) const;
const_stepper stepper_begin(const shape_type& shape) const;
const_stepper stepper_end(const shape_type& shape) const;
const_storage_iterator storage_begin() const;
const_storage_iterator storage_end() const;
private:
const T& m_value;
};
/*********************
* xscalar_stepper
*********************/
template <class T>
class xscalar_stepper
{
public:
using self_type = xscalar_stepper<T>;
using container_type = xscalar<T>;
using value_type = typename container_type::value_type;
using reference = typename container_type::const_reference;
using pointer = typename container_type::const_pointer;
using size_type = typename container_type::size_type;
using difference_type = typename container_type::difference_type;
explicit xscalar_stepper(const container_type* c);
reference operator*() const;
void step(size_type i);
void reset(size_type i);
void to_end();
bool equal(const self_type& rhs) const;
private:
const container_type* p_c;
};
template <class T>
bool operator==(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs);
template <class T>
bool operator!=(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs);
/**********************
* xscalar_iterator
**********************/
template <class T>
class xscalar_iterator
{
public:
using self_type = xscalar_stepper<T>;
using container_type = xscalar<T>;
using value_type = typename container_type::value_type;
using reference = typename container_type::const_reference;
using pointer = typename container_type::const_pointer;
using difference_type = typename container_type::difference_type;
using iterator_category = std::input_iterator_tag;
explicit xscalar_iterator(const container_type* c);
self_type& operator++();
self_type operator++(int);
reference operator*() const;
bool equal(const self_type& rhs) const;
private:
const container_type* p_c;
};
template <class T>
bool operator==(const xscalar_iterator<T>& lhs,
const xscalar_iterator<T>& rhs);
template <class T>
bool operator!=(const xscalar_iterator<T>& lhs,
const xscalar_iterator<T>& rhs);
/****************************
* xscalar implementation
****************************/
template <class T>
inline xscalar<T>::xscalar(const T& value)
: m_value(value)
{
}
template <class T>
inline auto xscalar<T>::size() const -> size_type
{
return 1;
}
template <class T>
inline auto xscalar<T>::dimension() const -> size_type
{
return 0;
}
template <class T>
inline auto xscalar<T>::shape() const -> shape_type
{
return {};
}
template <class T>
inline auto xscalar<T>::strides() const -> strides_type
{
return {};
}
template <class T>
inline auto xscalar<T>::backstrides() const -> strides_type
{
return {};
}
template <class T>
template <class... Args>
inline auto xscalar<T>::operator()(Args... args) const -> const_reference
{
return m_value;
}
template <class T>
inline bool xscalar<T>::broadcast_shape(shape_type&) const
{
return true;
}
template <class T>
inline bool xscalar<T>::is_trivial_broadcast(const strides_type&) const
{
return true;
}
template <class T>
inline auto xscalar<T>::stepper_begin(const shape_type&) const -> const_stepper
{
return const_stepper(this);
}
template <class T>
inline auto xscalar<T>::stepper_end(const shape_type& shape) const -> const_stepper
{
return const_stepper(this);
}
template <class T>
inline auto xscalar<T>::storage_begin() const -> const_storage_iterator
{
return const_storage_iterator(this);
}
template <class T>
inline auto xscalar<T>::storage_end() const -> const_storage_iterator
{
return const_storage_iterator(this);
}
/************************************
* xscalar_stepper implementation
************************************/
template <class T>
inline xscalar_stepper<T>::xscalar_stepper(const container_type* c)
: p_c(c)
{
}
template <class T>
inline auto xscalar_stepper<T>::operator*() const -> reference
{
return p_c->operator()();
}
template <class T>
inline void xscalar_stepper<T>::step(size_type i)
{
}
template <class T>
inline void xscalar_stepper<T>::reset(size_type i)
{
}
template <class T>
inline void xscalar_stepper<T>::to_end()
{
}
template <class T>
inline bool xscalar_stepper<T>::equal(const self_type& rhs) const
{
return p_c = rhs.p_c;
}
template <class T>
inline bool operator==(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs)
{
return lhs.equal(rhs);
}
template <class T>
inline bool operator!=(const xscalar_stepper<T>& lhs,
const xscalar_stepper<T>& rhs)
{
return !(lhs.equal(rhs));
}
/*************************************
* xscalar_iterator implementation
*************************************/
template <class T>
inline xscalar_iterator<T>::xscalar_iterator(const container_type* c)
: p_c(c)
{
}
template <class T>
inline auto xscalar_iterator<T>::operator++() -> self_type&
{
return *this;
}
template <class T>
inline auto xscalar_iterator<T>::operator++(int) -> self_type
{
self_type tmp(*this);
++(*this);
return tmp;
}
template <class T>
inline auto xscalar_iterator<T>::operator*() const -> reference
{
return p_c->operator()();
}
template <class T>
inline bool xscalar_iterator<T>::equal(const self_type& rhs) const
{
return p_c == rhs.p_c;
}
template <class T>
inline bool operator==(const xscalar_iterator<T>& lhs,
const xscalar_iterator<T>& rhs)
{
return lhs.equal(rhs);
}
template <class T>
inline bool operator!=(const xscalar_iterator<T>& lhs,
const xscalar_iterator<T>& rhs)
{
return !(lhs.equal(rhs));
}
}
#endif
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "J2534Connection.h"
#include "Timer.h"
J2534Connection::J2534Connection(
std::shared_ptr<PandaJ2534Device> panda_dev,
unsigned long ProtocolID,
unsigned long Flags,
unsigned long BaudRate
) : panda_dev(panda_dev), ProtocolID(ProtocolID), Flags(Flags), BaudRate(BaudRate), port(0) { }
unsigned long J2534Connection::validateTxMsg(PASSTHRU_MSG* msg) {
if (msg->DataSize < this->getMinMsgLen() || msg->DataSize > this->getMaxMsgLen())
return ERR_INVALID_MSG;
return STATUS_NOERROR;
}
long J2534Connection::PassThruReadMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) {
//Timeout of 0 means return immediately. Non zero means WAIT for that time then return. Dafuk.
long err_code = STATUS_NOERROR;
Timer t = Timer();
unsigned long msgnum = 0;
while (msgnum < *pNumMsgs) {
if (Timeout > 0 && t.getTimePassed() >= Timeout) {
err_code = ERR_TIMEOUT;
break;
}
//Synchronized won't work where we have to break out of a loop
messageRxBuff_mutex.lock();
if (this->messageRxBuff.empty()) {
messageRxBuff_mutex.unlock();
if (Timeout == 0)
break;
Sleep(2);
continue;
}
auto msg_in = this->messageRxBuff.front();
this->messageRxBuff.pop();
messageRxBuff_mutex.unlock();
PASSTHRU_MSG *msg_out = &pMsg[msgnum++];
msg_out->ProtocolID = this->ProtocolID;
msg_out->DataSize = msg_in.Data.size();
memcpy(msg_out->Data, msg_in.Data.c_str(), msg_in.Data.size());
msg_out->Timestamp = msg_in.Timestamp;
msg_out->RxStatus = msg_in.RxStatus;
msg_out->ExtraDataIndex = msg_in.ExtraDataIndex;
msg_out->TxFlags = 0;
if (msgnum == *pNumMsgs) break;
}
if (msgnum == 0)
err_code = ERR_BUFFER_EMPTY;
*pNumMsgs = msgnum;
return err_code;
}
long J2534Connection::PassThruWriteMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) {
//There doesn't seem to be much reason to implement the timeout here.
for (int msgnum = 0; msgnum < *pNumMsgs; msgnum++) {
PASSTHRU_MSG* msg = &pMsg[msgnum];
if (msg->ProtocolID != this->ProtocolID) {
*pNumMsgs = msgnum;
return ERR_MSG_PROTOCOL_ID;
}
auto retcode = this->validateTxMsg(msg);
if (retcode != STATUS_NOERROR) {
*pNumMsgs = msgnum;
return retcode;
}
auto msgtx = this->parseMessageTx(*pMsg);
if (msgtx != nullptr) //Nullptr is supported for unimplemented connection types.
this->schedultMsgTx(std::dynamic_pointer_cast<Action>(msgtx));
}
return STATUS_NOERROR;
}
//The docs say that a device has to support 10 periodic messages, though more is ok.
//It is easier to store them on the connection, so 10 per connection it is.
long J2534Connection::PassThruStartPeriodicMsg(PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval) {
if (pMsg->DataSize < getMinMsgLen() || pMsg->DataSize > getMaxMsgSingleFrameLen()) return ERR_INVALID_MSG;
if (pMsg->ProtocolID != this->ProtocolID) return ERR_MSG_PROTOCOL_ID;
if (TimeInterval < 5 || TimeInterval > 65535) return ERR_INVALID_TIME_INTERVAL;
for (int i = 0; i < this->periodicMessages.size(); i++) {
if (periodicMessages[i] != nullptr) continue;
*pMsgID = i;
auto msgtx = this->parseMessageTx(*pMsg);
if (msgtx != nullptr) {
periodicMessages[i] = std::make_shared<MessagePeriodic>(std::chrono::microseconds(TimeInterval*1000), msgtx);
periodicMessages[i]->scheduleImmediate();
if (auto panda_dev = this->getPandaDev()) {
panda_dev->insertActionIntoTaskList(periodicMessages[i]);
}
}
return STATUS_NOERROR;
}
return ERR_EXCEEDED_LIMIT;
}
long J2534Connection::PassThruStopPeriodicMsg(unsigned long MsgID) {
if (MsgID >= this->periodicMessages.size() || this->periodicMessages[MsgID] == nullptr)
return ERR_INVALID_MSG_ID;
this->periodicMessages[MsgID]->cancel();
this->periodicMessages[MsgID] = nullptr;
return STATUS_NOERROR;
}
long J2534Connection::PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg,
PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) {
for (int i = 0; i < this->filters.size(); i++) {
if (filters[i] == nullptr) {
try {
auto newfilter = std::make_shared<J2534MessageFilter>(this, FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg);
for (int check_idx = 0; check_idx < filters.size(); check_idx++) {
if (filters[check_idx] == nullptr) continue;
if (filters[check_idx] == newfilter) {
filters[i] = nullptr;
return ERR_NOT_UNIQUE;
}
}
*pFilterID = i;
filters[i] = newfilter;
return STATUS_NOERROR;
} catch (int e) {
return e;
}
}
}
return ERR_EXCEEDED_LIMIT;
}
long J2534Connection::PassThruStopMsgFilter(unsigned long FilterID) {
if (FilterID >= this->filters.size() || this->filters[FilterID] == nullptr)
return ERR_INVALID_FILTER_ID;
this->filters[FilterID] = nullptr;
return STATUS_NOERROR;
}
long J2534Connection::PassThruIoctl(unsigned long IoctlID, void *pInput, void *pOutput) {
return STATUS_NOERROR;
}
long J2534Connection::init5b(SBYTE_ARRAY* pInput, SBYTE_ARRAY* pOutput) { return ERR_FAILED; }
long J2534Connection::initFast(PASSTHRU_MSG* pInput, PASSTHRU_MSG* pOutput) { return ERR_FAILED; }
long J2534Connection::clearTXBuff() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
this->txbuff = {};
panda_ps->panda->can_clear(panda::PANDA_CAN1_TX);
}
}
return STATUS_NOERROR;
}
long J2534Connection::clearRXBuff() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(messageRxBuff_mutex) {
this->messageRxBuff = {};
panda_ps->panda->can_clear(panda::PANDA_CAN_RX);
}
}
return STATUS_NOERROR;
}
long J2534Connection::clearPeriodicMsgs() {
for (int i = 0; i < this->periodicMessages.size(); i++) {
if (periodicMessages[i] == nullptr) continue;
this->periodicMessages[i]->cancel();
this->periodicMessages[i] = nullptr;
}
return STATUS_NOERROR;
}
long J2534Connection::clearMsgFilters() {
for (auto& filter : this->filters) filter = nullptr;
return STATUS_NOERROR;
}
void J2534Connection::setBaud(unsigned long baud) {
this->BaudRate = baud;
}
void J2534Connection::schedultMsgTx(std::shared_ptr<Action> msgout) {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
this->txbuff.push(msgout);
panda_ps->registerConnectionTx(shared_from_this());
}
}
}
void J2534Connection::rescheduleExistingTxMsgs() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
panda_ps->unstallConnectionTx(shared_from_this());
}
}
}
//Works well as long as the protocol doesn't support flow control.
void J2534Connection::processMessage(const J2534Frame& msg) {
FILTER_RESULT filter_res = FILTER_RESULT_NEUTRAL;
for (auto filter : this->filters) {
if (filter == nullptr) continue;
FILTER_RESULT current_check_res = filter->check(msg);
if (current_check_res == FILTER_RESULT_BLOCK) return;
if (current_check_res == FILTER_RESULT_PASS) filter_res = FILTER_RESULT_PASS;
}
if (filter_res == FILTER_RESULT_PASS) {
addMsgToRxQueue(msg);
}
}
void J2534Connection::processIOCTLSetConfig(unsigned long Parameter, unsigned long Value) {
switch (Parameter) {
case DATA_RATE: // 5-500000
this->setBaud(Value);
case LOOPBACK: // 0 (OFF), 1 (ON) [0]
this->loopback = (Value != 0);
break;
case ISO15765_WFT_MAX:
break;
case NODE_ADDRESS: // J1850PWM Related (Not supported by panda). HDS requires these to 'work'.
case NETWORK_LINE:
case P1_MIN: // A bunch of stuff relating to ISO9141 and ISO14230 that the panda
case P1_MAX: // currently doesn't support. Don't let HDS know we can't use these.
case P2_MIN:
case P2_MAX:
case P3_MIN:
case P3_MAX:
case P4_MIN:
case P4_MAX:
case W0:
case W1:
case W2:
case W3:
case W4:
case W5:
case TIDLE:
case TINIL:
case TWUP:
case PARITY:
case T1_MAX: // SCI related options. The panda does not appear to support this
case T2_MAX:
case T3_MAX:
case T4_MAX:
case T5_MAX:
break; // Just smile and nod.
default:
printf("Got unknown SET code %X\n", Parameter);
}
// reserved parameters usually mean special equiptment is required
if (Parameter >= 0x20) {
throw ERR_NOT_SUPPORTED;
}
}
unsigned long J2534Connection::processIOCTLGetConfig(unsigned long Parameter) {
switch (Parameter) {
case DATA_RATE:
return this->getBaud();
case LOOPBACK:
return this->loopback;
break;
case BIT_SAMPLE_POINT:
return 80;
case SYNC_JUMP_WIDTH:
return 15;
default:
// HDS rarely reads off values through ioctl GET_CONFIG, but it often
// just wants the call to pass without erroring, so just don't do anything.
printf("Got unknown code %X\n", Parameter);
}
}
<commit_msg>fix LOOPBACK getting set when DATA_RATE is set<commit_after>#include "stdafx.h"
#include "J2534Connection.h"
#include "Timer.h"
J2534Connection::J2534Connection(
std::shared_ptr<PandaJ2534Device> panda_dev,
unsigned long ProtocolID,
unsigned long Flags,
unsigned long BaudRate
) : panda_dev(panda_dev), ProtocolID(ProtocolID), Flags(Flags), BaudRate(BaudRate), port(0) { }
unsigned long J2534Connection::validateTxMsg(PASSTHRU_MSG* msg) {
if (msg->DataSize < this->getMinMsgLen() || msg->DataSize > this->getMaxMsgLen())
return ERR_INVALID_MSG;
return STATUS_NOERROR;
}
long J2534Connection::PassThruReadMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) {
//Timeout of 0 means return immediately. Non zero means WAIT for that time then return. Dafuk.
long err_code = STATUS_NOERROR;
Timer t = Timer();
unsigned long msgnum = 0;
while (msgnum < *pNumMsgs) {
if (Timeout > 0 && t.getTimePassed() >= Timeout) {
err_code = ERR_TIMEOUT;
break;
}
//Synchronized won't work where we have to break out of a loop
messageRxBuff_mutex.lock();
if (this->messageRxBuff.empty()) {
messageRxBuff_mutex.unlock();
if (Timeout == 0)
break;
Sleep(2);
continue;
}
auto msg_in = this->messageRxBuff.front();
this->messageRxBuff.pop();
messageRxBuff_mutex.unlock();
PASSTHRU_MSG *msg_out = &pMsg[msgnum++];
msg_out->ProtocolID = this->ProtocolID;
msg_out->DataSize = msg_in.Data.size();
memcpy(msg_out->Data, msg_in.Data.c_str(), msg_in.Data.size());
msg_out->Timestamp = msg_in.Timestamp;
msg_out->RxStatus = msg_in.RxStatus;
msg_out->ExtraDataIndex = msg_in.ExtraDataIndex;
msg_out->TxFlags = 0;
if (msgnum == *pNumMsgs) break;
}
if (msgnum == 0)
err_code = ERR_BUFFER_EMPTY;
*pNumMsgs = msgnum;
return err_code;
}
long J2534Connection::PassThruWriteMsgs(PASSTHRU_MSG *pMsg, unsigned long *pNumMsgs, unsigned long Timeout) {
//There doesn't seem to be much reason to implement the timeout here.
for (int msgnum = 0; msgnum < *pNumMsgs; msgnum++) {
PASSTHRU_MSG* msg = &pMsg[msgnum];
if (msg->ProtocolID != this->ProtocolID) {
*pNumMsgs = msgnum;
return ERR_MSG_PROTOCOL_ID;
}
auto retcode = this->validateTxMsg(msg);
if (retcode != STATUS_NOERROR) {
*pNumMsgs = msgnum;
return retcode;
}
auto msgtx = this->parseMessageTx(*pMsg);
if (msgtx != nullptr) //Nullptr is supported for unimplemented connection types.
this->schedultMsgTx(std::dynamic_pointer_cast<Action>(msgtx));
}
return STATUS_NOERROR;
}
//The docs say that a device has to support 10 periodic messages, though more is ok.
//It is easier to store them on the connection, so 10 per connection it is.
long J2534Connection::PassThruStartPeriodicMsg(PASSTHRU_MSG *pMsg, unsigned long *pMsgID, unsigned long TimeInterval) {
if (pMsg->DataSize < getMinMsgLen() || pMsg->DataSize > getMaxMsgSingleFrameLen()) return ERR_INVALID_MSG;
if (pMsg->ProtocolID != this->ProtocolID) return ERR_MSG_PROTOCOL_ID;
if (TimeInterval < 5 || TimeInterval > 65535) return ERR_INVALID_TIME_INTERVAL;
for (int i = 0; i < this->periodicMessages.size(); i++) {
if (periodicMessages[i] != nullptr) continue;
*pMsgID = i;
auto msgtx = this->parseMessageTx(*pMsg);
if (msgtx != nullptr) {
periodicMessages[i] = std::make_shared<MessagePeriodic>(std::chrono::microseconds(TimeInterval*1000), msgtx);
periodicMessages[i]->scheduleImmediate();
if (auto panda_dev = this->getPandaDev()) {
panda_dev->insertActionIntoTaskList(periodicMessages[i]);
}
}
return STATUS_NOERROR;
}
return ERR_EXCEEDED_LIMIT;
}
long J2534Connection::PassThruStopPeriodicMsg(unsigned long MsgID) {
if (MsgID >= this->periodicMessages.size() || this->periodicMessages[MsgID] == nullptr)
return ERR_INVALID_MSG_ID;
this->periodicMessages[MsgID]->cancel();
this->periodicMessages[MsgID] = nullptr;
return STATUS_NOERROR;
}
long J2534Connection::PassThruStartMsgFilter(unsigned long FilterType, PASSTHRU_MSG *pMaskMsg, PASSTHRU_MSG *pPatternMsg,
PASSTHRU_MSG *pFlowControlMsg, unsigned long *pFilterID) {
for (int i = 0; i < this->filters.size(); i++) {
if (filters[i] == nullptr) {
try {
auto newfilter = std::make_shared<J2534MessageFilter>(this, FilterType, pMaskMsg, pPatternMsg, pFlowControlMsg);
for (int check_idx = 0; check_idx < filters.size(); check_idx++) {
if (filters[check_idx] == nullptr) continue;
if (filters[check_idx] == newfilter) {
filters[i] = nullptr;
return ERR_NOT_UNIQUE;
}
}
*pFilterID = i;
filters[i] = newfilter;
return STATUS_NOERROR;
} catch (int e) {
return e;
}
}
}
return ERR_EXCEEDED_LIMIT;
}
long J2534Connection::PassThruStopMsgFilter(unsigned long FilterID) {
if (FilterID >= this->filters.size() || this->filters[FilterID] == nullptr)
return ERR_INVALID_FILTER_ID;
this->filters[FilterID] = nullptr;
return STATUS_NOERROR;
}
long J2534Connection::PassThruIoctl(unsigned long IoctlID, void *pInput, void *pOutput) {
return STATUS_NOERROR;
}
long J2534Connection::init5b(SBYTE_ARRAY* pInput, SBYTE_ARRAY* pOutput) { return ERR_FAILED; }
long J2534Connection::initFast(PASSTHRU_MSG* pInput, PASSTHRU_MSG* pOutput) { return ERR_FAILED; }
long J2534Connection::clearTXBuff() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
this->txbuff = {};
panda_ps->panda->can_clear(panda::PANDA_CAN1_TX);
}
}
return STATUS_NOERROR;
}
long J2534Connection::clearRXBuff() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(messageRxBuff_mutex) {
this->messageRxBuff = {};
panda_ps->panda->can_clear(panda::PANDA_CAN_RX);
}
}
return STATUS_NOERROR;
}
long J2534Connection::clearPeriodicMsgs() {
for (int i = 0; i < this->periodicMessages.size(); i++) {
if (periodicMessages[i] == nullptr) continue;
this->periodicMessages[i]->cancel();
this->periodicMessages[i] = nullptr;
}
return STATUS_NOERROR;
}
long J2534Connection::clearMsgFilters() {
for (auto& filter : this->filters) filter = nullptr;
return STATUS_NOERROR;
}
void J2534Connection::setBaud(unsigned long baud) {
this->BaudRate = baud;
}
void J2534Connection::schedultMsgTx(std::shared_ptr<Action> msgout) {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
this->txbuff.push(msgout);
panda_ps->registerConnectionTx(shared_from_this());
}
}
}
void J2534Connection::rescheduleExistingTxMsgs() {
if (auto panda_ps = this->panda_dev.lock()) {
synchronized(staged_writes_lock) {
panda_ps->unstallConnectionTx(shared_from_this());
}
}
}
//Works well as long as the protocol doesn't support flow control.
void J2534Connection::processMessage(const J2534Frame& msg) {
FILTER_RESULT filter_res = FILTER_RESULT_NEUTRAL;
for (auto filter : this->filters) {
if (filter == nullptr) continue;
FILTER_RESULT current_check_res = filter->check(msg);
if (current_check_res == FILTER_RESULT_BLOCK) return;
if (current_check_res == FILTER_RESULT_PASS) filter_res = FILTER_RESULT_PASS;
}
if (filter_res == FILTER_RESULT_PASS) {
addMsgToRxQueue(msg);
}
}
void J2534Connection::processIOCTLSetConfig(unsigned long Parameter, unsigned long Value) {
switch (Parameter) {
case DATA_RATE: // 5-500000
this->setBaud(Value);
break;
case LOOPBACK: // 0 (OFF), 1 (ON) [0]
this->loopback = (Value != 0);
break;
case ISO15765_WFT_MAX:
break;
case NODE_ADDRESS: // J1850PWM Related (Not supported by panda). HDS requires these to 'work'.
case NETWORK_LINE:
case P1_MIN: // A bunch of stuff relating to ISO9141 and ISO14230 that the panda
case P1_MAX: // currently doesn't support. Don't let HDS know we can't use these.
case P2_MIN:
case P2_MAX:
case P3_MIN:
case P3_MAX:
case P4_MIN:
case P4_MAX:
case W0:
case W1:
case W2:
case W3:
case W4:
case W5:
case TIDLE:
case TINIL:
case TWUP:
case PARITY:
case T1_MAX: // SCI related options. The panda does not appear to support this
case T2_MAX:
case T3_MAX:
case T4_MAX:
case T5_MAX:
break; // Just smile and nod.
default:
printf("Got unknown SET code %X\n", Parameter);
}
// reserved parameters usually mean special equiptment is required
if (Parameter >= 0x20) {
throw ERR_NOT_SUPPORTED;
}
}
unsigned long J2534Connection::processIOCTLGetConfig(unsigned long Parameter) {
switch (Parameter) {
case DATA_RATE:
return this->getBaud();
case LOOPBACK:
return this->loopback;
break;
case BIT_SAMPLE_POINT:
return 80;
case SYNC_JUMP_WIDTH:
return 15;
default:
// HDS rarely reads off values through ioctl GET_CONFIG, but it often
// just wants the call to pass without erroring, so just don't do anything.
printf("Got unknown code %X\n", Parameter);
}
}
<|endoftext|> |
<commit_before>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
// When you add a new tests file, define a new name here and with
// DECLARE_TESTS_FILE near the top of test_header.hpp, and put at
// the bottom of your tests file:
// REGISTER_TESTS // This must come last in the file.
#define TESTS_FILE patricia_trie_tests
#include "test_header.hpp"
#include "patricia_trie_tests.hpp"
//namespace /*anonymous*/ {
using namespace patricia_trie_testing;
struct patricia_trie_tester {
// This is a friend of patricia_trie
static void test() {
trie_node root;
BOOST_CHECK(root.is_root_node());
BOOST_CHECK(!root.points_to_leaf());
BOOST_CHECK(!root.points_to_sub_nodes());
BOOST_CHECK(root.is_empty());
BOOST_CHECK(!root.sub_nodes());
BOOST_CHECK(!root.leaf());
BOOST_CHECK(!root.parent());
BOOST_CHECK(!root.siblings());
BOOST_CHECK_EQUAL(root.monoid(), 0u);
BOOST_CHECK_THROW(root.update_monoid(5), std::logic_error);
const std::array<coord, 3> somewhere = {{ 7, 27, -3 }};
const std::array<coord, 3> zerozerozero = {{ 0, 0, 0 }};
// This is undesirable but harmless:
BOOST_CHECK(root.contains(zerozerozero));
// or it could be desirable if the root contained everywhere
BOOST_CHECK(!root.contains(somewhere));
// related current fact:
BOOST_CHECK_EQUAL(root.bounding_box().size_exponent_in_each_dimension(), 0);
BOOST_CHECK(!root.find_leaf_node(somewhere));
BOOST_CHECK(!root.find_leaf(somewhere));
BOOST_CHECK_EQUAL(&root, &root.find_root());
BOOST_CHECK_EQUAL(0u, root.monoid());
BOOST_CHECK(!root.erase(somewhere));
BOOST_CHECK(!root.erase(zerozerozero));
BOOST_CHECK_NO_THROW(root.insert(somewhere, std::unique_ptr<block>(new block{86}), 2));
BOOST_CHECK_THROW(root.insert(somewhere, std::unique_ptr<block>(new block{86}), 5), std::logic_error);
BOOST_CHECK_EQUAL(root.monoid(), 2u);
BOOST_CHECK_NO_THROW(root.update_monoid(5));
BOOST_CHECK_EQUAL(root.monoid(), 5u);
BOOST_CHECK(!root.sub_nodes());
BOOST_CHECK(!root.is_empty());
BOOST_CHECK(root.erase(somewhere));
BOOST_CHECK_EQUAL(root.monoid(), 0u);
BOOST_CHECK(!root.erase(somewhere));
BOOST_CHECK(root.is_empty());
const std::array<coord, 3> v1 = {{ 10, 100, 1000 }};
const std::array<coord, 3> v2 = {{ 10, 100, 1001 }};
const std::array<coord, 3> v3 = {{ 10, 100, 1010 }};
const std::array<coord, 3> v4 = {{ 10, 200, 1005 }};
BOOST_CHECK_NO_THROW(root.insert(v1, std::unique_ptr<block>(new block{87}), 2));
BOOST_CHECK_NO_THROW(root.insert(v2, std::unique_ptr<block>(new block{88}), 3));
BOOST_CHECK_NO_THROW(root.insert(v3, std::unique_ptr<block>(new block{89}), 4));
BOOST_CHECK_NO_THROW(root.insert(v4, std::unique_ptr<block>(new block{90}), 5));
BOOST_CHECK_EQUAL(root.monoid(), 14u);
BOOST_CHECK_THROW(root.update_monoid(5), std::logic_error);
BOOST_CHECK_EQUAL(root.monoid(), 14u);
BOOST_CHECK_EQUAL(&root.find_node(v3).find_root(), &root);
BOOST_CHECK(!!root.find_leaf(v3));
BOOST_CHECK(root.find_leaf_node(v3));
BOOST_CHECK_EQUAL(root.find_leaf(v3)->contents, 89);
BOOST_CHECK_EQUAL(&root.find_leaf_node(v3)->find_root(), &root);
BOOST_CHECK_EQUAL(root.find_leaf_node(v3)->bounding_box(),
trie_node::power_of_two_bounding_cube_type(v3,0)
);
BOOST_CHECK(root.find_leaf_node(v3)->parent());
BOOST_CHECK_EQUAL(root.find_leaf_node(v3)->parent()->bounding_box(),
trie_node::power_of_two_bounding_cube_type(trie_node::loc_type{{0,32*3,32*31}},5)
);
BOOST_CHECK(root.erase(v3));
BOOST_CHECK_EQUAL(root.monoid(), 10u);
BOOST_CHECK(!root.find_leaf(v3));
BOOST_CHECK(!root.find_leaf_node(v3));
root.debug_check_recursive();
//root.debug_print();
}
};
BOOST_AUTO_TEST_CASE( patricia_trie_tests_ ) {
patricia_trie_tester::test();
}
//} /* end namespace tests */
REGISTER_TESTS // This must come last in the file.
<commit_msg>test trie erasure<commit_after>/*
Copyright Eli Dupree and Isaac Dupree, 2011, 2012, 2013
This file is part of Lasercake.
Lasercake is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Lasercake is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Lasercake. If not, see <http://www.gnu.org/licenses/>.
*/
// When you add a new tests file, define a new name here and with
// DECLARE_TESTS_FILE near the top of test_header.hpp, and put at
// the bottom of your tests file:
// REGISTER_TESTS // This must come last in the file.
#define TESTS_FILE patricia_trie_tests
#include "test_header.hpp"
#include "patricia_trie_tests.hpp"
//namespace /*anonymous*/ {
using namespace patricia_trie_testing;
struct patricia_trie_tester {
// This is a friend of patricia_trie
static int64_t tree_size(trie_node& node) {
int64_t result = 1;
if(auto* sub_nodes = node.sub_nodes()) {
for(trie_node& sub_node : *sub_nodes) {
result += tree_size(sub_node);
}
}
return result;
}
static void test() {
trie_node root;
BOOST_CHECK(root.is_root_node());
BOOST_CHECK(!root.points_to_leaf());
BOOST_CHECK(!root.points_to_sub_nodes());
BOOST_CHECK(root.is_empty());
BOOST_CHECK(!root.sub_nodes());
BOOST_CHECK(!root.leaf());
BOOST_CHECK(!root.parent());
BOOST_CHECK(!root.siblings());
BOOST_CHECK_EQUAL(root.monoid(), 0u);
BOOST_CHECK_EQUAL(tree_size(root), 1);
BOOST_CHECK_THROW(root.update_monoid(5), std::logic_error);
const std::array<coord, 3> somewhere = {{ 7, 27, -3 }};
const std::array<coord, 3> zerozerozero = {{ 0, 0, 0 }};
// This is undesirable but harmless:
BOOST_CHECK(root.contains(zerozerozero));
// or it could be desirable if the root contained everywhere
BOOST_CHECK(!root.contains(somewhere));
// related current fact:
BOOST_CHECK_EQUAL(root.bounding_box().size_exponent_in_each_dimension(), 0);
BOOST_CHECK(!root.find_leaf_node(somewhere));
BOOST_CHECK(!root.find_leaf(somewhere));
BOOST_CHECK_EQUAL(&root, &root.find_root());
BOOST_CHECK_EQUAL(0u, root.monoid());
BOOST_CHECK(!root.erase(somewhere));
BOOST_CHECK(!root.erase(zerozerozero));
BOOST_CHECK_NO_THROW(root.insert(somewhere, std::unique_ptr<block>(new block{86}), 2));
BOOST_CHECK_THROW(root.insert(somewhere, std::unique_ptr<block>(new block{86}), 5), std::logic_error);
BOOST_CHECK_EQUAL(root.monoid(), 2u);
BOOST_CHECK_EQUAL(tree_size(root), 1);
BOOST_CHECK_NO_THROW(root.update_monoid(5));
BOOST_CHECK_EQUAL(root.monoid(), 5u);
BOOST_CHECK(!root.sub_nodes());
BOOST_CHECK(!root.is_empty());
BOOST_CHECK(root.erase(somewhere));
BOOST_CHECK_EQUAL(root.monoid(), 0u);
BOOST_CHECK(!root.erase(somewhere));
BOOST_CHECK(root.is_empty());
BOOST_CHECK_EQUAL(tree_size(root), 1);
const std::array<coord, 3> v1 = {{ 10, 100, 1000 }};
const std::array<coord, 3> v2 = {{ 10, 100, 1001 }};
const std::array<coord, 3> v3 = {{ 10, 100, 1010 }};
const std::array<coord, 3> v4 = {{ 10, 200, 1005 }};
BOOST_CHECK_NO_THROW(root.insert(v1, std::unique_ptr<block>(new block{87}), 2));
BOOST_CHECK_EQUAL(tree_size(root), 1);
BOOST_CHECK_NO_THROW(root.insert(v2, std::unique_ptr<block>(new block{88}), 3));
BOOST_CHECK_EQUAL(tree_size(root), 9);
BOOST_CHECK_NO_THROW(root.insert(v3, std::unique_ptr<block>(new block{89}), 4));
BOOST_CHECK_EQUAL(tree_size(root), 17);
BOOST_CHECK_NO_THROW(root.insert(v4, std::unique_ptr<block>(new block{90}), 5));
BOOST_CHECK_EQUAL(tree_size(root), 25);
BOOST_CHECK_EQUAL(root.monoid(), 14u);
BOOST_CHECK_THROW(root.update_monoid(5), std::logic_error);
BOOST_CHECK_EQUAL(root.monoid(), 14u);
BOOST_CHECK_EQUAL(&root.find_node(v3).find_root(), &root);
BOOST_CHECK(!!root.find_leaf(v3));
BOOST_CHECK(root.find_leaf_node(v3));
BOOST_CHECK_EQUAL(root.find_leaf(v3)->contents, 89);
BOOST_CHECK_EQUAL(&root.find_leaf_node(v3)->find_root(), &root);
BOOST_CHECK_EQUAL(root.find_leaf_node(v3)->bounding_box(),
trie_node::power_of_two_bounding_cube_type(v3,0)
);
BOOST_CHECK(root.find_leaf_node(v3)->parent());
BOOST_CHECK_EQUAL(root.find_leaf_node(v3)->parent()->bounding_box(),
trie_node::power_of_two_bounding_cube_type(trie_node::loc_type{{0,32*3,32*31}},5)
);
BOOST_CHECK(root.erase(v3));
BOOST_CHECK_EQUAL(tree_size(root), 25);
BOOST_CHECK_EQUAL(root.monoid(), 10u);
BOOST_CHECK(!root.find_leaf(v3));
BOOST_CHECK(!root.find_leaf_node(v3));
root.debug_check_recursive();
//root.debug_print();
BOOST_CHECK_EQUAL(root.monoid(), 10u);
root.debug_check_recursive();
root.erase(v1);
BOOST_CHECK_EQUAL(root.monoid(), 8u);
BOOST_CHECK_EQUAL(tree_size(root), 25);
root.erase(v2);
BOOST_CHECK_EQUAL(root.monoid(), 5u);
BOOST_CHECK_EQUAL(tree_size(root), 9);
}
};
BOOST_AUTO_TEST_CASE( patricia_trie_tests_ ) {
patricia_trie_tester::test();
}
//} /* end namespace tests */
REGISTER_TESTS // This must come last in the file.
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2020 ScyllaDB Ltd.
*/
#include <seastar/testing/perf_tests.hh>
#include <seastar/core/sharded.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/when_all.hh>
#include <boost/range/irange.hpp>
static constexpr fair_queue::class_id cid = 0;
struct local_fq_and_class {
seastar::fair_group fg;
seastar::fair_queue fq;
seastar::fair_queue sfq;
unsigned executed = 0;
static fair_group::config fg_config() {
fair_group::config cfg;
cfg.weight_rate = std::numeric_limits<int>::max();
cfg.size_rate = std::numeric_limits<int>::max();
return cfg;
}
seastar::fair_queue& queue(bool local) noexcept { return local ? fq : sfq; }
local_fq_and_class(seastar::fair_group& sfg)
: fg(fg_config())
, fq(fg, seastar::fair_queue::config())
, sfq(sfg, seastar::fair_queue::config())
{
fq.register_priority_class(cid, 1);
}
~local_fq_and_class() {
fq.unregister_priority_class(cid);
}
};
struct local_fq_entry {
seastar::fair_queue_entry ent;
std::function<void()> submit;
template <typename Func>
local_fq_entry(unsigned weight, unsigned index, Func&& f)
: ent(seastar::fair_queue_ticket(weight, index))
, submit(std::move(f)) {}
};
struct perf_fair_queue {
static constexpr unsigned requests_to_dispatch = 1000;
seastar::sharded<local_fq_and_class> local_fq;
seastar::fair_group shared_fg;
static fair_group::config fg_config() {
fair_group::config cfg;
cfg.weight_rate = std::numeric_limits<int>::max();
cfg.size_rate = std::numeric_limits<int>::max();
return cfg;
}
perf_fair_queue()
: shared_fg(fg_config())
{
local_fq.start(std::ref(shared_fg)).get();
}
~perf_fair_queue() {
local_fq.stop().get();
}
future<> test(bool local);
};
future<> perf_fair_queue::test(bool loc) {
auto invokers = local_fq.invoke_on_all([loc] (local_fq_and_class& local) {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [&local, loc] (unsigned dummy) {
auto req = std::make_unique<local_fq_entry>(1, 1, [&local, loc] {
local.executed++;
local.queue(loc).notify_request_finished(seastar::fair_queue_ticket{1, 1});
});
local.queue(loc).queue(cid, req->ent);
req.release();
return make_ready_future<>();
});
});
auto collectors = local_fq.invoke_on_all([loc] (local_fq_and_class& local) {
// Zeroing this counter must be here, otherwise should the collectors win the
// execution order in when_all_succeed(), the do_until()'s stopping callback
// would return true immediately and the queue would not be dispatched.
//
// At the same time, although this counter is incremented by the lambda from
// invokers, it's not called until the fq.dispatch_requests() is, so there's no
// opposite problem if zeroing it here.
local.executed = 0;
return do_until([&local] { return local.executed == requests_to_dispatch; }, [&local, loc] {
local.queue(loc).dispatch_requests([] (fair_queue_entry& ent) {
local_fq_entry* le = boost::intrusive::get_parent_from_member(&ent, &local_fq_entry::ent);
le->submit();
delete le;
});
return make_ready_future<>();
});
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_local)
{
return test(true);
}
PERF_TEST_F(perf_fair_queue, contended_shared)
{
return test(false);
}
<commit_msg>register one default priority class for queue<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2020 ScyllaDB Ltd.
*/
#include <seastar/testing/perf_tests.hh>
#include <seastar/core/sharded.hh>
#include <seastar/core/thread.hh>
#include <seastar/core/fair_queue.hh>
#include <seastar/core/semaphore.hh>
#include <seastar/core/loop.hh>
#include <seastar/core/when_all.hh>
#include <boost/range/irange.hpp>
static constexpr fair_queue::class_id cid = 0;
struct local_fq_and_class {
seastar::fair_group fg;
seastar::fair_queue fq;
seastar::fair_queue sfq;
unsigned executed = 0;
static fair_group::config fg_config() {
fair_group::config cfg;
cfg.weight_rate = std::numeric_limits<int>::max();
cfg.size_rate = std::numeric_limits<int>::max();
return cfg;
}
seastar::fair_queue& queue(bool local) noexcept { return local ? fq : sfq; }
local_fq_and_class(seastar::fair_group& sfg)
: fg(fg_config())
, fq(fg, seastar::fair_queue::config())
, sfq(sfg, seastar::fair_queue::config())
{
fq.register_priority_class(cid, 1);
sfq.register_priority_class(cid, 1);
}
~local_fq_and_class() {
fq.unregister_priority_class(cid);
sfq.unregister_priority_class(cid);
}
};
struct local_fq_entry {
seastar::fair_queue_entry ent;
std::function<void()> submit;
template <typename Func>
local_fq_entry(unsigned weight, unsigned index, Func&& f)
: ent(seastar::fair_queue_ticket(weight, index))
, submit(std::move(f)) {}
};
struct perf_fair_queue {
static constexpr unsigned requests_to_dispatch = 1000;
seastar::sharded<local_fq_and_class> local_fq;
seastar::fair_group shared_fg;
static fair_group::config fg_config() {
fair_group::config cfg;
cfg.weight_rate = std::numeric_limits<int>::max();
cfg.size_rate = std::numeric_limits<int>::max();
return cfg;
}
perf_fair_queue()
: shared_fg(fg_config())
{
local_fq.start(std::ref(shared_fg)).get();
}
~perf_fair_queue() {
local_fq.stop().get();
}
future<> test(bool local);
};
future<> perf_fair_queue::test(bool loc) {
auto invokers = local_fq.invoke_on_all([loc] (local_fq_and_class& local) {
return parallel_for_each(boost::irange(0u, requests_to_dispatch), [&local, loc] (unsigned dummy) {
auto req = std::make_unique<local_fq_entry>(1, 1, [&local, loc] {
local.executed++;
local.queue(loc).notify_request_finished(seastar::fair_queue_ticket{1, 1});
});
local.queue(loc).queue(cid, req->ent);
req.release();
return make_ready_future<>();
});
});
auto collectors = local_fq.invoke_on_all([loc] (local_fq_and_class& local) {
// Zeroing this counter must be here, otherwise should the collectors win the
// execution order in when_all_succeed(), the do_until()'s stopping callback
// would return true immediately and the queue would not be dispatched.
//
// At the same time, although this counter is incremented by the lambda from
// invokers, it's not called until the fq.dispatch_requests() is, so there's no
// opposite problem if zeroing it here.
local.executed = 0;
return do_until([&local] { return local.executed == requests_to_dispatch; }, [&local, loc] {
local.queue(loc).dispatch_requests([] (fair_queue_entry& ent) {
local_fq_entry* le = boost::intrusive::get_parent_from_member(&ent, &local_fq_entry::ent);
le->submit();
delete le;
});
return make_ready_future<>();
});
});
return when_all_succeed(std::move(invokers), std::move(collectors)).discard_result();
}
PERF_TEST_F(perf_fair_queue, contended_local)
{
return test(true);
}
PERF_TEST_F(perf_fair_queue, contended_shared)
{
return test(false);
}
<|endoftext|> |
<commit_before>/*! @file convolute.cc
* @brief Tests for src/primitives/convolute.cc.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include "src/primitives/convolute.h"
#include "src/primitives/memory.h"
#include "src/primitives/arithmetic-inl.h"
void convolute_reference(const float *__restrict x, size_t xLength,
const float *__restrict h, size_t hLength,
float *__restrict result) {
for (int n = 0; n < static_cast<int>(xLength); n++) {
float sum = .0f;
for (int m = 0; m < static_cast<int>(hLength) && m <= n; m++) {
sum += h[m] * x[n - m];
}
result[n] = sum;
}
}
void DebugPrintConvolution(const char* name, const float* vec) {
printf("%s\t", name);
for (int i = 0; i < 10; i++) {
printf("%f ", vec[i]);
}
printf("\n");
}
TEST(convolute, convolute) {
float x[1024];
for (int i = 0; i < static_cast<int>(sizeof(x) / sizeof(x[0])); i++) {
x[i] = 1.0f;
}
float h[50];
for (int i = 0; i < static_cast<int>(sizeof(h) / sizeof(h[0])); i++) {
h[i] = i / (sizeof(h) / sizeof(h[0]) - 1.0f);
}
float verif[sizeof(x) / sizeof(x[0])];
convolute_reference(x, sizeof(x) / sizeof(x[0]),
h, sizeof(h) / sizeof(h[0]), verif);
DebugPrintConvolution("BRUTE-FORCE", verif);
float res[sizeof(x) / sizeof(x[0])];
convolute(x, sizeof(x) / sizeof(x[0]), h, sizeof(h) / sizeof(h[0]), res);
DebugPrintConvolution("OVERLAP-SAVE", res);
int firstDifferenceIndex = -1;
for (int i = 0; i < static_cast<int>(sizeof(x) / sizeof(x[0])); i++) {
float delta = res[i] - verif[i];
if (delta * delta > 1E-10 && firstDifferenceIndex == -1) {
firstDifferenceIndex = i;
}
}
ASSERT_EQ(-1, firstDifferenceIndex);
}
#include "tests/google/src/gtest_main.cc"
<commit_msg>More friendly test code<commit_after>/*! @file convolute.cc
* @brief Tests for src/primitives/convolute.cc.
* @author Markovtsev Vadim <[email protected]>
* @version 1.0
*
* @section Notes
* This code partially conforms to <a href="http://google-styleguide.googlecode.com/svn/trunk/cppguide.xml">Google C++ Style Guide</a>.
*
* @section Copyright
* Copyright 2013 Samsung R&D Institute Russia
*/
#include <gtest/gtest.h>
#include "src/primitives/convolute.h"
#include "src/primitives/memory.h"
#include "src/primitives/arithmetic-inl.h"
void convolute_reference(const float *__restrict x, size_t xLength,
const float *__restrict h, size_t hLength,
float *__restrict result) {
for (int n = 0; n < static_cast<int>(xLength); n++) {
float sum = .0f;
for (int m = 0; m < static_cast<int>(hLength) && m <= n; m++) {
sum += h[m] * x[n - m];
}
result[n] = sum;
}
}
void DebugPrintConvolution(const char* name, const float* vec) {
printf("%s\t", name);
for (int i = 0; i < 10; i++) {
printf("%f ", vec[i]);
}
printf("\n");
}
TEST(convolute, convolute) {
const int xlen = 1024;
const int hlen = 50;
float x[xlen];
for (int i = 0; i < xlen; i++) {
x[i] = 1.0f;
}
float h[hlen];
for (int i = 0; i < hlen; i++) {
h[i] = i / (sizeof(h) / sizeof(h[0]) - 1.0f);
}
float verif[xlen];
convolute_reference(x, xlen, h, hlen, verif);
DebugPrintConvolution("BRUTE-FORCE", verif);
float res[xlen];
convolute(x, xlen, h, hlen, res);
DebugPrintConvolution("OVERLAP-SAVE", res);
int firstDifferenceIndex = -1;
for (int i = 0; i < xlen; i++) {
float delta = res[i] - verif[i];
if (delta * delta > 1E-10 && firstDifferenceIndex == -1) {
firstDifferenceIndex = i;
}
}
ASSERT_EQ(-1, firstDifferenceIndex);
}
#include "tests/google/src/gtest_main.cc"
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2003-2011 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// file DboxTray.cpp
//
// Tray-related methods of DboxMain
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "DboxMain.h"
#include "RUEList.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include <errno.h>
#include "resource.h"
#include "resource2.h" // Menu, Toolbar & Accelerator resources
#include "resource3.h" // String resources
#endif
#include "core/pwsprefs.h"
#include "core/pwscore.h"
#include "core/PWSAuxParse.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////// New System Tray Commands /////////////////////
#ifndef POCKET_PC
void DboxMain::OnTrayLockUnLock()
{
switch(app.GetSystemTrayState()) {
case ThisMfcApp::LOCKED: // User clicked UnLock!
// This only unlocks the database - it does not restore the window
pws_os::Trace(L"OnTrayLockUnLock: User clicked Unlock\n");
RestoreWindowsData(false, false);
TellUserAboutExpiredPasswords();
break;
case ThisMfcApp::UNLOCKED: // User clicked Lock!
UpdateSystemTray(LOCKED);
ClearClipboardData();
if (!IsIconic())
m_vGroupDisplayState = GetGroupDisplayState();
if (LockDataBase()) { // save db if needed, clear data
ShowWindow(SW_HIDE);
}
break;
case ThisMfcApp::CLOSED:
break;
default:
ASSERT(0);
break;
}
}
void DboxMain::OnTrayClearRecentEntries()
{
m_RUEList.ClearEntries();
}
void DboxMain::OnTrayCopyUsername(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYUSERNAME1) &&
(nID <= ID_MENUITEM_TRAYCOPYUSERNAMEMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYUSERNAME1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
const StringX cs_username = ci.GetUser();
SetClipboardData(cs_username);
UpdateLastClipboardAction(CItemData::USER);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyUsername(CCmdUI *)
{
}
void DboxMain::OnTrayCopyPassword(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYPASSWORD1) && (nID <= ID_MENUITEM_TRAYCOPYPASSWORDMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYPASSWORD1, ci))
return;
if (ci.IsDependent()) {
ci = *GetBaseEntry(&ci);
}
const StringX cs_password = ci.GetPassword();
SetClipboardData(cs_password);
UpdateLastClipboardAction(CItemData::PASSWORD);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyPassword(CCmdUI *)
{
}
void DboxMain::OnTrayCopyNotes(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYNOTES1) && (nID <= ID_MENUITEM_TRAYCOPYNOTESMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYNOTES1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
SetClipboardData(ci.GetNotes());
UpdateLastClipboardAction(CItemData::NOTES);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyNotes(CCmdUI *)
{
}
void DboxMain::OnTrayBrowse(UINT nID)
{
ASSERT(((nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX)) ||
((nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX)));
CItemData ci;
const bool bDoAutotype = (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) &&
(nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX);
if (!bDoAutotype) {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSE1, ci))
return;
} else {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSEPLUS1, ci))
return;
}
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
if (!ci.IsURLEmpty()) {
std::vector<size_t> vactionverboffsets;
StringX sxAutotype = PWSAuxParse::GetAutoTypeString(ci.GetAutoType(),
ci.GetGroup(), ci.GetTitle(),
ci.GetUser(), ci.GetPassword(),
ci.GetNotes(),
vactionverboffsets);
LaunchBrowser(ci.GetURL().c_str(), sxAutotype, vactionverboffsets, bDoAutotype);
if (PWSprefs::GetInstance()->GetPref(PWSprefs::CopyPasswordWhenBrowseToURL)) {
SetClipboardData(ci.GetPassword());
UpdateLastClipboardAction(CItemData::PASSWORD);
} else
UpdateLastClipboardAction(CItemData::URL);
}
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayBrowse(CCmdUI *pCmdUI)
{
int nID = pCmdUI->m_nID;
ASSERT(((nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX)) ||
((nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX)));
CItemData ci;
const bool bDoAutotype = (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) &&
(nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX);
if (!bDoAutotype) {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSE1, ci))
return;
} else {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSEPLUS1, ci))
return;
}
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
// Has it an embedded URL
if (ci.IsURLEmpty()) {
pCmdUI->Enable(FALSE);
} else {
const bool bIsEmail = ci.IsURLEmail();
MapMenuShortcutsIter iter;
if (!bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_BROWSEURL);
else if (!bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_BROWSEURLPLUS);
else if (bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_SENDEMAIL);
ASSERT(iter != m_MapMenuShortcuts.end());
CString cs_text = iter->second.name.c_str();
int nPos = cs_text.Find(L"\t");
if (nPos > 0)
cs_text = cs_text.Left(nPos);
pCmdUI->SetText(cs_text);
}
}
void DboxMain::OnTrayCopyEmail(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYEMAIL1) &&
(nID <= ID_MENUITEM_TRAYCOPYEMAILMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYEMAIL1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
const StringX cs_email = ci.GetEmail();
SetClipboardData(cs_email);
UpdateLastClipboardAction(CItemData::EMAIL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyEmail(CCmdUI *)
{
}
void DboxMain::OnTraySendEmail(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYSENDEMAIL1) && (nID <= ID_MENUITEM_TRAYSENDEMAILMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYSENDEMAIL1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
CString cs_command;
if (!ci.IsEmailEmpty()) {
cs_command = L"mailto:";
cs_command += ci.GetEmail().c_str();
} else {
cs_command = ci.GetURL().c_str();
}
if (!cs_command.IsEmpty()) {
std::vector<size_t> vactionverboffsets;
LaunchBrowser(cs_command, L"", vactionverboffsets, false);
UpdateAccessTime(&ci);
}
}
void DboxMain::OnUpdateTraySendEmail(CCmdUI *)
{
}
void DboxMain::OnTraySelect(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYSELECT1) && (nID <= ID_MENUITEM_TRAYSELECTMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYSELECT1, ci))
return;
DisplayInfo *pdi = (DisplayInfo *)ci.GetDisplayInfo();
if (pdi != NULL) { // could be null if RefreshViews not called,
// in which case we've no display to select to.
// An alternate solution would be to force the main window
// to display, along with a call to RefreshViews(), before
// calling GetDisplayInfo().
SelectEntry(pdi->list_index,TRUE);
}
}
void DboxMain::OnUpdateTraySelect(CCmdUI *)
{
}
void DboxMain::OnTrayDeleteEntry(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYDELETE1) && (nID <= ID_MENUITEM_TRAYDELETEMAX));
m_RUEList.DeleteRUEntry(nID - ID_MENUITEM_TRAYDELETE1);
}
void DboxMain::OnUpdateTrayDeleteEntry(CCmdUI *)
{
}
void DboxMain::OnTrayAutoType(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYAUTOTYPE1) && (nID <= ID_MENUITEM_TRAYAUTOTYPEMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYAUTOTYPE1, ci))
return;
m_bInAT = true;
AutoType(ci);
UpdateAccessTime(&ci);
m_bInAT = false;
}
void DboxMain::OnUpdateTrayAutoType(CCmdUI *)
{
}
void DboxMain::OnTrayCopyURL(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYURL1) && (nID <= ID_MENUITEM_TRAYCOPYURLMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYURL1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
StringX cs_URL = ci.GetURL();
StringX::size_type ipos;
ipos = cs_URL.find(L"[alt]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"[ssh]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"{alt}");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
SetClipboardData(cs_URL);
UpdateLastClipboardAction(CItemData::URL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyURL(CCmdUI *)
{
}
void DboxMain::OnTrayRunCommand(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYRUNCMD1) && (nID <= ID_MENUITEM_TRAYRUNCMDMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYRUNCMD1, ci))
return;
if (ci.IsShortcut()) {
ci = *GetBaseEntry(&ci);
}
StringX cs_URL = ci.GetURL();
StringX::size_type ipos;
ipos = cs_URL.find(L"[alt]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"[ssh]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"{alt}");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
SetClipboardData(cs_URL);
UpdateLastClipboardAction(CItemData::URL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayRunCommand(CCmdUI *)
{
}
#endif /* POCKET_PC */
<commit_msg>Add some bulletproofing to GetBaseEntry calls in systray actions<commit_after>/*
* Copyright (c) 2003-2011 Rony Shapiro <[email protected]>.
* All rights reserved. Use of the code is allowed under the
* Artistic License 2.0 terms, as specified in the LICENSE file
* distributed with this code, or available from
* http://www.opensource.org/licenses/artistic-license-2.0.php
*/
/// file DboxTray.cpp
//
// Tray-related methods of DboxMain
//-----------------------------------------------------------------------------
#include "PasswordSafe.h"
#include "ThisMfcApp.h"
#include "DboxMain.h"
#include "RUEList.h"
#if defined(POCKET_PC)
#include "pocketpc/resource.h"
#else
#include <errno.h>
#include "resource.h"
#include "resource2.h" // Menu, Toolbar & Accelerator resources
#include "resource3.h" // String resources
#endif
#include "core/pwsprefs.h"
#include "core/pwscore.h"
#include "core/PWSAuxParse.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
static bool SafeGetBaseEntry(const DboxMain *dbm, const CItemData &dep, CItemData &base)
{
// Asserts in debug build if GetBase(dep) fails
// returns false in release build
const CItemData *pBase = dbm->GetBaseEntry(&dep);
ASSERT(pBase != NULL);
if (pBase != NULL) {
base = *pBase;
return true;
} else
return false;
}
/////////////////////////////// New System Tray Commands /////////////////////
#ifndef POCKET_PC
void DboxMain::OnTrayLockUnLock()
{
switch(app.GetSystemTrayState()) {
case ThisMfcApp::LOCKED: // User clicked UnLock!
// This only unlocks the database - it does not restore the window
pws_os::Trace(L"OnTrayLockUnLock: User clicked Unlock\n");
RestoreWindowsData(false, false);
TellUserAboutExpiredPasswords();
break;
case ThisMfcApp::UNLOCKED: // User clicked Lock!
UpdateSystemTray(LOCKED);
ClearClipboardData();
if (!IsIconic())
m_vGroupDisplayState = GetGroupDisplayState();
if (LockDataBase()) { // save db if needed, clear data
ShowWindow(SW_HIDE);
}
break;
case ThisMfcApp::CLOSED:
break;
default:
ASSERT(0);
break;
}
}
void DboxMain::OnTrayClearRecentEntries()
{
m_RUEList.ClearEntries();
}
void DboxMain::OnTrayCopyUsername(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYUSERNAME1) &&
(nID <= ID_MENUITEM_TRAYCOPYUSERNAMEMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYUSERNAME1, ci))
return;
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
const StringX cs_username = ci.GetUser();
SetClipboardData(cs_username);
UpdateLastClipboardAction(CItemData::USER);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyUsername(CCmdUI *)
{
}
void DboxMain::OnTrayCopyPassword(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYPASSWORD1) && (nID <= ID_MENUITEM_TRAYCOPYPASSWORDMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYPASSWORD1, ci))
return;
if (ci.IsDependent()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
const StringX cs_password = ci.GetPassword();
SetClipboardData(cs_password);
UpdateLastClipboardAction(CItemData::PASSWORD);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyPassword(CCmdUI *)
{
}
void DboxMain::OnTrayCopyNotes(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYNOTES1) && (nID <= ID_MENUITEM_TRAYCOPYNOTESMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYNOTES1, ci))
return;
if (ci.IsShortcut())
if (!SafeGetBaseEntry(this, ci, ci))
return;
SetClipboardData(ci.GetNotes());
UpdateLastClipboardAction(CItemData::NOTES);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyNotes(CCmdUI *)
{
}
void DboxMain::OnTrayBrowse(UINT nID)
{
ASSERT(((nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX)) ||
((nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX)));
CItemData ci;
const bool bDoAutotype = (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) &&
(nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX);
if (!bDoAutotype) {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSE1, ci))
return;
} else {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSEPLUS1, ci))
return;
}
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return;
}
if (!ci.IsURLEmpty()) {
std::vector<size_t> vactionverboffsets;
StringX sxAutotype = PWSAuxParse::GetAutoTypeString(ci.GetAutoType(),
ci.GetGroup(), ci.GetTitle(),
ci.GetUser(), ci.GetPassword(),
ci.GetNotes(),
vactionverboffsets);
LaunchBrowser(ci.GetURL().c_str(), sxAutotype, vactionverboffsets, bDoAutotype);
if (PWSprefs::GetInstance()->GetPref(PWSprefs::CopyPasswordWhenBrowseToURL)) {
SetClipboardData(ci.GetPassword());
UpdateLastClipboardAction(CItemData::PASSWORD);
} else
UpdateLastClipboardAction(CItemData::URL);
}
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayBrowse(CCmdUI *pCmdUI)
{
int nID = pCmdUI->m_nID;
ASSERT(((nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX)) ||
((nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX)));
CItemData ci;
const bool bDoAutotype = (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) &&
(nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX);
if (!bDoAutotype) {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSE1, ci))
return;
} else {
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYBROWSEPLUS1, ci))
return;
}
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return;
}
// Has it an embedded URL
if (ci.IsURLEmpty()) {
pCmdUI->Enable(FALSE);
} else {
const bool bIsEmail = ci.IsURLEmail();
MapMenuShortcutsIter iter;
if (!bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_BROWSEURL);
else if (!bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSEPLUS1) && (nID <= ID_MENUITEM_TRAYBROWSEPLUSMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_BROWSEURLPLUS);
else if (bIsEmail && (nID >= ID_MENUITEM_TRAYBROWSE1) && (nID <= ID_MENUITEM_TRAYBROWSEMAX))
iter = m_MapMenuShortcuts.find(ID_MENUITEM_SENDEMAIL);
ASSERT(iter != m_MapMenuShortcuts.end());
CString cs_text = iter->second.name.c_str();
int nPos = cs_text.Find(L"\t");
if (nPos > 0)
cs_text = cs_text.Left(nPos);
pCmdUI->SetText(cs_text);
}
}
void DboxMain::OnTrayCopyEmail(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYEMAIL1) &&
(nID <= ID_MENUITEM_TRAYCOPYEMAILMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYEMAIL1, ci))
return;
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
const StringX cs_email = ci.GetEmail();
SetClipboardData(cs_email);
UpdateLastClipboardAction(CItemData::EMAIL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyEmail(CCmdUI *)
{
}
void DboxMain::OnTraySendEmail(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYSENDEMAIL1) && (nID <= ID_MENUITEM_TRAYSENDEMAILMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYSENDEMAIL1, ci))
return;
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
CString cs_command;
if (!ci.IsEmailEmpty()) {
cs_command = L"mailto:";
cs_command += ci.GetEmail().c_str();
} else {
cs_command = ci.GetURL().c_str();
}
if (!cs_command.IsEmpty()) {
std::vector<size_t> vactionverboffsets;
LaunchBrowser(cs_command, L"", vactionverboffsets, false);
UpdateAccessTime(&ci);
}
}
void DboxMain::OnUpdateTraySendEmail(CCmdUI *)
{
}
void DboxMain::OnTraySelect(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYSELECT1) && (nID <= ID_MENUITEM_TRAYSELECTMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYSELECT1, ci))
return;
DisplayInfo *pdi = (DisplayInfo *)ci.GetDisplayInfo();
if (pdi != NULL) { // could be null if RefreshViews not called,
// in which case we've no display to select to.
// An alternate solution would be to force the main window
// to display, along with a call to RefreshViews(), before
// calling GetDisplayInfo().
SelectEntry(pdi->list_index,TRUE);
}
}
void DboxMain::OnUpdateTraySelect(CCmdUI *)
{
}
void DboxMain::OnTrayDeleteEntry(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYDELETE1) && (nID <= ID_MENUITEM_TRAYDELETEMAX));
m_RUEList.DeleteRUEntry(nID - ID_MENUITEM_TRAYDELETE1);
}
void DboxMain::OnUpdateTrayDeleteEntry(CCmdUI *)
{
}
void DboxMain::OnTrayAutoType(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYAUTOTYPE1) && (nID <= ID_MENUITEM_TRAYAUTOTYPEMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYAUTOTYPE1, ci))
return;
m_bInAT = true;
AutoType(ci);
UpdateAccessTime(&ci);
m_bInAT = false;
}
void DboxMain::OnUpdateTrayAutoType(CCmdUI *)
{
}
void DboxMain::OnTrayCopyURL(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYCOPYURL1) && (nID <= ID_MENUITEM_TRAYCOPYURLMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYCOPYURL1, ci))
return;
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
StringX cs_URL = ci.GetURL();
StringX::size_type ipos;
ipos = cs_URL.find(L"[alt]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"[ssh]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"{alt}");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
SetClipboardData(cs_URL);
UpdateLastClipboardAction(CItemData::URL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayCopyURL(CCmdUI *)
{
}
void DboxMain::OnTrayRunCommand(UINT nID)
{
ASSERT((nID >= ID_MENUITEM_TRAYRUNCMD1) && (nID <= ID_MENUITEM_TRAYRUNCMDMAX));
CItemData ci;
if (!m_RUEList.GetPWEntry(nID - ID_MENUITEM_TRAYRUNCMD1, ci))
return;
if (ci.IsShortcut()) {
if (!SafeGetBaseEntry(this, ci, ci))
return; // fail safely in release
}
StringX cs_URL = ci.GetURL();
StringX::size_type ipos;
ipos = cs_URL.find(L"[alt]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"[ssh]");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
ipos = cs_URL.find(L"{alt}");
if (ipos != StringX::npos)
cs_URL.replace(ipos, 5, L"");
SetClipboardData(cs_URL);
UpdateLastClipboardAction(CItemData::URL);
UpdateAccessTime(&ci);
}
void DboxMain::OnUpdateTrayRunCommand(CCmdUI *)
{
}
#endif /* POCKET_PC */
<|endoftext|> |
<commit_before><commit_msg>Added a comment to the usage function.<commit_after><|endoftext|> |
<commit_before>/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#define __STDC_LIMIT_MACROS
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#include <xen/xen.h>
#include <xen/features.h>
#include <llamaos/api/sleep.h>
#include <llamaos/memory/Memory.h>
#include <llamaos/xen/Export-glibc.h>
#include <llamaos/xen/Hypervisor.h>
#include <bits/stringfwd.h>
#include <llamaos/llamaOS.h>
#include <llamaos/Trace.h>
using namespace std;
using namespace llamaos;
using namespace llamaos::xen;
static inline uint64_t rdtsc ()
{
uint32_t lo, hi;
asm volatile ("rdtsc" : "=a" (lo), "=d" (hi));
return (static_cast<uint64_t>(hi) << 32) | lo;
}
static inline uint64_t tsc_to_ns (const vcpu_time_info_t *time_info, uint64_t tsc)
{
const uint64_t overflow = UINT64_MAX / time_info->tsc_to_system_mul;
uint64_t time_ns = 0UL;
uint64_t stsc = (time_info->tsc_shift < 0)
? (tsc >> -time_info->tsc_shift) : (tsc << time_info->tsc_shift);
// mul will overflow 64 bits
while (stsc > overflow)
{
time_ns += ((overflow * time_info->tsc_to_system_mul) >> 32);
stsc -= overflow;
}
time_ns += (stsc * time_info->tsc_to_system_mul) >> 32;
return time_ns;
}
static void glibc_abort (void)
{
cout << "!!! ALERT: glibc calling abort()." << endl;
cout.flush();
fflush(stdout);
for(;;);
}
static int glibc_gethostname (char *name, size_t len)
{
stringstream ss;
ss << Hypervisor::get_instance ()->name << "." << Hypervisor::get_instance ()->domid;
if ((ss.str().size() + 1) > len)
{
errno = ENAMETOOLONG;
return -1;
}
memcpy(name, ss.str().c_str(), len < ss.str().size() + 1);
return 0;
}
static int glibc_getpid ()
{
return Hypervisor::get_instance ()->domid;
}
static int glibc_gettimeofday (struct timeval *tv, struct timezone * /* tz */)
{
uint32_t wc_version = 0;
uint32_t wc_sec = 0;
uint32_t wc_nsec = 0;
uint32_t version = 0;
uint64_t tsc_timestamp = 0;
uint64_t system_time = 0;
shared_info_t *shared_info = Hypervisor::get_instance ()->shared_info;
vcpu_time_info_t *time_info = &shared_info->vcpu_info [0].time;
for (;;)
{
wc_version = shared_info->wc_version;
version = time_info->version;
mb();
if ( !(wc_version & 1)
&& !(version & 1))
{
wc_sec = shared_info->wc_sec;
wc_nsec = shared_info->wc_nsec;
tsc_timestamp = time_info->tsc_timestamp;
system_time = time_info->system_time;
mb();
if ( (wc_version == shared_info->wc_version)
&& (version == time_info->version))
{
break;
}
}
}
uint64_t tsc = rdtsc () - tsc_timestamp;
uint64_t nsec = tsc_to_ns (time_info, tsc);
nsec += system_time;
wc_sec += (nsec / 1000000000UL);
wc_nsec += (nsec % 1000000000UL);
if (wc_nsec > 1000000000UL)
{
wc_sec += 1;
wc_nsec -= 1000000000UL;
}
tv->tv_sec = wc_sec;
tv->tv_usec = wc_nsec / 1000;
return 0;
}
static unsigned int glibc_libc_sleep (unsigned int seconds)
{
api::sleep (seconds);
return 0;
}
static stringstream np_out;
static int glibc_libc_open (const char *file, int oflag)
{
if (strcmp (file, "fort.6") == 0)
{
return 6;
}
else if (strcmp (file, "np.out") == 0)
{
return 10;
}
else
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (strcmp (file, hypervisor->blocks [i]->get_name ().c_str ()) == 0)
{
return 100 + i;
}
}
}
// trace("!!! ALERT: glibc calling libc_open() before file system support is enabled.\n");
trace (" opening file %s, %x\n", file, oflag);
errno = ENOENT;
return -1;
}
static int glibc_close (int fd)
{
trace("!!! ALERT: glibc calling close() on %d.\n", fd);
if (fd == 10)
{
cout << "np.out:" << endl;
cout << np_out.str() << endl;
}
else
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
// special close?
break;
}
}
}
return 0;
}
static ssize_t glibc_read (int fd, void *buf, size_t nbytes)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
return hypervisor->blocks [i]->read (buf, nbytes);
}
}
return -1;
}
static ssize_t glibc_write (int fd, const void *buf, size_t nbytes)
{
if ( (stdout->_fileno != fd)
&& (stderr->_fileno != fd)
&& (6 != fd) // fortran uses 6 for alt std output
&& (10 != fd)) // fortran uses 6 for alt std output
{
cout << "Alert: writing to fileno " << fd << endl;
}
if (fd == 10)
{
for (size_t i = 0; i < nbytes; i++)
{
np_out << static_cast<const char *>(buf) [i];
}
}
else
{
Hypervisor::get_instance ()->console.write (static_cast<const char *>(buf), nbytes);
}
return nbytes;
}
static off_t glibc_lseek (int fd, off_t offset, int whence)
{
if (fd == 6)
{
return offset;
}
cout << "lseek " << fd << endl;
trace("!!! ALERT: glibc calling lseek() before file system support is enabled.\n");
trace (" fd: %d, offset: %d, whence: %d\n", fd, offset, whence);
return -1;
}
static off64_t glibc_lseek64 (int fd, off64_t offset, int whence)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
return hypervisor->blocks [i]->lseek64 (offset, whence);
}
}
cout << "lseek64 " << fd << endl;
trace("!!! ALERT: glibc calling lseek64() before file system support is enabled.\n");
return -1;
}
static void register_glibc_exports (void)
{
register_llamaos_abort (glibc_abort);
register_llamaos_gethostname (glibc_gethostname);
register_llamaos_getpid (glibc_getpid);
register_llamaos_gettimeofday (glibc_gettimeofday);
register_llamaos_sleep (glibc_libc_sleep);
register_llamaos_close (glibc_close);
register_llamaos_libc_open (glibc_libc_open);
register_llamaos_read (glibc_read);
register_llamaos_write (glibc_write);
register_llamaos_lseek (glibc_lseek);
register_llamaos_lseek64 (glibc_lseek64);
}
static vector<string> split (const string &input)
{
vector<string> tokens;
string::const_iterator first = input.begin ();
string::const_iterator mark = input.begin ();
string::const_iterator last = input.end ();
while (first != last)
{
if (isspace (*first))
{
string token = string (mark, first);
if (token.length () > 0)
{
tokens.push_back (token);
}
mark = first + 1;
}
first++;
}
string token = string (mark, first);
if (token.length () > 0)
{
tokens.push_back (token);
}
return tokens;
}
extern "C"
int main (int argc, char *argv []);
extern "C"
int __main (int argc, char *argv [], char * /* env[] */)
{
return main (argc, argv);
}
void entry_llamaOS (start_info_t *start_info)
{
// try
{
// create the one and only hypervisor object
trace ("Creating Hypervisor...\n");
Hypervisor *hypervisor = new Hypervisor (start_info);
register_glibc_exports ();
hypervisor->initialize ();
// read and create args
string cmd_line (reinterpret_cast<char *>(start_info->cmd_line));
vector<string> args = split (cmd_line);
trace ("args size is %d\n", args.size ());
for (unsigned int i = 0; i < args.size (); i++)
{
trace ("argv [%d] = %s\n", i, args [i].c_str ());
}
hypervisor->argc = static_cast<int>(args.size () + 1);
hypervisor->argv [0] = const_cast<char *>(hypervisor->name.c_str ());
for (unsigned int i = 0; i < args.size (); i++)
{
hypervisor->argv [i+1] = const_cast<char *>(args [i].c_str ());
}
trace ("Before application main()...\n");
main (hypervisor->argc, hypervisor->argv);
// get rid of all leftover console buffer
cout.flush ();
fflush (stdout);
trace ("After application main()...\n");
api::sleep(1);
delete hypervisor;
}
// catch (const std::runtime_error &e)
// {
// trace ("*** runtime_error: %s ***\n", e.what ());
// }
// catch (...)
// {
// trace ("*** unknown exception ***\n");
// }
}
<commit_msg>directing hpcc output to console just as netpipe<commit_after>/*
Copyright (c) 2012, William Magato
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) 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.
The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the copyright holder(s) or contributors.
*/
#define __STDC_LIMIT_MACROS
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
#include <xen/xen.h>
#include <xen/features.h>
#include <llamaos/api/sleep.h>
#include <llamaos/memory/Memory.h>
#include <llamaos/xen/Export-glibc.h>
#include <llamaos/xen/Hypervisor.h>
#include <bits/stringfwd.h>
#include <llamaos/llamaOS.h>
#include <llamaos/Trace.h>
using namespace std;
using namespace llamaos;
using namespace llamaos::xen;
static inline uint64_t rdtsc ()
{
uint32_t lo, hi;
asm volatile ("rdtsc" : "=a" (lo), "=d" (hi));
return (static_cast<uint64_t>(hi) << 32) | lo;
}
static inline uint64_t tsc_to_ns (const vcpu_time_info_t *time_info, uint64_t tsc)
{
const uint64_t overflow = UINT64_MAX / time_info->tsc_to_system_mul;
uint64_t time_ns = 0UL;
uint64_t stsc = (time_info->tsc_shift < 0)
? (tsc >> -time_info->tsc_shift) : (tsc << time_info->tsc_shift);
// mul will overflow 64 bits
while (stsc > overflow)
{
time_ns += ((overflow * time_info->tsc_to_system_mul) >> 32);
stsc -= overflow;
}
time_ns += (stsc * time_info->tsc_to_system_mul) >> 32;
return time_ns;
}
static void glibc_abort (void)
{
cout << "!!! ALERT: glibc calling abort()." << endl;
cout.flush();
fflush(stdout);
for(;;);
}
static int glibc_gethostname (char *name, size_t len)
{
stringstream ss;
ss << Hypervisor::get_instance ()->name << "." << Hypervisor::get_instance ()->domid;
if ((ss.str().size() + 1) > len)
{
errno = ENAMETOOLONG;
return -1;
}
memcpy(name, ss.str().c_str(), len < ss.str().size() + 1);
return 0;
}
static int glibc_getpid ()
{
return Hypervisor::get_instance ()->domid;
}
static int glibc_gettimeofday (struct timeval *tv, struct timezone * /* tz */)
{
uint32_t wc_version = 0;
uint32_t wc_sec = 0;
uint32_t wc_nsec = 0;
uint32_t version = 0;
uint64_t tsc_timestamp = 0;
uint64_t system_time = 0;
shared_info_t *shared_info = Hypervisor::get_instance ()->shared_info;
vcpu_time_info_t *time_info = &shared_info->vcpu_info [0].time;
for (;;)
{
wc_version = shared_info->wc_version;
version = time_info->version;
mb();
if ( !(wc_version & 1)
&& !(version & 1))
{
wc_sec = shared_info->wc_sec;
wc_nsec = shared_info->wc_nsec;
tsc_timestamp = time_info->tsc_timestamp;
system_time = time_info->system_time;
mb();
if ( (wc_version == shared_info->wc_version)
&& (version == time_info->version))
{
break;
}
}
}
uint64_t tsc = rdtsc () - tsc_timestamp;
uint64_t nsec = tsc_to_ns (time_info, tsc);
nsec += system_time;
wc_sec += (nsec / 1000000000UL);
wc_nsec += (nsec % 1000000000UL);
if (wc_nsec > 1000000000UL)
{
wc_sec += 1;
wc_nsec -= 1000000000UL;
}
tv->tv_sec = wc_sec;
tv->tv_usec = wc_nsec / 1000;
return 0;
}
static unsigned int glibc_libc_sleep (unsigned int seconds)
{
api::sleep (seconds);
return 0;
}
static stringstream np_out;
static int glibc_libc_open (const char *file, int oflag)
{
if (strcmp (file, "fort.6") == 0)
{
return 6;
}
else if ( (strcmp (file, "np.out") == 0)
|| (strcmp (file, "hpccoutf.txt") == 0))
{
return 10;
}
else
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (strcmp (file, hypervisor->blocks [i]->get_name ().c_str ()) == 0)
{
return 100 + i;
}
}
}
// trace("!!! ALERT: glibc calling libc_open() before file system support is enabled.\n");
trace (" opening file %s, %x\n", file, oflag);
errno = ENOENT;
return -1;
}
static int glibc_close (int fd)
{
trace("!!! ALERT: glibc calling close() on %d.\n", fd);
if (fd == 10)
{
cout << "np.out:" << endl;
cout << np_out.str() << endl;
}
else
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
// special close?
break;
}
}
}
return 0;
}
static ssize_t glibc_read (int fd, void *buf, size_t nbytes)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
return hypervisor->blocks [i]->read (buf, nbytes);
}
}
return -1;
}
static ssize_t glibc_write (int fd, const void *buf, size_t nbytes)
{
if ( (stdout->_fileno != fd)
&& (stderr->_fileno != fd)
&& (6 != fd) // fortran uses 6 for alt std output
&& (10 != fd)) // fortran uses 6 for alt std output
{
cout << "Alert: writing to fileno " << fd << endl;
}
if (fd == 10)
{
for (size_t i = 0; i < nbytes; i++)
{
np_out << static_cast<const char *>(buf) [i];
}
}
else
{
Hypervisor::get_instance ()->console.write (static_cast<const char *>(buf), nbytes);
}
return nbytes;
}
static off_t glibc_lseek (int fd, off_t offset, int whence)
{
if (fd == 6)
{
return offset;
}
cout << "lseek " << fd << endl;
trace("!!! ALERT: glibc calling lseek() before file system support is enabled.\n");
trace (" fd: %d, offset: %d, whence: %d\n", fd, offset, whence);
return -1;
}
static off64_t glibc_lseek64 (int fd, off64_t offset, int whence)
{
Hypervisor *hypervisor = Hypervisor::get_instance ();
for (size_t i = 0; i < hypervisor->blocks.size (); i++)
{
if (fd == static_cast<int>(100 + i))
{
return hypervisor->blocks [i]->lseek64 (offset, whence);
}
}
cout << "lseek64 " << fd << endl;
trace("!!! ALERT: glibc calling lseek64() before file system support is enabled.\n");
return -1;
}
static void register_glibc_exports (void)
{
register_llamaos_abort (glibc_abort);
register_llamaos_gethostname (glibc_gethostname);
register_llamaos_getpid (glibc_getpid);
register_llamaos_gettimeofday (glibc_gettimeofday);
register_llamaos_sleep (glibc_libc_sleep);
register_llamaos_close (glibc_close);
register_llamaos_libc_open (glibc_libc_open);
register_llamaos_read (glibc_read);
register_llamaos_write (glibc_write);
register_llamaos_lseek (glibc_lseek);
register_llamaos_lseek64 (glibc_lseek64);
}
static vector<string> split (const string &input)
{
vector<string> tokens;
string::const_iterator first = input.begin ();
string::const_iterator mark = input.begin ();
string::const_iterator last = input.end ();
while (first != last)
{
if (isspace (*first))
{
string token = string (mark, first);
if (token.length () > 0)
{
tokens.push_back (token);
}
mark = first + 1;
}
first++;
}
string token = string (mark, first);
if (token.length () > 0)
{
tokens.push_back (token);
}
return tokens;
}
extern "C"
int main (int argc, char *argv []);
extern "C"
int __main (int argc, char *argv [], char * /* env[] */)
{
return main (argc, argv);
}
void entry_llamaOS (start_info_t *start_info)
{
// try
{
// create the one and only hypervisor object
trace ("Creating Hypervisor...\n");
Hypervisor *hypervisor = new Hypervisor (start_info);
register_glibc_exports ();
hypervisor->initialize ();
// read and create args
string cmd_line (reinterpret_cast<char *>(start_info->cmd_line));
vector<string> args = split (cmd_line);
trace ("args size is %d\n", args.size ());
for (unsigned int i = 0; i < args.size (); i++)
{
trace ("argv [%d] = %s\n", i, args [i].c_str ());
}
hypervisor->argc = static_cast<int>(args.size () + 1);
hypervisor->argv [0] = const_cast<char *>(hypervisor->name.c_str ());
for (unsigned int i = 0; i < args.size (); i++)
{
hypervisor->argv [i+1] = const_cast<char *>(args [i].c_str ());
}
trace ("Before application main()...\n");
main (hypervisor->argc, hypervisor->argv);
// get rid of all leftover console buffer
cout.flush ();
fflush (stdout);
trace ("After application main()...\n");
api::sleep(1);
delete hypervisor;
}
// catch (const std::runtime_error &e)
// {
// trace ("*** runtime_error: %s ***\n", e.what ());
// }
// catch (...)
// {
// trace ("*** unknown exception ***\n");
// }
}
<|endoftext|> |
<commit_before>#pragma once
#include "physics/forkable.hpp"
namespace principia {
namespace physics {
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteFork(not_null<Tr4jectory**> const trajectory) {
CHECK_NOTNULL(*trajectory);
std::experimental::optional<Instant> const fork_time =
(*trajectory)->ForkTime();
CHECK(fork_time);
// Find the position of |*forkable| among our children and remove it.
auto const range = children_.equal_range(*fork_time);
for (auto it = range.first; it != range.second; ++it) {
if (&it->second == *trajectory) {
children_.erase(it);
*trajectory = nullptr;
return;
}
}
LOG(FATAL) << "argument is not a child of this trajectory";
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::is_root() const {
return parent_ == nullptr;
}
template<typename Tr4jectory>
not_null<Tr4jectory const*>
Forkable<Tr4jectory>::root() const {
not_null<Tr4jectory const*> ancestor = that();
while (ancestor->parent_ != nullptr) {
ancestor = ancestor->parent_;
}
return ancestor;
}
template<typename Tr4jectory>
not_null<Tr4jectory*>
Forkable<Tr4jectory>::root() {
not_null<Tr4jectory*> ancestor = that();
while (ancestor->parent_ != nullptr) {
ancestor = ancestor->parent_;
}
return ancestor;
}
template<typename Tr4jectory>
std::experimental::optional<Instant> Forkable<Tr4jectory>::ForkTime() const {
if (is_root()) {
return std::experimental::nullopt;
} else {
return (*position_in_parent_children_)->first;
}
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::Iterator::operator==(Iterator const& right) const {
return ancestry_ == right.ancestry_ && current_ == right.current_;
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::Iterator::operator!=(Iterator const& right) const {
return !(*this == right);
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator&
Forkable<Tr4jectory>::Iterator::operator++() {
CHECK(!ancestry_.empty());
CHECK(current_ != ancestry_.front()->timeline_end());
// Check if there is a next child in the ancestry.
auto ancestry_it = ancestry_.begin();
if (++ancestry_it != ancestry_.end()) {
// There is a next child. See if we reached its fork time.
Instant const& current_time = ForkableTraits<Tr4jectory>::time(current_);
not_null<Tr4jectory const*> child = *ancestry_it;
Instant child_fork_time = (*child->position_in_parent_children_)->first;
if (current_time == child_fork_time) {
// We have reached the fork time of the next child. There may be several
// forks at that time so we must skip them until we find a fork that is at
// a different time or the end of the children.
do {
current_ = child->timeline_begin(); // May be at end.
ancestry_.pop_front();
if (++ancestry_it == ancestry_.end()) {
break;
}
child = *ancestry_it;
child_fork_time = (*child->position_in_parent_children_)->first;
} while (current_time == child_fork_time);
CheckNormalizedIfEnd();
return *this;
}
}
// Business as usual, keep moving along the same timeline.
++current_;
CheckNormalizedIfEnd();
return *this;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator&
Forkable<Tr4jectory>::Iterator::operator--() {
CHECK(!ancestry_.empty());
not_null<Tr4jectory const*> ancestor = ancestry_.front();
if (current_ == ancestor->timeline_begin()) {
CHECK_NOTNULL(ancestor->parent_);
// At the beginning of the first timeline. Push the parent in front of the
// ancestry and set |current_| to the fork point. If the timeline is empty,
// keep going until we find a non-empty one or the root.
do {
current_ = *ancestor->position_in_parent_timeline_;
ancestor = ancestor->parent_;
ancestry_.push_front(ancestor);
} while (current_ == ancestor->timeline_end() &&
ancestor->parent_ != nullptr);
return *this;
}
--current_;
return *this;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::TimelineConstIterator
Forkable<Tr4jectory>::Iterator::current() const {
return current_;
}
template<typename Tr4jectory>
not_null<Tr4jectory const*> Forkable<Tr4jectory>::Iterator::trajectory() const {
CHECK(!ancestry_.empty());
return ancestry_.back();
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::Iterator::NormalizeIfEnd() {
CHECK(!ancestry_.empty());
if (current_ == ancestry_.front()->timeline_end() &&
ancestry_.size() > 1) {
ancestry_.erase(ancestry_.begin(), --ancestry_.end());
current_ = ancestry_.front()->timeline_end();
}
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::Iterator::CheckNormalizedIfEnd() {
CHECK(current_ != ancestry_.front()->timeline_end() ||
ancestry_.size() == 1);
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Begin() const {
not_null<Tr4jectory const*> ancestor = root();
return Wrap(ancestor, ancestor->timeline_begin());
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::End() const {
not_null<Tr4jectory const*> const ancestor = that();
Iterator iterator;
iterator.ancestry_.push_front(ancestor);
iterator.current_ = ancestor->timeline_end();
iterator.CheckNormalizedIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Find(Instant const& time) const {
Iterator iterator;
// Go up the ancestry chain until we find a timeline that covers |time| (that
// is, |time| is after the first time of the timeline). Set |current_| to
// the location of |time|, which may be |end()|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
Tr4jectory const* ancestor = that();
do {
iterator.ancestry_.push_front(ancestor);
if (!ancestor->timeline_empty() &&
ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) {
iterator.current_ = ancestor->timeline_find(time); // May be at end.
break;
}
iterator.current_ = ancestor->timeline_end();
ancestor = ancestor->parent_;
} while (ancestor != nullptr);
iterator.NormalizeIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::LowerBound(Instant const& time) const {
Iterator iterator;
// Go up the ancestry chain until we find a timeline that covers |time| (that
// is, |time| is after the first time of the timeline). Set |current_| to
// the location of |time|, which may be |end()|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
Tr4jectory const* ancestor = that();
do {
iterator.ancestry_.push_front(ancestor);
if (!ancestor->timeline_empty() &&
ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) {
iterator.current_ =
ancestor->timeline_lower_bound(time); // May be at end.
break;
}
iterator.current_ = ancestor->timeline_begin();
ancestor = ancestor->parent_;
} while (ancestor != nullptr);
iterator.NormalizeIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Wrap(
not_null<const Tr4jectory*> const ancestor,
TimelineConstIterator const position_in_ancestor_timeline) const {
Iterator iterator;
// Go up the ancestry chain until we find |ancestor| and set |current_| to
// |position_in_ancestor_timeline|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
not_null<Tr4jectory const*> ancest0r = that();
do {
iterator.ancestry_.push_front(ancest0r);
if (ancestor == ancest0r) {
iterator.current_ = position_in_ancestor_timeline; // May be at end.
iterator.CheckNormalizedIfEnd();
return iterator;
}
iterator.current_ = ancest0r->timeline_end();
ancest0r = ancest0r->parent_;
} while (ancest0r != nullptr);
LOG(FATAL) << "The ancestor parameter is not an ancestor of this trajectory";
base::noreturn();
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::WritePointerToMessage(
not_null<serialization::Trajectory::Pointer*> const message) const {
not_null<Tr4jectory const*> ancestor = that();
while (ancestor->parent_ != nullptr) {
auto const position_in_parent_children = position_in_parent_children_;
auto const position_in_parent_timeline = position_in_parent_timeline_;
ancestor = ancestor->parent_;
int const children_distance = std::distance(ancestor->children_.begin(),
*position_in_parent_children);
int const timeline_distance = std::distance(ancestor->timeline_begin(),
*position_in_parent_timeline);
auto* const fork_message = message->add_fork();
fork_message->set_children_distance(children_distance);
fork_message->set_timeline_distance(timeline_distance);
}
}
template<typename Tr4jectory>
not_null<Tr4jectory*> Forkable<Tr4jectory>::ReadPointerFromMessage(
serialization::Trajectory::Pointer const& message,
not_null<Tr4jectory*> const trajectory) {
CHECK(trajectory->is_root());
not_null<Tr4jectory*> descendant = trajectory;
for (auto const& fork_message : message.fork()) {
int const children_distance = fork_message.children_distance();
int const timeline_distance = fork_message.timeline_distance();
auto children_it = descendant->children_.begin();
auto timeline_it = descendant->timeline_begin();
std::advance(children_it, children_distance);
std::advance(timeline_it, timeline_distance);
descendant = &children_it->second;
}
return descendant;
}
template<typename Tr4jectory>
not_null<Tr4jectory*> Forkable<Tr4jectory>::NewFork(Instant const & time) {
std::experimental::optional<Instant> const fork_time = ForkTime();
CHECK(timeline_find(time) != timeline_end() ||
(fork_time && time == *fork_time))
<< "NewFork at nonexistent time " << time;
// May be at |timeline_end()| if |time| is the fork time of this object.
auto timeline_it = timeline_find(time);
// First create a child in the multimap.
auto const child_it = children_.emplace(std::piecewise_construct,
std::forward_as_tuple(time),
std::forward_as_tuple());
// Now set the members of the child object.
auto& child_forkable = child_it->second;
child_forkable.parent_ = that();
child_forkable.position_in_parent_children_ = child_it;
child_forkable.position_in_parent_timeline_ = timeline_it;
return &child_forkable;
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteAllForksAfter(Instant const& time) {
// Get an iterator denoting the first entry with time > |time|. Remove that
// entry and all the entries that follow it. This preserve any entry with
// time == |time|.
CHECK(is_root() || time >= *ForkTime())
<< "DeleteAllForksAfter before the fork time";
auto const it = children_.upper_bound(time);
children_.erase(it, children_.end());
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteAllForksBefore(Instant const& time) {
CHECK(is_root()) << "DeleteAllForksBefore on a nonroot trajectory";
// Get an iterator denoting the first entry with time > |time|. Remove all
// the entries that precede it. This removes any entry with time == |time|.
auto it = children_.upper_bound(time);
children_.erase(children_.begin(), it);
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const {
std::experimental::optional<Instant> last_instant;
serialization::Trajectory::Litter* litter = nullptr;
for (auto const& pair : children_) {
Instant const& fork_time = pair.first;
Tr4jectory const& child = pair.second;
if (!last_instant || fork_time != last_instant) {
last_instant = fork_time;
litter = message->add_children();
fork_time.WriteToMessage(litter->mutable_fork_time());
}
child.WriteSubTreeToMessage(litter->add_trajectories());
}
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::FillSubTreeFromMessage(
serialization::Trajectory const& message) {
for (serialization::Trajectory::Litter const& litter : message.children()) {
Instant const fork_time = Instant::ReadFromMessage(litter.fork_time());
for (serialization::Trajectory const& child : litter.trajectories()) {
NewFork(fork_time)->FillSubTreeFromMessage(child);
}
}
}
} // namespace physics
} // namespace principia
<commit_msg>Access optional from inside last_instant.<commit_after>#pragma once
#include "physics/forkable.hpp"
namespace principia {
namespace physics {
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteFork(not_null<Tr4jectory**> const trajectory) {
CHECK_NOTNULL(*trajectory);
std::experimental::optional<Instant> const fork_time =
(*trajectory)->ForkTime();
CHECK(fork_time);
// Find the position of |*forkable| among our children and remove it.
auto const range = children_.equal_range(*fork_time);
for (auto it = range.first; it != range.second; ++it) {
if (&it->second == *trajectory) {
children_.erase(it);
*trajectory = nullptr;
return;
}
}
LOG(FATAL) << "argument is not a child of this trajectory";
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::is_root() const {
return parent_ == nullptr;
}
template<typename Tr4jectory>
not_null<Tr4jectory const*>
Forkable<Tr4jectory>::root() const {
not_null<Tr4jectory const*> ancestor = that();
while (ancestor->parent_ != nullptr) {
ancestor = ancestor->parent_;
}
return ancestor;
}
template<typename Tr4jectory>
not_null<Tr4jectory*>
Forkable<Tr4jectory>::root() {
not_null<Tr4jectory*> ancestor = that();
while (ancestor->parent_ != nullptr) {
ancestor = ancestor->parent_;
}
return ancestor;
}
template<typename Tr4jectory>
std::experimental::optional<Instant> Forkable<Tr4jectory>::ForkTime() const {
if (is_root()) {
return std::experimental::nullopt;
} else {
return (*position_in_parent_children_)->first;
}
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::Iterator::operator==(Iterator const& right) const {
return ancestry_ == right.ancestry_ && current_ == right.current_;
}
template<typename Tr4jectory>
bool Forkable<Tr4jectory>::Iterator::operator!=(Iterator const& right) const {
return !(*this == right);
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator&
Forkable<Tr4jectory>::Iterator::operator++() {
CHECK(!ancestry_.empty());
CHECK(current_ != ancestry_.front()->timeline_end());
// Check if there is a next child in the ancestry.
auto ancestry_it = ancestry_.begin();
if (++ancestry_it != ancestry_.end()) {
// There is a next child. See if we reached its fork time.
Instant const& current_time = ForkableTraits<Tr4jectory>::time(current_);
not_null<Tr4jectory const*> child = *ancestry_it;
Instant child_fork_time = (*child->position_in_parent_children_)->first;
if (current_time == child_fork_time) {
// We have reached the fork time of the next child. There may be several
// forks at that time so we must skip them until we find a fork that is at
// a different time or the end of the children.
do {
current_ = child->timeline_begin(); // May be at end.
ancestry_.pop_front();
if (++ancestry_it == ancestry_.end()) {
break;
}
child = *ancestry_it;
child_fork_time = (*child->position_in_parent_children_)->first;
} while (current_time == child_fork_time);
CheckNormalizedIfEnd();
return *this;
}
}
// Business as usual, keep moving along the same timeline.
++current_;
CheckNormalizedIfEnd();
return *this;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator&
Forkable<Tr4jectory>::Iterator::operator--() {
CHECK(!ancestry_.empty());
not_null<Tr4jectory const*> ancestor = ancestry_.front();
if (current_ == ancestor->timeline_begin()) {
CHECK_NOTNULL(ancestor->parent_);
// At the beginning of the first timeline. Push the parent in front of the
// ancestry and set |current_| to the fork point. If the timeline is empty,
// keep going until we find a non-empty one or the root.
do {
current_ = *ancestor->position_in_parent_timeline_;
ancestor = ancestor->parent_;
ancestry_.push_front(ancestor);
} while (current_ == ancestor->timeline_end() &&
ancestor->parent_ != nullptr);
return *this;
}
--current_;
return *this;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::TimelineConstIterator
Forkable<Tr4jectory>::Iterator::current() const {
return current_;
}
template<typename Tr4jectory>
not_null<Tr4jectory const*> Forkable<Tr4jectory>::Iterator::trajectory() const {
CHECK(!ancestry_.empty());
return ancestry_.back();
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::Iterator::NormalizeIfEnd() {
CHECK(!ancestry_.empty());
if (current_ == ancestry_.front()->timeline_end() &&
ancestry_.size() > 1) {
ancestry_.erase(ancestry_.begin(), --ancestry_.end());
current_ = ancestry_.front()->timeline_end();
}
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::Iterator::CheckNormalizedIfEnd() {
CHECK(current_ != ancestry_.front()->timeline_end() ||
ancestry_.size() == 1);
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Begin() const {
not_null<Tr4jectory const*> ancestor = root();
return Wrap(ancestor, ancestor->timeline_begin());
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::End() const {
not_null<Tr4jectory const*> const ancestor = that();
Iterator iterator;
iterator.ancestry_.push_front(ancestor);
iterator.current_ = ancestor->timeline_end();
iterator.CheckNormalizedIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Find(Instant const& time) const {
Iterator iterator;
// Go up the ancestry chain until we find a timeline that covers |time| (that
// is, |time| is after the first time of the timeline). Set |current_| to
// the location of |time|, which may be |end()|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
Tr4jectory const* ancestor = that();
do {
iterator.ancestry_.push_front(ancestor);
if (!ancestor->timeline_empty() &&
ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) {
iterator.current_ = ancestor->timeline_find(time); // May be at end.
break;
}
iterator.current_ = ancestor->timeline_end();
ancestor = ancestor->parent_;
} while (ancestor != nullptr);
iterator.NormalizeIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::LowerBound(Instant const& time) const {
Iterator iterator;
// Go up the ancestry chain until we find a timeline that covers |time| (that
// is, |time| is after the first time of the timeline). Set |current_| to
// the location of |time|, which may be |end()|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
Tr4jectory const* ancestor = that();
do {
iterator.ancestry_.push_front(ancestor);
if (!ancestor->timeline_empty() &&
ForkableTraits<Tr4jectory>::time(ancestor->timeline_begin()) <= time) {
iterator.current_ =
ancestor->timeline_lower_bound(time); // May be at end.
break;
}
iterator.current_ = ancestor->timeline_begin();
ancestor = ancestor->parent_;
} while (ancestor != nullptr);
iterator.NormalizeIfEnd();
return iterator;
}
template<typename Tr4jectory>
typename Forkable<Tr4jectory>::Iterator
Forkable<Tr4jectory>::Wrap(
not_null<const Tr4jectory*> const ancestor,
TimelineConstIterator const position_in_ancestor_timeline) const {
Iterator iterator;
// Go up the ancestry chain until we find |ancestor| and set |current_| to
// |position_in_ancestor_timeline|. The ancestry has |forkable|
// at the back, and the object containing |current_| at the front.
not_null<Tr4jectory const*> ancest0r = that();
do {
iterator.ancestry_.push_front(ancest0r);
if (ancestor == ancest0r) {
iterator.current_ = position_in_ancestor_timeline; // May be at end.
iterator.CheckNormalizedIfEnd();
return iterator;
}
iterator.current_ = ancest0r->timeline_end();
ancest0r = ancest0r->parent_;
} while (ancest0r != nullptr);
LOG(FATAL) << "The ancestor parameter is not an ancestor of this trajectory";
base::noreturn();
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::WritePointerToMessage(
not_null<serialization::Trajectory::Pointer*> const message) const {
not_null<Tr4jectory const*> ancestor = that();
while (ancestor->parent_ != nullptr) {
auto const position_in_parent_children = position_in_parent_children_;
auto const position_in_parent_timeline = position_in_parent_timeline_;
ancestor = ancestor->parent_;
int const children_distance = std::distance(ancestor->children_.begin(),
*position_in_parent_children);
int const timeline_distance = std::distance(ancestor->timeline_begin(),
*position_in_parent_timeline);
auto* const fork_message = message->add_fork();
fork_message->set_children_distance(children_distance);
fork_message->set_timeline_distance(timeline_distance);
}
}
template<typename Tr4jectory>
not_null<Tr4jectory*> Forkable<Tr4jectory>::ReadPointerFromMessage(
serialization::Trajectory::Pointer const& message,
not_null<Tr4jectory*> const trajectory) {
CHECK(trajectory->is_root());
not_null<Tr4jectory*> descendant = trajectory;
for (auto const& fork_message : message.fork()) {
int const children_distance = fork_message.children_distance();
int const timeline_distance = fork_message.timeline_distance();
auto children_it = descendant->children_.begin();
auto timeline_it = descendant->timeline_begin();
std::advance(children_it, children_distance);
std::advance(timeline_it, timeline_distance);
descendant = &children_it->second;
}
return descendant;
}
template<typename Tr4jectory>
not_null<Tr4jectory*> Forkable<Tr4jectory>::NewFork(Instant const & time) {
std::experimental::optional<Instant> const fork_time = ForkTime();
CHECK(timeline_find(time) != timeline_end() ||
(fork_time && time == *fork_time))
<< "NewFork at nonexistent time " << time;
// May be at |timeline_end()| if |time| is the fork time of this object.
auto timeline_it = timeline_find(time);
// First create a child in the multimap.
auto const child_it = children_.emplace(std::piecewise_construct,
std::forward_as_tuple(time),
std::forward_as_tuple());
// Now set the members of the child object.
auto& child_forkable = child_it->second;
child_forkable.parent_ = that();
child_forkable.position_in_parent_children_ = child_it;
child_forkable.position_in_parent_timeline_ = timeline_it;
return &child_forkable;
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteAllForksAfter(Instant const& time) {
// Get an iterator denoting the first entry with time > |time|. Remove that
// entry and all the entries that follow it. This preserve any entry with
// time == |time|.
CHECK(is_root() || time >= *ForkTime())
<< "DeleteAllForksAfter before the fork time";
auto const it = children_.upper_bound(time);
children_.erase(it, children_.end());
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::DeleteAllForksBefore(Instant const& time) {
CHECK(is_root()) << "DeleteAllForksBefore on a nonroot trajectory";
// Get an iterator denoting the first entry with time > |time|. Remove all
// the entries that precede it. This removes any entry with time == |time|.
auto it = children_.upper_bound(time);
children_.erase(children_.begin(), it);
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::WriteSubTreeToMessage(
not_null<serialization::Trajectory*> const message) const {
std::experimental::optional<Instant> last_instant;
serialization::Trajectory::Litter* litter = nullptr;
for (auto const& pair : children_) {
Instant const& fork_time = pair.first;
Tr4jectory const& child = pair.second;
if (!last_instant || fork_time != *last_instant) {
last_instant = fork_time;
litter = message->add_children();
fork_time.WriteToMessage(litter->mutable_fork_time());
}
child.WriteSubTreeToMessage(litter->add_trajectories());
}
}
template<typename Tr4jectory>
void Forkable<Tr4jectory>::FillSubTreeFromMessage(
serialization::Trajectory const& message) {
for (serialization::Trajectory::Litter const& litter : message.children()) {
Instant const fork_time = Instant::ReadFromMessage(litter.fork_time());
for (serialization::Trajectory const& child : litter.trajectories()) {
NewFork(fork_time)->FillSubTreeFromMessage(child);
}
}
}
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
* @file /home/ryan/programming/atl/print.hpp
* @author Ryan Domigan <ryan_domigan@[email protected]>
* Created on Aug 10, 2013
*/
#include <functional>
#include <iostream>
#include <utility>
#include "./utility.hpp"
#include "./helpers.hpp"
namespace atl
{
namespace printer
{
struct Printer
{
virtual std::ostream& print(std::ostream&) const = 0;
};
typedef ::Range<typename Ast::const_iterator> Range;
struct PrintRange : public Printer
{
Range _range;
char _delim_open, _delim_close;
PrintRange(Range const& range, char delim_open, char delim_close)
: _range(range),
_delim_open(delim_open),
_delim_close(delim_close)
{}
virtual std::ostream& print(std::ostream&) const;
};
struct PrintAny : public Printer
{
const Any &a;
PrintAny(const Any &a_) : a(a_) {}
virtual std::ostream& print(std::ostream&) const;
};
PrintRange range(Range const& rr, char open='(', char close=')')
{ return PrintRange(rr, open, close); }
PrintAny any(Any const& aa) { return PrintAny(aa); }
std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }
std::ostream& PrintRange::print(std::ostream& out) const
{
if(_range.empty())
return out << _delim_open << _delim_close << endl;
else {
out << _delim_open << printer::any(_range[0]) << flush;
for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
return out << _delim_close;
}
}
std::ostream& PrintAny::print(std::ostream& out) const
{
auto trim_addr = [](void *pntr)
{ return reinterpret_cast<long>(pntr) & (256 - 1); };
using namespace std;
switch(a._tag)
{
case tag<Undefined>::value:
{
out << "#<Undefined ";
return out << ":" << hex << trim_addr(a.value) << ">";
}
case tag<Symbol>::value:
return out << "'" << unwrap<string>(a);
case tag<Type>::value:
return out << "#{" << unwrap<Type>(a).value << "}";
case tag<Fixnum>::value:
return out << value<Fixnum>(a);
case tag<Bool>::value:
{
if(value<bool>(a))
return out << "True";
else
return out << "False";
}
case tag<String>::value:
return out << '"' << *reinterpret_cast<string*>(a.value) << '"';
case tag<CxxFunctor>::value:
return out << unwrap<CxxFunctor>(a)._name;
case tag<Pointer>::value:
{
if(a.value)
return out << "#<Pointer-" << hex << (reinterpret_cast<long>(a.value) & (256 - 1)) << ">";
else
return out << "#<Pointer-NULL>";
}
case tag<Ast>::value:
return out << range(make_range(unwrap<Ast>(a)));
case tag<AstData>::value:
return out << range(make_range(unwrap<AstData>(a)));
case tag<Slice>::value:
return out << range(make_range(unwrap<Slice>(a)), '[', ']');
case tag<DefProcedure>::value:
{
out << "#<DefProcedure" << flush;
auto closure = unwrap<DefProcedure>(a).closure;
if(!closure.empty())
{
out << " (" << closure.size() << " free vars)";
}
return out << ">" << flush;;
}
default:
return out << "#<" << type_name(a._tag) << ">";
}
}
}
void dbg_any(Any vv)
{ cout << printer::any(vv) << endl; }
void dbg_pbv(PassByValue value)
{ return dbg_any(value.as_Any()); }
void dbg_ast(Ast const& vv)
{ cout << printer::range(make_range(vv)) << endl; }
}
#endif
<commit_msg>Print type information<commit_after>#ifndef ATL_PRINT_HH
#define ATL_PRINT_HH
/**
* @file /home/ryan/programming/atl/print.hpp
* @author Ryan Domigan <ryan_domigan@[email protected]>
* Created on Aug 10, 2013
*/
#include <functional>
#include <iostream>
#include <utility>
#include "./utility.hpp"
#include "./helpers.hpp"
namespace atl
{
namespace printer
{
struct Printer
{
virtual std::ostream& print(std::ostream&) const = 0;
};
typedef ::Range<typename Ast::const_iterator> Range;
struct PrintRange : public Printer
{
Range _range;
char _delim_open, _delim_close;
PrintRange(Range const& range, char delim_open, char delim_close)
: _range(range),
_delim_open(delim_open),
_delim_close(delim_close)
{}
virtual std::ostream& print(std::ostream&) const;
};
struct PrintAny : public Printer
{
const Any &a;
PrintAny(const Any &a_) : a(a_) {}
virtual std::ostream& print(std::ostream&) const;
};
PrintRange range(Range const& rr, char open='(', char close=')')
{ return PrintRange(rr, open, close); }
PrintAny any(Any const& aa) { return PrintAny(aa); }
std::ostream& operator<<(std::ostream& out, const printer::Printer& p) { return p.print(out); }
std::ostream& PrintRange::print(std::ostream& out) const
{
if(_range.empty())
return out << _delim_open << _delim_close << endl;
else {
out << _delim_open << printer::any(_range[0]) << flush;
for(auto& vv : slice(_range, 1)) out << " " << printer::any(vv);
return out << _delim_close;
}
}
std::ostream& PrintAny::print(std::ostream& out) const
{
auto trim_addr = [](void *pntr)
{ return reinterpret_cast<long>(pntr) & (256 - 1); };
using namespace std;
switch(a._tag)
{
case tag<Undefined>::value:
{
out << "#<Undefined ";
return out << ":" << hex << trim_addr(a.value) << ">";
}
case tag<Symbol>::value:
return out << "'" << unwrap<string>(a);
case tag<Type>::value:
return out << "#{" << unwrap<Type>(a).value << "}";
case tag<Fixnum>::value:
return out << value<Fixnum>(a);
case tag<Bool>::value:
{
if(value<bool>(a))
return out << "True";
else
return out << "False";
}
case tag<String>::value:
return out << '"' << *reinterpret_cast<string*>(a.value) << '"';
case tag<CxxFunctor>::value:
return out << unwrap<CxxFunctor>(a)._name;
case tag<Pointer>::value:
{
if(a.value)
return out << "#<Pointer-" << hex << (reinterpret_cast<long>(a.value) & (256 - 1)) << ">";
else
return out << "#<Pointer-NULL>";
}
case tag<Ast>::value:
return out << range(make_range(unwrap<Ast>(a)));
case tag<AstData>::value:
return out << range(make_range(unwrap<AstData>(a)));
case tag<Slice>::value:
return out << range(make_range(unwrap<Slice>(a)), '[', ']');
case tag<DefProcedure>::value:
{
out << "#<DefProcedure" << flush;
auto closure = unwrap<DefProcedure>(a).closure;
if(!closure.empty())
{
out << " (" << closure.size() << " free vars)";
}
return out << ">" << flush;;
}
default:
return out << "#<" << type_name(a._tag) << ">";
}
}
}
void dbg_any(Any vv)
{ cout << printer::any(vv) << endl; }
void dbg_pbv(PassByValue value)
{ return dbg_any(value.as_Any()); }
void dbg_ast(Ast const& vv)
{ cout << printer::range(make_range(vv)) << endl; }
std::ostream& print_type(PassByValue const& value, std::ostream& out)
{
switch(value._tag)
{
case tag<Ast>::value:
{
auto ast = unwrap<Ast>(value);
out << "(";
if(!ast.empty())
{
print_type(ast[0], out);
for(auto& vv : slice(ast, 1))
{
out << ' ';
print_type(vv, out);
}
}
return out << ")";
}
case tag<Type>::value:
{ return out << "#<Type: " << unwrap<Type>(value).value << ">"; }
default:
return out << type_name(value._tag);
}
}
void dbg_type(PassByValue const& value)
{ print_type(value, std::cout) << std::endl; }
}
#endif
<|endoftext|> |
<commit_before>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//
#include "ClangDiagnosticsEmitter.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/VectorExtras.h"
#include <set>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//
void ClangDiagsDefsEmitter::run(std::ostream &OS) {
// Write the #if guard
if (!Component.empty()) {
std::string ComponentName = UppercaseString(Component);
OS << "#ifdef " << ComponentName << "START\n";
OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
<< ",\n";
OS << "#undef " << ComponentName << "START\n";
OS << "#endif\n";
}
const std::vector<Record*> &Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record &R = *Diags[i];
// Filter by component.
if (!Component.empty() && Component != R.getValueAsString("Component"))
continue;
OS << "DIAG(" << R.getName() << ", ";
OS << R.getValueAsDef("Class")->getName();
OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();
OS << ", \"";
std::string S = R.getValueAsString("Text");
EscapeString(S);
OS << S << "\")\n";
}
}
//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//
void ClangDiagGroupsEmitter::run(std::ostream &OS) {
// Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
// groups to diags in the group.
std::map<std::string, std::vector<const Record*> > DiagsInGroup;
std::vector<Record*> Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record *R = Diags[i];
DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
if (DI == 0) continue;
DiagsInGroup[DI->getDef()->getValueAsString("GroupName")].push_back(R);
}
// Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
// groups (these are warnings that GCC supports that clang never produces).
Diags = Records.getAllDerivedDefinitions("DiagGroup");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
DiagsInGroup[Diags[i]->getValueAsString("GroupName")];
}
// Walk through the groups emitting an array for each diagnostic of the diags
// that are mapped to.
OS << "\n#ifdef GET_DIAG_ARRAYS\n";
unsigned IDNo = 0;
unsigned MaxLen = 0;
for (std::map<std::string, std::vector<const Record*> >::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
MaxLen = std::max(MaxLen, (unsigned)I->first.size());
OS << "static const short DiagArray" << IDNo++
<< "[] = { ";
std::vector<const Record*> &V = I->second;
for (unsigned i = 0, e = V.size(); i != e; ++i)
OS << "diag::" << V[i]->getName() << ", ";
OS << "-1 };\n";
}
OS << "#endif // GET_DIAG_ARRAYS\n\n";
// Emit the table now.
OS << "\n#ifdef GET_DIAG_TABLE\n";
IDNo = 0;
for (std::map<std::string, std::vector<const Record*> >::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
std::string S = I->first;
EscapeString(S);
OS << " { \"" << S << "\","
<< std::string(MaxLen-I->first.size()+1, ' ')
<< "DiagArray" << IDNo++ << " },\n";
}
OS << "#endif // GET_DIAG_TABLE\n\n";
}
<commit_msg>start producing subgroup info.<commit_after>//=- ClangDiagnosticsEmitter.cpp - Generate Clang diagnostics tables -*- C++ -*-
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// These tablegen backends emit Clang diagnostics tables.
//
//===----------------------------------------------------------------------===//
#include "ClangDiagnosticsEmitter.h"
#include "Record.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/VectorExtras.h"
#include <set>
#include <map>
using namespace llvm;
//===----------------------------------------------------------------------===//
// Warning Tables (.inc file) generation.
//===----------------------------------------------------------------------===//
void ClangDiagsDefsEmitter::run(std::ostream &OS) {
// Write the #if guard
if (!Component.empty()) {
std::string ComponentName = UppercaseString(Component);
OS << "#ifdef " << ComponentName << "START\n";
OS << "__" << ComponentName << "START = DIAG_START_" << ComponentName
<< ",\n";
OS << "#undef " << ComponentName << "START\n";
OS << "#endif\n";
}
const std::vector<Record*> &Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record &R = *Diags[i];
// Filter by component.
if (!Component.empty() && Component != R.getValueAsString("Component"))
continue;
OS << "DIAG(" << R.getName() << ", ";
OS << R.getValueAsDef("Class")->getName();
OS << ", diag::" << R.getValueAsDef("DefaultMapping")->getName();
OS << ", \"";
std::string S = R.getValueAsString("Text");
EscapeString(S);
OS << S << "\")\n";
}
}
//===----------------------------------------------------------------------===//
// Warning Group Tables generation
//===----------------------------------------------------------------------===//
struct GroupInfo {
std::vector<const Record*> DiagsInGroup;
std::vector<std::string> SubGroups;
};
void ClangDiagGroupsEmitter::run(std::ostream &OS) {
// Invert the 1-[0/1] mapping of diags to group into a one to many mapping of
// groups to diags in the group.
std::map<std::string, GroupInfo> DiagsInGroup;
std::vector<Record*> Diags =
Records.getAllDerivedDefinitions("Diagnostic");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
const Record *R = Diags[i];
DefInit *DI = dynamic_cast<DefInit*>(R->getValueInit("Group"));
if (DI == 0) continue;
std::string GroupName = DI->getDef()->getValueAsString("GroupName");
DiagsInGroup[GroupName].DiagsInGroup.push_back(R);
}
// Add all DiagGroup's to the DiagsInGroup list to make sure we pick up empty
// groups (these are warnings that GCC supports that clang never produces).
Diags = Records.getAllDerivedDefinitions("DiagGroup");
for (unsigned i = 0, e = Diags.size(); i != e; ++i) {
Record *Group = Diags[i];
GroupInfo &GI = DiagsInGroup[Group->getValueAsString("GroupName")];
std::vector<Record*> SubGroups = Group->getValueAsListOfDefs("SubGroups");
for (unsigned j = 0, e = SubGroups.size(); j != e; ++j)
GI.SubGroups.push_back(SubGroups[j]->getValueAsString("GroupName"));
}
// Walk through the groups emitting an array for each diagnostic of the diags
// that are mapped to.
OS << "\n#ifdef GET_DIAG_ARRAYS\n";
unsigned IDNo = 0;
unsigned MaxLen = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
MaxLen = std::max(MaxLen, (unsigned)I->first.size());
std::vector<const Record*> &V = I->second.DiagsInGroup;
if (V.empty()) continue;
OS << "static const short DiagArray" << IDNo++
<< "[] = { ";
for (unsigned i = 0, e = V.size(); i != e; ++i)
OS << "diag::" << V[i]->getName() << ", ";
OS << "-1 };\n";
}
OS << "#endif // GET_DIAG_ARRAYS\n\n";
// Emit the table now.
OS << "\n#ifdef GET_DIAG_TABLE\n";
IDNo = 0;
for (std::map<std::string, GroupInfo>::iterator
I = DiagsInGroup.begin(), E = DiagsInGroup.end(); I != E; ++I) {
std::string S = I->first;
EscapeString(S);
// Group option string.
OS << " { \"" << S << "\","
<< std::string(MaxLen-I->first.size()+1, ' ');
// Diagnostics in the group.
if (I->second.DiagsInGroup.empty())
OS << "0, ";
else
OS << "DiagArray" << IDNo++ << ", ";
// FIXME: Subgroups.
OS << 0;
OS << " },\n";
}
OS << "#endif // GET_DIAG_TABLE\n\n";
}
<|endoftext|> |
<commit_before>#include "physics/forkable.hpp"
#include "geometry/named_quantities.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
namespace principia {
using geometry::Instant;
using si::Second;
using ::testing::ElementsAre;
namespace physics {
class FakeTrajectory;
template<>
struct ForkableTraits<FakeTrajectory> {
using TimelineConstIterator = std::list<Instant>::const_iterator;
static Instant const& time(TimelineConstIterator const it);
};
class FakeTrajectory : public Forkable<FakeTrajectory> {
public:
FakeTrajectory() = default;
void push_back(Instant const& time);
protected:
not_null<FakeTrajectory*> that() override;
not_null<FakeTrajectory const*> that() const override;
TimelineConstIterator timeline_begin() const override;
TimelineConstIterator timeline_end() const override;
TimelineConstIterator timeline_find(Instant const& time) const override;
void timeline_insert(TimelineConstIterator begin,
TimelineConstIterator end) override;
bool timeline_empty() const override;
private:
// Use list<> because we want the iterators to remain valid across operations.
std::list<Instant> timeline_;
template<typename Tr4jectory>
friend class Forkable;
};
Instant const& ForkableTraits<FakeTrajectory>::time(
TimelineConstIterator const it) {
return *it;
}
void FakeTrajectory::push_back(Instant const& time) {
timeline_.push_back(time);
}
not_null<FakeTrajectory*> FakeTrajectory::that() {
return this;
}
not_null<FakeTrajectory const*> FakeTrajectory::that() const {
return this;
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_begin() const {
return timeline_.begin();
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_end() const {
return timeline_.end();
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_find(
Instant const & time) const {
// Stupid O(N) search.
for (auto it = timeline_.begin(); it != timeline_.end(); ++it) {
if (*it == time) {
return it;
}
}
return timeline_.end();
}
void FakeTrajectory::timeline_insert(TimelineConstIterator begin,
TimelineConstIterator end) {
CHECK(timeline_empty());
timeline_.insert(timeline_.end(), begin, end);
}
bool FakeTrajectory::timeline_empty() const {
return timeline_.empty();
}
class ForkableTest : public testing::Test {
protected:
ForkableTest() :
t0_(),
t1_(t0_ + 7 * Second),
t2_(t0_ + 17 * Second),
t3_(t0_ + 27 * Second),
t4_(t0_ + 37 * Second) {}
static std::vector<Instant> After(
not_null<FakeTrajectory const*> const trajectory,
Instant const& time) {
std::vector<Instant> after;
for (FakeTrajectory::Iterator it = trajectory->Find(time);
it != trajectory->End();
++it) {
after.push_back(*it.current());
}
return after;
}
static Instant const& LastTime(
not_null<FakeTrajectory const*> const trajectory) {
FakeTrajectory::Iterator it = trajectory->End();
--it;
return *it.current();
}
static std::vector<Instant> Times(
not_null<FakeTrajectory const*> const trajectory) {
std::vector<Instant> times;
for (FakeTrajectory::Iterator it = trajectory->Begin();
it != trajectory->End();
++it) {
times.push_back(*it.current());
}
return times;
}
FakeTrajectory trajectory_;
Instant t0_, t1_, t2_, t3_, t4_;
};
using ForkableDeathTest = ForkableTest;
TEST_F(ForkableDeathTest, ForkError) {
EXPECT_DEATH({
trajectory_.push_back(t1_);
trajectory_.push_back(t3_);
trajectory_.NewFork(t2_);
}, "nonexistent time");
}
TEST_F(ForkableDeathTest, ForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
auto times = Times(&trajectory_);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
times = Times(fork);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_));
}
TEST_F(ForkableTest, ForkAtLast) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t3_);
not_null<FakeTrajectory*> const fork2 = fork1->NewFork(LastTime(fork1));
not_null<FakeTrajectory*> const fork3 = fork2->NewFork(LastTime(fork1));
EXPECT_EQ(t3_, LastTime(&trajectory_));
EXPECT_EQ(t3_, LastTime(fork1));
auto times = Times(fork2);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
EXPECT_EQ(t3_, LastTime(fork2));
EXPECT_EQ(t3_, *fork2->ForkTime());
auto after = After(fork3, t3_);
EXPECT_THAT(after, ElementsAre(t3_));
after = After(fork2, t3_);
EXPECT_THAT(after, ElementsAre(t3_));
fork1->push_back(t4_);
times = Times(fork2);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
after = After(fork1, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
times = Times(fork3);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
fork2->push_back(t4_);
after = After(fork2, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
fork3->push_back(t4_);
after = After(fork3, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
after = After(fork3, t2_);
EXPECT_THAT(after, ElementsAre(t2_, t3_, t4_));
}
TEST_F(ForkableDeathTest, DeleteForkError) {
EXPECT_DEATH({
trajectory_.push_back(t1_);
FakeTrajectory* root = &trajectory_;
trajectory_.DeleteFork(&root);
}, "'fork_time'.* non NULL");
EXPECT_DEATH({
trajectory_.push_back(t1_);
FakeTrajectory* fork1 = trajectory_.NewFork(t1_);
fork1->push_back(t2_);
FakeTrajectory* fork2 = fork1->NewFork(t2_);
trajectory_.DeleteFork(&fork2);
}, "not a child");
}
TEST_F(ForkableTest, DeleteForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t2_);
FakeTrajectory* fork2 = trajectory_.NewFork(t2_);
fork1->push_back(t4_);
trajectory_.DeleteFork(&fork2);
EXPECT_EQ(nullptr, fork2);
auto times = Times(&trajectory_);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
times = Times(fork1);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_));
}
TEST_F(ForkableDeathTest, IteratorDecrementError) {
EXPECT_DEATH({
auto it = trajectory_.End();
--it;
}, "parent_.*non NULL");
}
TEST_F(ForkableTest, IteratorDecrementNoForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
auto it = trajectory_.End();
--it;
EXPECT_EQ(t3_, *it.current());
--it;
EXPECT_EQ(t2_, *it.current());
--it;
EXPECT_EQ(t1_, *it.current());
}
TEST_F(ForkableTest, IteratorDecrementForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
auto fork = trajectory_.NewFork(t1_);
trajectory_.push_back(t4_);
fork->push_back(t3_);
auto it = fork->End();
--it;
EXPECT_EQ(t3_, *it.current());
--it;
EXPECT_EQ(t2_, *it.current());
--it;
EXPECT_EQ(t1_, *it.current());
}
TEST_F(ForkableDeathTest, IteratorIncrementError) {
EXPECT_DEATH({
auto it = trajectory_.Begin();
++it;
}, "!at_end");
}
TEST_F(ForkableTest, IteratorIncrementNoForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
auto it = trajectory_.Begin();
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
}
TEST_F(ForkableTest, IteratorIncrementForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
auto fork = trajectory_.NewFork(t1_);
trajectory_.push_back(t4_);
fork->push_back(t3_);
auto it = fork->Begin();
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
}
TEST_F(ForkableTest, Root) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
EXPECT_TRUE(trajectory_.is_root());
EXPECT_FALSE(fork->is_root());
EXPECT_EQ(&trajectory_, trajectory_.root());
EXPECT_EQ(&trajectory_, fork->root());
EXPECT_EQ(nullptr, trajectory_.ForkTime());
EXPECT_EQ(t2_, *fork->ForkTime());
}
TEST_F(ForkableTest, IteratorBeginSuccess) {
auto it = trajectory_.Begin();
EXPECT_EQ(it, trajectory_.End());
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
it = trajectory_.Begin();
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
++it;
EXPECT_EQ(it, trajectory_.End());
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
it = fork->Begin();
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
++it;
EXPECT_EQ(t4_, *it.current());
++it;
EXPECT_EQ(it, trajectory_.End());
}
TEST_F(ForkableTest, IteratorFindSuccess) {
auto it = trajectory_.Find(t0_);
EXPECT_EQ(it, trajectory_.End());
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
it = trajectory_.Find(t1_);
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
it = trajectory_.Find(t2_);
EXPECT_EQ(t2_, *it.current());
it = trajectory_.Find(t4_);
EXPECT_EQ(it, trajectory_.End());
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
it = fork->Find(t1_);
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
it = fork->Find(t2_);
EXPECT_EQ(t2_, *it.current());
it = fork->Find(t4_);
EXPECT_EQ(t4_, *it.current());
it = fork->Find(t4_ + 1 * Second);
EXPECT_EQ(it, trajectory_.End());
}
} // namespace physics
} // namespace principia
<commit_msg>Lint.<commit_after>#include "physics/forkable.hpp"
#include <list>
#include <vector>
#include "geometry/named_quantities.hpp"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "quantities/si.hpp"
namespace principia {
using geometry::Instant;
using si::Second;
using ::testing::ElementsAre;
namespace physics {
class FakeTrajectory;
template<>
struct ForkableTraits<FakeTrajectory> {
using TimelineConstIterator = std::list<Instant>::const_iterator;
static Instant const& time(TimelineConstIterator const it);
};
class FakeTrajectory : public Forkable<FakeTrajectory> {
public:
FakeTrajectory() = default;
void push_back(Instant const& time);
protected:
not_null<FakeTrajectory*> that() override;
not_null<FakeTrajectory const*> that() const override;
TimelineConstIterator timeline_begin() const override;
TimelineConstIterator timeline_end() const override;
TimelineConstIterator timeline_find(Instant const& time) const override;
void timeline_insert(TimelineConstIterator begin,
TimelineConstIterator end) override;
bool timeline_empty() const override;
private:
// Use list<> because we want the iterators to remain valid across operations.
std::list<Instant> timeline_;
template<typename Tr4jectory>
friend class Forkable;
};
Instant const& ForkableTraits<FakeTrajectory>::time(
TimelineConstIterator const it) {
return *it;
}
void FakeTrajectory::push_back(Instant const& time) {
timeline_.push_back(time);
}
not_null<FakeTrajectory*> FakeTrajectory::that() {
return this;
}
not_null<FakeTrajectory const*> FakeTrajectory::that() const {
return this;
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_begin() const {
return timeline_.begin();
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_end() const {
return timeline_.end();
}
FakeTrajectory::TimelineConstIterator FakeTrajectory::timeline_find(
Instant const & time) const {
// Stupid O(N) search.
for (auto it = timeline_.begin(); it != timeline_.end(); ++it) {
if (*it == time) {
return it;
}
}
return timeline_.end();
}
void FakeTrajectory::timeline_insert(TimelineConstIterator begin,
TimelineConstIterator end) {
CHECK(timeline_empty());
timeline_.insert(timeline_.end(), begin, end);
}
bool FakeTrajectory::timeline_empty() const {
return timeline_.empty();
}
class ForkableTest : public testing::Test {
protected:
ForkableTest() :
t0_(),
t1_(t0_ + 7 * Second),
t2_(t0_ + 17 * Second),
t3_(t0_ + 27 * Second),
t4_(t0_ + 37 * Second) {}
static std::vector<Instant> After(
not_null<FakeTrajectory const*> const trajectory,
Instant const& time) {
std::vector<Instant> after;
for (FakeTrajectory::Iterator it = trajectory->Find(time);
it != trajectory->End();
++it) {
after.push_back(*it.current());
}
return after;
}
static Instant const& LastTime(
not_null<FakeTrajectory const*> const trajectory) {
FakeTrajectory::Iterator it = trajectory->End();
--it;
return *it.current();
}
static std::vector<Instant> Times(
not_null<FakeTrajectory const*> const trajectory) {
std::vector<Instant> times;
for (FakeTrajectory::Iterator it = trajectory->Begin();
it != trajectory->End();
++it) {
times.push_back(*it.current());
}
return times;
}
FakeTrajectory trajectory_;
Instant t0_, t1_, t2_, t3_, t4_;
};
using ForkableDeathTest = ForkableTest;
TEST_F(ForkableDeathTest, ForkError) {
EXPECT_DEATH({
trajectory_.push_back(t1_);
trajectory_.push_back(t3_);
trajectory_.NewFork(t2_);
}, "nonexistent time");
}
TEST_F(ForkableDeathTest, ForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
auto times = Times(&trajectory_);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
times = Times(fork);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_));
}
TEST_F(ForkableTest, ForkAtLast) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t3_);
not_null<FakeTrajectory*> const fork2 = fork1->NewFork(LastTime(fork1));
not_null<FakeTrajectory*> const fork3 = fork2->NewFork(LastTime(fork1));
EXPECT_EQ(t3_, LastTime(&trajectory_));
EXPECT_EQ(t3_, LastTime(fork1));
auto times = Times(fork2);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
EXPECT_EQ(t3_, LastTime(fork2));
EXPECT_EQ(t3_, *fork2->ForkTime());
auto after = After(fork3, t3_);
EXPECT_THAT(after, ElementsAre(t3_));
after = After(fork2, t3_);
EXPECT_THAT(after, ElementsAre(t3_));
fork1->push_back(t4_);
times = Times(fork2);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
after = After(fork1, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
times = Times(fork3);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
fork2->push_back(t4_);
after = After(fork2, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
fork3->push_back(t4_);
after = After(fork3, t3_);
EXPECT_THAT(after, ElementsAre(t3_, t4_));
after = After(fork3, t2_);
EXPECT_THAT(after, ElementsAre(t2_, t3_, t4_));
}
TEST_F(ForkableDeathTest, DeleteForkError) {
EXPECT_DEATH({
trajectory_.push_back(t1_);
FakeTrajectory* root = &trajectory_;
trajectory_.DeleteFork(&root);
}, "'fork_time'.* non NULL");
EXPECT_DEATH({
trajectory_.push_back(t1_);
FakeTrajectory* fork1 = trajectory_.NewFork(t1_);
fork1->push_back(t2_);
FakeTrajectory* fork2 = fork1->NewFork(t2_);
trajectory_.DeleteFork(&fork2);
}, "not a child");
}
TEST_F(ForkableTest, DeleteForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork1 = trajectory_.NewFork(t2_);
FakeTrajectory* fork2 = trajectory_.NewFork(t2_);
fork1->push_back(t4_);
trajectory_.DeleteFork(&fork2);
EXPECT_EQ(nullptr, fork2);
auto times = Times(&trajectory_);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_));
times = Times(fork1);
EXPECT_THAT(times, ElementsAre(t1_, t2_, t3_, t4_));
}
TEST_F(ForkableDeathTest, IteratorDecrementError) {
EXPECT_DEATH({
auto it = trajectory_.End();
--it;
}, "parent_.*non NULL");
}
TEST_F(ForkableTest, IteratorDecrementNoForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
auto it = trajectory_.End();
--it;
EXPECT_EQ(t3_, *it.current());
--it;
EXPECT_EQ(t2_, *it.current());
--it;
EXPECT_EQ(t1_, *it.current());
}
TEST_F(ForkableTest, IteratorDecrementForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
auto fork = trajectory_.NewFork(t1_);
trajectory_.push_back(t4_);
fork->push_back(t3_);
auto it = fork->End();
--it;
EXPECT_EQ(t3_, *it.current());
--it;
EXPECT_EQ(t2_, *it.current());
--it;
EXPECT_EQ(t1_, *it.current());
}
TEST_F(ForkableDeathTest, IteratorIncrementError) {
EXPECT_DEATH({
auto it = trajectory_.Begin();
++it;
}, "!at_end");
}
TEST_F(ForkableTest, IteratorIncrementNoForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
auto it = trajectory_.Begin();
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
}
TEST_F(ForkableTest, IteratorIncrementForkSuccess) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
auto fork = trajectory_.NewFork(t1_);
trajectory_.push_back(t4_);
fork->push_back(t3_);
auto it = fork->Begin();
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
}
TEST_F(ForkableTest, Root) {
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
EXPECT_TRUE(trajectory_.is_root());
EXPECT_FALSE(fork->is_root());
EXPECT_EQ(&trajectory_, trajectory_.root());
EXPECT_EQ(&trajectory_, fork->root());
EXPECT_EQ(nullptr, trajectory_.ForkTime());
EXPECT_EQ(t2_, *fork->ForkTime());
}
TEST_F(ForkableTest, IteratorBeginSuccess) {
auto it = trajectory_.Begin();
EXPECT_EQ(it, trajectory_.End());
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
it = trajectory_.Begin();
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
++it;
EXPECT_EQ(it, trajectory_.End());
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
it = fork->Begin();
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
++it;
EXPECT_EQ(t2_, *it.current());
++it;
EXPECT_EQ(t3_, *it.current());
++it;
EXPECT_EQ(t4_, *it.current());
++it;
EXPECT_EQ(it, trajectory_.End());
}
TEST_F(ForkableTest, IteratorFindSuccess) {
auto it = trajectory_.Find(t0_);
EXPECT_EQ(it, trajectory_.End());
trajectory_.push_back(t1_);
trajectory_.push_back(t2_);
trajectory_.push_back(t3_);
it = trajectory_.Find(t1_);
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
it = trajectory_.Find(t2_);
EXPECT_EQ(t2_, *it.current());
it = trajectory_.Find(t4_);
EXPECT_EQ(it, trajectory_.End());
not_null<FakeTrajectory*> const fork = trajectory_.NewFork(t2_);
fork->push_back(t4_);
it = fork->Find(t1_);
EXPECT_NE(it, trajectory_.End());
EXPECT_EQ(t1_, *it.current());
it = fork->Find(t2_);
EXPECT_EQ(t2_, *it.current());
it = fork->Find(t4_);
EXPECT_EQ(t4_, *it.current());
it = fork->Find(t4_ + 1 * Second);
EXPECT_EQ(it, trajectory_.End());
}
} // namespace physics
} // namespace principia
<|endoftext|> |
<commit_before>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "ManagedDatabase.h"
#include "dbms_utils.h"
#include "condor_config.h"
#include "pgsqldatabase.h"
#include "condor_email.h"
ManagedDatabase::ManagedDatabase() {
char *tmp;
QuillErrCode ret_st;
if (param_boolean("QUILL_ENABLED", false) == false) {
EXCEPT("Quill++ is currently disabled. Please set QUILL_ENABLED to "
"TRUE if you want this functionality and read the manual "
"about this feature since it requires other attributes to be "
"set properly.");
}
//bail out if no SPOOL variable is defined since its used to
//figure out the location of the quillWriter password file
char *spool = param("SPOOL");
if(!spool) {
EXCEPT("No SPOOL variable found in config file\n");
}
/*
Here we try to read the database parameters in config
the db ip address format is <ipaddress:port>
*/
dt = getConfigDBType();
dbIpAddress = param("QUILL_DB_IP_ADDR");
dbName = param("QUILL_DB_NAME");
dbUser = param("QUILL_DB_USER");
dbConnStr = getDBConnStr(dbIpAddress,
dbName,
dbUser,
spool);
dprintf(D_ALWAYS, "Using Database Type = Postgres\n");
dprintf(D_ALWAYS, "Using Database IpAddress = %s\n",
dbIpAddress?dbIpAddress:"");
dprintf(D_ALWAYS, "Using Database Name = %s\n",
dbName?dbName:"");
dprintf(D_ALWAYS, "Using Database User = %s\n",
dbUser?dbUser:"");
if (spool) {
free(spool);
}
switch (dt) {
case T_PGSQL:
DBObj = new PGSQLDatabase(dbConnStr);
break;
default:
break;
}
/* default to a week of resource history info */
resourceHistoryDuration = param_integer("QUILL_RESOURCE_HISTORY_DURATION", 7);
tmp = param("QUILL_RUN_HISTORY_DURATION");
if (tmp) {
runHistoryDuration= atoi(tmp);
free(tmp);
} else {
/* default to a week of job run information */
runHistoryDuration = 7;
}
tmp = param("QUILL_JOB_HISTORY_DURATION");
if (tmp) {
jobHistoryDuration= atoi(tmp);
free(tmp);
} else {
/* default to 10 years of job history */
jobHistoryDuration = 3650;
}
tmp = param("QUILL_DBSIZE_LIMIT");
if (tmp) {
dbSizeLimit= atoi(tmp);
free(tmp);
} else {
/* default to 20 GB */
dbSizeLimit = 20;
}
/* check if schema version is ok */
ret_st = DBObj->connectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "config: unable to connect to DB--- ERROR");
EXCEPT("config: unable to connect to DB\n");
}
/* the following will also throw an exception of the schema
version is not correct */
DBObj->assertSchemaVersion();
DBObj->disconnectDB();
}
ManagedDatabase::~ManagedDatabase() {
if (dbIpAddress) {
free(dbIpAddress);
dbIpAddress = NULL;
}
if (dbName) {
free(dbName);
dbName = NULL;
}
if (dbUser) {
free(dbUser);
dbUser = NULL;
}
if (dbConnStr) {
free(dbConnStr);
dbConnStr = NULL;
}
if (DBObj) {
delete DBObj;
}
}
void ManagedDatabase::PurgeDatabase() {
QuillErrCode ret_st;
int dbsize;
int num_result;
MyString sql_str;
ret_st = DBObj->connectDB();
/* call the puging routine */
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase: unable to connect to DB--- ERROR\n");
return;
}
switch (dt) {
case T_PGSQL:
sql_str.sprintf("select quill_purgeHistory(%d, %d, %d)",
resourceHistoryDuration,
runHistoryDuration,
jobHistoryDuration);
break;
default:
// can't have this case
dprintf(D_ALWAYS, "database type is %d, unexpected! exiting!\n", dt);
ASSERT(0);
break;
}
ret_st = DBObj->execCommand(sql_str.Value());
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase --- ERROR [SQL] %s\n",
sql_str.Value());
}
ret_st = DBObj->commitTransaction();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase --- ERROR [COMMIT] \n");
}
/* query the space usage and if it is above some threshold, send
a warning to the administrator
*/
sql_str.sprintf("SELECT dbsize FROM quillDBMonitor");
ret_st = DBObj->execQuery(sql_str.Value(), num_result);
if ((ret_st == QUILL_SUCCESS) &&
(num_result == 1)) {
dbsize = atoi(DBObj->getValue(0, 0));
/* if dbsize is bigger than 75% the dbSizeLimit, send a
warning to the administrator with information about
the situation and suggestion for looking at the table
sizes using the following sql statement and tune down
the *HistoryDuration parameters accordingly.
This is an oracle version of sql for examining the
table sizes in descending order, sql for other
databases can be similarly constructed:
SELECT NUM_ROWS*AVG_ROW_LEN, table_name
FROM USER_TABLES
ORDER BY NUM_ROWS*AVG_ROW_LEN DESC;
*/
if (dbsize/1024 > dbSizeLimit) {
FILE *email;
char msg_body[4000];
snprintf(msg_body, 4000, "Current database size (> %d MB) is "
"bigger than 75 percent of the limit (%d GB). Please "
"decrease the values of these parameters: "
"QUILL_RESOURCE_HISTORY_DURATION, "
"QUILL_RUN_HISTORY_DURATION, "
"QUILL_JOB_HISTORY_DURATION or QUILL_DBSIZE_LIMIT\n",
dbsize, dbSizeLimit);
/* notice that dbsize is stored in unit of MB, but
dbSizeLimit is stored in unit of GB */
dprintf(D_ALWAYS, "%s", msg_body);
email = email_admin_open(msg_body);
if (email) {
email_close ( email );
} else {
dprintf( D_ALWAYS, "ERROR: Can't send email to the Condor "
"Administrator\n" );
}
}
} else {
dprintf(D_ALWAYS, "Reading quillDBMonitor --- ERROR or returned # of rows is not exactly one [SQL] %s\n",
sql_str.Value());
}
DBObj->releaseQueryResult();
ret_st = DBObj->disconnectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::disconnectDB: unable to disconnect --- ERROR\n");
return;
}
}
void ManagedDatabase::ReindexDatabase() {
QuillErrCode ret_st;
MyString sql_str;
switch (dt) {
case T_PGSQL:
ret_st = DBObj->connectDB();
/* call the reindex routine */
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::ReindexDatabase: unable to connect to DB--- ERROR\n");
return;
}
sql_str.sprintf("select quill_reindexTables()");
ret_st = DBObj->execCommand(sql_str.Value());
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::ReindexDatabase --- ERROR [SQL] %s\n",
sql_str.Value());
}
ret_st = DBObj->disconnectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::disconnectDB: unable to disconnect --- ERROR\n");
return;
}
break;
default:
// can't have this case
dprintf(D_ALWAYS, "database type is %d, unexpected! exiting!\n", dt);
ASSERT(0);
break;
}
}
<commit_msg>param+atoi -> param_integer for QUILL_RUN_HISTORY_DURATION<commit_after>/***************************************************************
*
* Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
* University of Wisconsin-Madison, WI.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
***************************************************************/
#include "condor_common.h"
#include "ManagedDatabase.h"
#include "dbms_utils.h"
#include "condor_config.h"
#include "pgsqldatabase.h"
#include "condor_email.h"
ManagedDatabase::ManagedDatabase() {
char *tmp;
QuillErrCode ret_st;
if (param_boolean("QUILL_ENABLED", false) == false) {
EXCEPT("Quill++ is currently disabled. Please set QUILL_ENABLED to "
"TRUE if you want this functionality and read the manual "
"about this feature since it requires other attributes to be "
"set properly.");
}
//bail out if no SPOOL variable is defined since its used to
//figure out the location of the quillWriter password file
char *spool = param("SPOOL");
if(!spool) {
EXCEPT("No SPOOL variable found in config file\n");
}
/*
Here we try to read the database parameters in config
the db ip address format is <ipaddress:port>
*/
dt = getConfigDBType();
dbIpAddress = param("QUILL_DB_IP_ADDR");
dbName = param("QUILL_DB_NAME");
dbUser = param("QUILL_DB_USER");
dbConnStr = getDBConnStr(dbIpAddress,
dbName,
dbUser,
spool);
dprintf(D_ALWAYS, "Using Database Type = Postgres\n");
dprintf(D_ALWAYS, "Using Database IpAddress = %s\n",
dbIpAddress?dbIpAddress:"");
dprintf(D_ALWAYS, "Using Database Name = %s\n",
dbName?dbName:"");
dprintf(D_ALWAYS, "Using Database User = %s\n",
dbUser?dbUser:"");
if (spool) {
free(spool);
}
switch (dt) {
case T_PGSQL:
DBObj = new PGSQLDatabase(dbConnStr);
break;
default:
break;
}
/* default to a week of resource history info */
resourceHistoryDuration = param_integer("QUILL_RESOURCE_HISTORY_DURATION", 7);
/* default to a week of job run information */
runHistoryDuration = param_integer("QUILL_RUN_HISTORY_DURATION", 7);
tmp = param("QUILL_JOB_HISTORY_DURATION");
if (tmp) {
jobHistoryDuration= atoi(tmp);
free(tmp);
} else {
/* default to 10 years of job history */
jobHistoryDuration = 3650;
}
tmp = param("QUILL_DBSIZE_LIMIT");
if (tmp) {
dbSizeLimit= atoi(tmp);
free(tmp);
} else {
/* default to 20 GB */
dbSizeLimit = 20;
}
/* check if schema version is ok */
ret_st = DBObj->connectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "config: unable to connect to DB--- ERROR");
EXCEPT("config: unable to connect to DB\n");
}
/* the following will also throw an exception of the schema
version is not correct */
DBObj->assertSchemaVersion();
DBObj->disconnectDB();
}
ManagedDatabase::~ManagedDatabase() {
if (dbIpAddress) {
free(dbIpAddress);
dbIpAddress = NULL;
}
if (dbName) {
free(dbName);
dbName = NULL;
}
if (dbUser) {
free(dbUser);
dbUser = NULL;
}
if (dbConnStr) {
free(dbConnStr);
dbConnStr = NULL;
}
if (DBObj) {
delete DBObj;
}
}
void ManagedDatabase::PurgeDatabase() {
QuillErrCode ret_st;
int dbsize;
int num_result;
MyString sql_str;
ret_st = DBObj->connectDB();
/* call the puging routine */
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase: unable to connect to DB--- ERROR\n");
return;
}
switch (dt) {
case T_PGSQL:
sql_str.sprintf("select quill_purgeHistory(%d, %d, %d)",
resourceHistoryDuration,
runHistoryDuration,
jobHistoryDuration);
break;
default:
// can't have this case
dprintf(D_ALWAYS, "database type is %d, unexpected! exiting!\n", dt);
ASSERT(0);
break;
}
ret_st = DBObj->execCommand(sql_str.Value());
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase --- ERROR [SQL] %s\n",
sql_str.Value());
}
ret_st = DBObj->commitTransaction();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::PurgeDatabase --- ERROR [COMMIT] \n");
}
/* query the space usage and if it is above some threshold, send
a warning to the administrator
*/
sql_str.sprintf("SELECT dbsize FROM quillDBMonitor");
ret_st = DBObj->execQuery(sql_str.Value(), num_result);
if ((ret_st == QUILL_SUCCESS) &&
(num_result == 1)) {
dbsize = atoi(DBObj->getValue(0, 0));
/* if dbsize is bigger than 75% the dbSizeLimit, send a
warning to the administrator with information about
the situation and suggestion for looking at the table
sizes using the following sql statement and tune down
the *HistoryDuration parameters accordingly.
This is an oracle version of sql for examining the
table sizes in descending order, sql for other
databases can be similarly constructed:
SELECT NUM_ROWS*AVG_ROW_LEN, table_name
FROM USER_TABLES
ORDER BY NUM_ROWS*AVG_ROW_LEN DESC;
*/
if (dbsize/1024 > dbSizeLimit) {
FILE *email;
char msg_body[4000];
snprintf(msg_body, 4000, "Current database size (> %d MB) is "
"bigger than 75 percent of the limit (%d GB). Please "
"decrease the values of these parameters: "
"QUILL_RESOURCE_HISTORY_DURATION, "
"QUILL_RUN_HISTORY_DURATION, "
"QUILL_JOB_HISTORY_DURATION or QUILL_DBSIZE_LIMIT\n",
dbsize, dbSizeLimit);
/* notice that dbsize is stored in unit of MB, but
dbSizeLimit is stored in unit of GB */
dprintf(D_ALWAYS, "%s", msg_body);
email = email_admin_open(msg_body);
if (email) {
email_close ( email );
} else {
dprintf( D_ALWAYS, "ERROR: Can't send email to the Condor "
"Administrator\n" );
}
}
} else {
dprintf(D_ALWAYS, "Reading quillDBMonitor --- ERROR or returned # of rows is not exactly one [SQL] %s\n",
sql_str.Value());
}
DBObj->releaseQueryResult();
ret_st = DBObj->disconnectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::disconnectDB: unable to disconnect --- ERROR\n");
return;
}
}
void ManagedDatabase::ReindexDatabase() {
QuillErrCode ret_st;
MyString sql_str;
switch (dt) {
case T_PGSQL:
ret_st = DBObj->connectDB();
/* call the reindex routine */
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::ReindexDatabase: unable to connect to DB--- ERROR\n");
return;
}
sql_str.sprintf("select quill_reindexTables()");
ret_st = DBObj->execCommand(sql_str.Value());
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::ReindexDatabase --- ERROR [SQL] %s\n",
sql_str.Value());
}
ret_st = DBObj->disconnectDB();
if (ret_st == QUILL_FAILURE) {
dprintf(D_ALWAYS, "ManagedDatabase::disconnectDB: unable to disconnect --- ERROR\n");
return;
}
break;
default:
// can't have this case
dprintf(D_ALWAYS, "database type is %d, unexpected! exiting!\n", dt);
ASSERT(0);
break;
}
}
<|endoftext|> |
<commit_before>/**
* @file llchatentry.cpp
* @brief LLChatEntry implementation
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llchatentry.h"
static LLDefaultChildRegistry::Register<LLChatEntry> r("text_editor");
LLChatEntry::LLChatEntry::Params::Params()
: has_history("has_history", true),
is_expandable("is_expandable", false),
expand_lines_count("expand_lines_count", 1)
{}
LLChatEntry::LLChatEntry(const Params& p)
: LLTextEditor(p),
mTextExpandedSignal(NULL),
mHasHistory(p.has_history),
mIsExpandable(p.is_expandable),
mExpandLinesCount(p.expand_lines_count),
mPrevLinesCount(0)
{
// Initialize current history line iterator
mCurrentHistoryLine = mLineHistory.begin();
mAutoIndent = false;
}
LLChatEntry::~LLChatEntry()
{
delete mTextExpandedSignal;
}
void LLChatEntry::draw()
{
LLTextEditor::draw();
if(mIsExpandable)
{
expandText();
}
}
void LLChatEntry::onCommit()
{
updateHistory();
LLTextEditor::onCommit();
}
boost::signals2::connection LLChatEntry::setTextExpandedCallback(const commit_signal_t::slot_type& cb)
{
if (!mTextExpandedSignal)
{
mTextExpandedSignal = new commit_signal_t();
}
return mTextExpandedSignal->connect(cb);
}
void LLChatEntry::expandText()
{
int visible_lines_count = llabs(getVisibleLines(true).first - getVisibleLines(true).second);
bool can_expand = getLineCount() <= mExpandLinesCount;
// true if pasted text has more lines than expand height limit and expand limit is not reached yet
bool text_pasted = (getLineCount() > mExpandLinesCount) && (visible_lines_count < mExpandLinesCount);
if (mIsExpandable && (can_expand || text_pasted) && getLineCount() != mPrevLinesCount)
{
int lines_height = 0;
if (text_pasted)
{
// text is pasted and now mLineInfoList.size() > mExpandLineCounts and mLineInfoList is not empty,
// so lines_height is the sum of the last 'mExpandLinesCount' lines height
lines_height = (mLineInfoList.end() - mExpandLinesCount)->mRect.mTop - mLineInfoList.back().mRect.mBottom;
}
else
{
lines_height = mLineInfoList.begin()->mRect.mTop - mLineInfoList.back().mRect.mBottom;
}
int height = mVPad * 2 + lines_height;
LLRect doc_rect = getRect();
doc_rect.setOriginAndSize(doc_rect.mLeft, doc_rect.mBottom, doc_rect.getWidth(), height);
setShape(doc_rect);
mPrevLinesCount = getLineCount();
if (mTextExpandedSignal)
{
(*mTextExpandedSignal)(this, LLSD() );
}
}
}
// line history support
void LLChatEntry::updateHistory()
{
// On history enabled, remember committed line and
// reset current history line number.
// Be sure only to remember lines that are not empty and that are
// different from the last on the list.
if (mHasHistory && getLength())
{
// Add text to history, ignoring duplicates
if (mLineHistory.empty() || getText() != mLineHistory.back())
{
mLineHistory.push_back(getText());
}
mCurrentHistoryLine = mLineHistory.end();
}
}
BOOL LLChatEntry::handleSpecialKey(const KEY key, const MASK mask)
{
BOOL handled = FALSE;
LLTextEditor::handleSpecialKey(key, mask);
switch(key)
{
case KEY_RETURN:
if (MASK_NONE == mask)
{
needsReflow();
}
break;
case KEY_UP:
if (mHasHistory && MASK_CONTROL == mask)
{
if (!mLineHistory.empty() && mCurrentHistoryLine > mLineHistory.begin())
{
setText(*(--mCurrentHistoryLine));
endOfDoc();
}
else
{
LLUI::reportBadKeystroke();
}
handled = TRUE;
}
break;
case KEY_DOWN:
if (mHasHistory && MASK_CONTROL == mask)
{
if (!mLineHistory.empty() && ++mCurrentHistoryLine < mLineHistory.end())
{
setText(*mCurrentHistoryLine);
endOfDoc();
}
else if (!mLineHistory.empty() && mCurrentHistoryLine == mLineHistory.end())
{
std::string empty("");
setText(empty);
needsReflow();
endOfDoc();
}
else
{
LLUI::reportBadKeystroke();
}
handled = TRUE;
}
break;
default:
break;
}
return handled;
}
<commit_msg>Win build fix<commit_after>/**
* @file llchatentry.cpp
* @brief LLChatEntry implementation
*
* $LicenseInfo:firstyear=2001&license=viewerlgpl$
* Second Life Viewer Source Code
* Copyright (C) 2012, Linden Research, Inc.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License only.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* Linden Research, Inc., 945 Battery Street, San Francisco, CA 94111 USA
* $/LicenseInfo$
*/
#include "linden_common.h"
#include "llchatentry.h"
static LLDefaultChildRegistry::Register<LLChatEntry> r("text_editor");
LLChatEntry::Params::Params()
: has_history("has_history", true),
is_expandable("is_expandable", false),
expand_lines_count("expand_lines_count", 1)
{}
LLChatEntry::LLChatEntry(const Params& p)
: LLTextEditor(p),
mTextExpandedSignal(NULL),
mHasHistory(p.has_history),
mIsExpandable(p.is_expandable),
mExpandLinesCount(p.expand_lines_count),
mPrevLinesCount(0)
{
// Initialize current history line iterator
mCurrentHistoryLine = mLineHistory.begin();
mAutoIndent = false;
}
LLChatEntry::~LLChatEntry()
{
delete mTextExpandedSignal;
}
void LLChatEntry::draw()
{
LLTextEditor::draw();
if(mIsExpandable)
{
expandText();
}
}
void LLChatEntry::onCommit()
{
updateHistory();
LLTextEditor::onCommit();
}
boost::signals2::connection LLChatEntry::setTextExpandedCallback(const commit_signal_t::slot_type& cb)
{
if (!mTextExpandedSignal)
{
mTextExpandedSignal = new commit_signal_t();
}
return mTextExpandedSignal->connect(cb);
}
void LLChatEntry::expandText()
{
int visible_lines_count = llabs(getVisibleLines(true).first - getVisibleLines(true).second);
bool can_expand = getLineCount() <= mExpandLinesCount;
// true if pasted text has more lines than expand height limit and expand limit is not reached yet
bool text_pasted = (getLineCount() > mExpandLinesCount) && (visible_lines_count < mExpandLinesCount);
if (mIsExpandable && (can_expand || text_pasted) && getLineCount() != mPrevLinesCount)
{
int lines_height = 0;
if (text_pasted)
{
// text is pasted and now mLineInfoList.size() > mExpandLineCounts and mLineInfoList is not empty,
// so lines_height is the sum of the last 'mExpandLinesCount' lines height
lines_height = (mLineInfoList.end() - mExpandLinesCount)->mRect.mTop - mLineInfoList.back().mRect.mBottom;
}
else
{
lines_height = mLineInfoList.begin()->mRect.mTop - mLineInfoList.back().mRect.mBottom;
}
int height = mVPad * 2 + lines_height;
LLRect doc_rect = getRect();
doc_rect.setOriginAndSize(doc_rect.mLeft, doc_rect.mBottom, doc_rect.getWidth(), height);
setShape(doc_rect);
mPrevLinesCount = getLineCount();
if (mTextExpandedSignal)
{
(*mTextExpandedSignal)(this, LLSD() );
}
}
}
// line history support
void LLChatEntry::updateHistory()
{
// On history enabled, remember committed line and
// reset current history line number.
// Be sure only to remember lines that are not empty and that are
// different from the last on the list.
if (mHasHistory && getLength())
{
// Add text to history, ignoring duplicates
if (mLineHistory.empty() || getText() != mLineHistory.back())
{
mLineHistory.push_back(getText());
}
mCurrentHistoryLine = mLineHistory.end();
}
}
BOOL LLChatEntry::handleSpecialKey(const KEY key, const MASK mask)
{
BOOL handled = FALSE;
LLTextEditor::handleSpecialKey(key, mask);
switch(key)
{
case KEY_RETURN:
if (MASK_NONE == mask)
{
needsReflow();
}
break;
case KEY_UP:
if (mHasHistory && MASK_CONTROL == mask)
{
if (!mLineHistory.empty() && mCurrentHistoryLine > mLineHistory.begin())
{
setText(*(--mCurrentHistoryLine));
endOfDoc();
}
else
{
LLUI::reportBadKeystroke();
}
handled = TRUE;
}
break;
case KEY_DOWN:
if (mHasHistory && MASK_CONTROL == mask)
{
if (!mLineHistory.empty() && ++mCurrentHistoryLine < mLineHistory.end())
{
setText(*mCurrentHistoryLine);
endOfDoc();
}
else if (!mLineHistory.empty() && mCurrentHistoryLine == mLineHistory.end())
{
std::string empty("");
setText(empty);
needsReflow();
endOfDoc();
}
else
{
LLUI::reportBadKeystroke();
}
handled = TRUE;
}
break;
default:
break;
}
return handled;
}
<|endoftext|> |
<commit_before>/*
* Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
* Copyright (C) 2013 Rasmus Eskola <[email protected]>
* based on sample.cpp sample module code
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <dirent.h>
#include <vector>
#include <algorithm>
class CBacklogMod : public CModule {
public:
MODCONSTRUCTOR(CBacklogMod) {}
virtual bool OnLoad(const CString& sArgs, CString& sMessage);
virtual ~CBacklogMod();
virtual void OnModCommand(const CString& sCommand);
bool inChan(const CString& Chan);
private:
CString LogPath;
};
bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
LogPath = sArgs;
if(LogPath.empty()) {
LogPath = GetNV("LogPath");
if(LogPath.empty()) {
// TODO: guess logpath?
PutModule("LogPath is empty, set it with the LogPath command (help for more info)");
}
} else {
SetNV("LogPath", LogPath);
PutModule("LogPath set to: " + LogPath);
}
return true;
}
CBacklogMod::~CBacklogMod() {
}
void CBacklogMod::OnModCommand(const CString& sCommand) {
if (sCommand.Token(0).CaseCmp("help") == 0) {
// TODO: proper help text, look how AddHelpCommand() does it in other ZNC code
PutModule("Usage:");
PutModule("<window-name> [num-lines] (e.g. #foo 42)");
PutModule("");
PutModule("Commands:");
PutModule("Help (print this text)");
PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)");
return;
}
else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
if(sCommand.Token(1, true).empty()) {
PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)");
PutModule("Current LogPath is set to: " + GetNV("LogPath"));
return;
}
LogPath = sCommand.Token(1, true);
SetNV("LogPath", LogPath);
PutModule("LogPath set to: " + LogPath);
return;
}
// TODO: handle these differently depending on how the module was loaded
CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN");
CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc");
CString Channel = sCommand.Token(0);
int printedLines = 0;
int reqLines = sCommand.Token(1).ToInt();
if(reqLines <= 0) {
reqLines = 150;
}
reqLines = std::max(std::min(reqLines, 1000), 1);
CString Path = LogPath.substr(); // make copy
Path.Replace("$NETWORK", Network);
Path.Replace("$WINDOW", Channel);
Path.Replace("$USER", User);
CString DirPath = Path.substr(0, Path.find_last_of("/"));
CString FilePath;
std::vector<CString> FileList;
std::vector<CString> LinesToPrint;
// gather list of all log files for requested channel/window
DIR *dir;
struct dirent *ent;
if ((dir = opendir (DirPath.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
FilePath = DirPath + "/" + ent->d_name;
//PutModule("DEBUG: " + FilePath + " " + Path);
if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) {
FileList.push_back(FilePath);
}
}
closedir (dir);
} else {
PutModule("Could not list directory " + DirPath + ": " + strerror(errno));
return;
}
std::sort(FileList.begin(), FileList.end());
// loop through list of log files one by one starting from most recent...
for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) {
CFile LogFile(*it);
CString Line;
std::vector<CString> Lines;
if (LogFile.Open()) {
while (LogFile.ReadLine(Line)) {
// store lines from file into Lines
Lines.push_back(Line);
}
} else {
PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
continue;
}
LogFile.Close();
// loop through Lines in reverse order, push to LinesToPrint
for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) {
LinesToPrint.push_back(*itl);
printedLines++;
if(printedLines >= reqLines) {
break;
}
}
if(printedLines >= reqLines) {
break;
}
}
bool isInChan = CBacklogMod::inChan(Channel);
if(printedLines == 0) {
PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
return;
} else if (isInChan) {
m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Backlog playback...", GetClient());
} else {
PutModule("*** Backlog playback...");
}
// now actually print
for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) {
if(isInChan) {
CString Line = *it;
size_t FirstSpace = Line.find_first_of(' ');
size_t Len = Line.find_first_of(' ', FirstSpace + 1) - FirstSpace;
CString Nick = Line.substr(FirstSpace + 2, Len - 3);
m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstSpace) + Line.substr(FirstSpace + Len, Line.npos), GetClient());
} else {
PutModule(*it);
}
}
if (isInChan) {
m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Playback complete.", GetClient());
} else {
PutModule("*** Playback complete.");
}
}
bool CBacklogMod::inChan(const CString& Chan) {
const std::vector <CChan*>& vChans (m_pNetwork->GetChans());
for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) {
CChan *curChan = *it;
if(Chan.StrCmp(curChan->GetName()) == 0) {
return true;
}
}
return false;
}
template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
Info.AddType(CModInfo::NetworkModule);
Info.AddType(CModInfo::GlobalModule);
Info.SetWikiPage("backlog");
Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
Info.SetHasArgs(true);
}
NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<commit_msg>rename LogPath member variable to m_sLogPath<commit_after>/*
* Copyright (C) 2004-2013 ZNC, see the NOTICE file for details.
* Copyright (C) 2013 Rasmus Eskola <[email protected]>
* based on sample.cpp sample module code
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <znc/FileUtils.h>
#include <znc/Client.h>
#include <znc/Chan.h>
#include <znc/User.h>
#include <znc/IRCNetwork.h>
#include <znc/Modules.h>
#include <dirent.h>
#include <vector>
#include <algorithm>
class CBacklogMod : public CModule {
public:
MODCONSTRUCTOR(CBacklogMod) {}
virtual bool OnLoad(const CString& sArgs, CString& sMessage);
virtual ~CBacklogMod();
virtual void OnModCommand(const CString& sCommand);
bool inChan(const CString& Chan);
private:
CString m_sLogPath;
};
bool CBacklogMod::OnLoad(const CString& sArgs, CString& sMessage) {
m_sLogPath = sArgs;
if(m_sLogPath.empty()) {
m_sLogPath = GetNV("LogPath");
if(m_sLogPath.empty()) {
// TODO: guess logpath?
PutModule("LogPath is empty, set it with the LogPath command (help for more info)");
}
} else {
SetNV("LogPath", m_sLogPath);
PutModule("LogPath set to: " + m_sLogPath);
}
return true;
}
CBacklogMod::~CBacklogMod() {
}
void CBacklogMod::OnModCommand(const CString& sCommand) {
if (sCommand.Token(0).CaseCmp("help") == 0) {
// TODO: proper help text, look how AddHelpCommand() does it in other ZNC code
PutModule("Usage:");
PutModule("<window-name> [num-lines] (e.g. #foo 42)");
PutModule("");
PutModule("Commands:");
PutModule("Help (print this text)");
PutModule("LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date)");
return;
}
else if (sCommand.Token(0).CaseCmp("logpath") == 0) {
if(sCommand.Token(1, true).empty()) {
PutModule("Usage: LogPath <path> (use keywords $USER, $NETWORK, $WINDOW and an asterisk * for date:)");
PutModule("Current LogPath is set to: " + GetNV("LogPath"));
return;
}
m_sLogPath = sCommand.Token(1, true);
SetNV("LogPath", m_sLogPath);
PutModule("LogPath set to: " + m_sLogPath);
return;
}
// TODO: handle these differently depending on how the module was loaded
CString User = (m_pUser ? m_pUser->GetUserName() : "UNKNOWN");
CString Network = (m_pNetwork ? m_pNetwork->GetName() : "znc");
CString Channel = sCommand.Token(0);
int printedLines = 0;
int reqLines = sCommand.Token(1).ToInt();
if(reqLines <= 0) {
reqLines = 150;
}
reqLines = std::max(std::min(reqLines, 1000), 1);
CString Path = m_sLogPath.substr(); // make copy
Path.Replace("$NETWORK", Network);
Path.Replace("$WINDOW", Channel);
Path.Replace("$USER", User);
CString DirPath = Path.substr(0, Path.find_last_of("/"));
CString FilePath;
std::vector<CString> FileList;
std::vector<CString> LinesToPrint;
// gather list of all log files for requested channel/window
DIR *dir;
struct dirent *ent;
if ((dir = opendir (DirPath.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
FilePath = DirPath + "/" + ent->d_name;
//PutModule("DEBUG: " + FilePath + " " + Path);
if(FilePath.StrCmp(Path, Path.find_last_of("*")) == 0) {
FileList.push_back(FilePath);
}
}
closedir (dir);
} else {
PutModule("Could not list directory " + DirPath + ": " + strerror(errno));
return;
}
std::sort(FileList.begin(), FileList.end());
// loop through list of log files one by one starting from most recent...
for (std::vector<CString>::reverse_iterator it = FileList.rbegin(); it != FileList.rend(); ++it) {
CFile LogFile(*it);
CString Line;
std::vector<CString> Lines;
if (LogFile.Open()) {
while (LogFile.ReadLine(Line)) {
// store lines from file into Lines
Lines.push_back(Line);
}
} else {
PutModule("Could not open log file [" + sCommand + "]: " + strerror(errno));
continue;
}
LogFile.Close();
// loop through Lines in reverse order, push to LinesToPrint
for (std::vector<CString>::reverse_iterator itl = Lines.rbegin(); itl != Lines.rend(); ++itl) {
LinesToPrint.push_back(*itl);
printedLines++;
if(printedLines >= reqLines) {
break;
}
}
if(printedLines >= reqLines) {
break;
}
}
bool isInChan = CBacklogMod::inChan(Channel);
if(printedLines == 0) {
PutModule("No log files found for window " + Channel + " in " + DirPath + "/");
return;
} else if (isInChan) {
m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Backlog playback...", GetClient());
} else {
PutModule("*** Backlog playback...");
}
// now actually print
for (std::vector<CString>::reverse_iterator it = LinesToPrint.rbegin(); it != LinesToPrint.rend(); ++it) {
if(isInChan) {
CString Line = *it;
size_t FirstSpace = Line.find_first_of(' ');
size_t Len = Line.find_first_of(' ', FirstSpace + 1) - FirstSpace;
CString Nick = Line.substr(FirstSpace + 2, Len - 3);
m_pNetwork->PutUser(":" + Nick + "[email protected] PRIVMSG " + Channel + " :" + Line.substr(0, FirstSpace) + Line.substr(FirstSpace + Len, Line.npos), GetClient());
} else {
PutModule(*it);
}
}
if (isInChan) {
m_pNetwork->PutUser(":***[email protected] PRIVMSG " + Channel + " :" + "Playback complete.", GetClient());
} else {
PutModule("*** Playback complete.");
}
}
bool CBacklogMod::inChan(const CString& Chan) {
const std::vector <CChan*>& vChans (m_pNetwork->GetChans());
for (std::vector<CChan*>::const_iterator it = vChans.begin(); it != vChans.end(); ++it) {
CChan *curChan = *it;
if(Chan.StrCmp(curChan->GetName()) == 0) {
return true;
}
}
return false;
}
template<> void TModInfo<CBacklogMod>(CModInfo& Info) {
Info.AddType(CModInfo::NetworkModule);
Info.AddType(CModInfo::GlobalModule);
Info.SetWikiPage("backlog");
Info.SetArgsHelpText("Takes as optional argument (and if given, sets) the log path, use keywords: $USER, $NETWORK and $WINDOW");
Info.SetHasArgs(true);
}
NETWORKMODULEDEFS(CBacklogMod, "Module for getting the last X lines of a channels log.")
<|endoftext|> |
<commit_before>/*
This file is part of KDE Kontact.
Copyright (C) 2003 Sven Lüppken <[email protected]>
Copyright (C) 2003 Tobias König <[email protected]>
Copyright (C) 2003 Daniel Molkentin <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qframe.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtimer.h>
#include <dcopclient.h>
#include <kaction.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdcopservicestarter.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kservice.h>
#include <ktrader.h>
#include <kstandarddirs.h>
#include <qscrollview.h>
#include <kglobal.h>
#include <klocale.h>
#include <kcmultidialog.h>
#include <kparts/componentfactory.h>
#include <kparts/event.h>
#include <infoextension.h>
#include <sidebarextension.h>
#include "plugin.h"
#include "summary.h"
#include "summaryview_part.h"
#include "broadcaststatus.h"
using KPIM::BroadcastStatus;
namespace Kontact
{
class MainWindow;
}
SummaryViewPart::SummaryViewPart( Kontact::Core *core, const char*,
const KAboutData *aboutData,
QObject *parent, const char *name )
: KPIM::Part( parent, name ),
mCore( core ), mFrame( 0 ), mConfigAction( 0 )
{
setInstance( new KInstance( aboutData ) );
loadLayout();
initGUI( core );
connect( kapp, SIGNAL( kdisplayPaletteChanged() ), SLOT( slotAdjustPalette() ) );
slotAdjustPalette();
setDate( QDate::currentDate() );
connect( mCore, SIGNAL( dayChanged( const QDate& ) ),
SLOT( setDate( const QDate& ) ) );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "Summary" );
connect( this, SIGNAL( textChanged( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
mConfigAction = new KAction( i18n( "&Configure Summary View..." ),
"configure", 0, this,
SLOT( slotConfigure() ), actionCollection(),
"summaryview_configure" );
setXMLFile( "kontactsummary_part.rc" );
QTimer::singleShot( 0, this, SLOT( slotTextChanged() ) );
}
SummaryViewPart::~SummaryViewPart()
{
saveLayout();
}
bool SummaryViewPart::openFile()
{
kdDebug(5006) << "SummaryViewPart:openFile()" << endl;
return true;
}
void SummaryViewPart::partActivateEvent( KParts::PartActivateEvent *event )
{
// inform the plugins that the part has been activated so that they can
// update the displayed information
if ( event->activated() && ( event->part() == this ) ) {
QMap<QString, Kontact::Summary*>::Iterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it )
it.data()->updateSummary( false );
}
KParts::ReadOnlyPart::partActivateEvent( event );
}
void SummaryViewPart::updateWidgets()
{
mMainWidget->setUpdatesEnabled( false );
delete mFrame;
mSummaries.clear();
mFrame = new DropWidget( mMainWidget );
connect( mFrame, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
mMainLayout->insertWidget( 2, mFrame );
QStringList activeSummaries;
KConfig config( "kontact_summaryrc" );
if ( !config.hasKey( "ActiveSummaries" ) ) {
activeSummaries << "kontact_kmailplugin";
activeSummaries << "kontact_kaddressbookplugin";
activeSummaries << "kontact_korganizerplugin";
activeSummaries << "kontact_todoplugin";
activeSummaries << "kontact_newstickerplugin";
} else {
activeSummaries = config.readListEntry( "ActiveSummaries" );
}
// Collect all summary widgets with a summaryHeight > 0
QValueList<Kontact::Plugin*> plugins = mCore->pluginList();
QValueList<Kontact::Plugin*>::ConstIterator end = plugins.end();
QValueList<Kontact::Plugin*>::ConstIterator it = plugins.begin();
for ( ; it != end; ++it ) {
Kontact::Plugin *plugin = *it;
if ( activeSummaries.find( plugin->identifier() ) == activeSummaries.end() )
continue;
Kontact::Summary *summary = plugin->createSummaryWidget( mFrame );
if ( summary ) {
if ( summary->summaryHeight() > 0 ) {
mSummaries.insert( plugin->identifier(), summary );
connect( summary, SIGNAL( message( const QString& ) ),
BroadcastStatus::instance(), SLOT( setStatusMsg( const QString& ) ) );
connect( summary, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
if ( !mLeftColumnSummaries.contains( plugin->identifier() ) &&
!mRightColumnSummaries.contains( plugin->identifier() ) ) {
mLeftColumnSummaries.append( plugin->identifier() );
}
} else {
summary->hide();
}
}
}
// Add vertical line between the two rows of summary widgets.
QFrame *vline = new QFrame( mFrame );
vline->setFrameStyle( QFrame::VLine | QFrame::Plain );
QHBoxLayout *layout = new QHBoxLayout( mFrame );
mLeftColumn = new QVBoxLayout( layout, KDialog::spacingHint() );
layout->addWidget( vline );
mRightColumn = new QVBoxLayout( layout, KDialog::spacingHint() );
QStringList::Iterator strIt;
for ( strIt = mLeftColumnSummaries.begin(); strIt != mLeftColumnSummaries.end(); ++strIt ) {
if ( mSummaries.find( *strIt ) != mSummaries.end() )
mLeftColumn->addWidget( mSummaries[ *strIt ] );
}
for ( strIt = mRightColumnSummaries.begin(); strIt != mRightColumnSummaries.end(); ++strIt ) {
if ( mSummaries.find( *strIt ) != mSummaries.end() )
mRightColumn->addWidget( mSummaries[ *strIt ] );
}
mFrame->show();
mMainWidget->setUpdatesEnabled( true );
mMainWidget->update();
mLeftColumn->addStretch();
mRightColumn->addStretch();
}
void SummaryViewPart::summaryWidgetMoved( QWidget *target, QWidget *widget, int alignment )
{
if ( target == widget )
return;
if ( target == mFrame ) {
if ( mLeftColumn->findWidget( widget ) == -1 && mRightColumn->findWidget( widget ) == -1 )
return;
} else {
if ( mLeftColumn->findWidget( target ) == -1 && mRightColumn->findWidget( target ) == -1 ||
mLeftColumn->findWidget( widget ) == -1 && mRightColumn->findWidget( widget ) == -1 )
return;
}
if ( mLeftColumn->findWidget( widget ) != -1 ) {
mLeftColumn->remove( widget );
mLeftColumnSummaries.remove( widgetName( widget ) );
} else if ( mRightColumn->findWidget( widget ) != -1 ) {
mRightColumn->remove( widget );
mRightColumnSummaries.remove( widgetName( widget ) );
}
if ( target == mFrame ) {
int pos = 0;
if ( alignment & Qt::AlignTop )
pos = 0;
if ( alignment & Qt::AlignLeft ) {
if ( alignment & Qt::AlignBottom )
pos = mLeftColumnSummaries.count();
mLeftColumn->insertWidget( pos, widget );
mLeftColumnSummaries.insert( mLeftColumnSummaries.at( pos ), widgetName( widget ) );
} else {
if ( alignment & Qt::AlignBottom )
pos = mRightColumnSummaries.count();
mRightColumn->insertWidget( pos, widget );
mRightColumnSummaries.insert( mRightColumnSummaries.at( pos ), widgetName( widget ) );
}
return;
}
int targetPos = mLeftColumn->findWidget( target );
if ( targetPos != -1 ) {
if ( alignment == Qt::AlignBottom )
targetPos++;
mLeftColumn->insertWidget( targetPos, widget );
mLeftColumnSummaries.insert( mLeftColumnSummaries.at( targetPos ), widgetName( widget ) );
} else {
targetPos = mRightColumn->findWidget( target );
if ( alignment == Qt::AlignBottom )
targetPos++;
mRightColumn->insertWidget( targetPos, widget );
mRightColumnSummaries.insert( mRightColumnSummaries.at( targetPos ), widgetName( widget ) );
}
}
void SummaryViewPart::slotTextChanged()
{
emit textChanged( i18n( "What's next?" ) );
}
void SummaryViewPart::slotAdjustPalette()
{
mMainWidget->setPaletteBackgroundColor( kapp->palette().active().base() );
}
void SummaryViewPart::setDate( const QDate& newDate )
{
QString date( "<b>%1<b>" );
date = date.arg( KGlobal::locale()->formatDate( newDate ) );
mDateLabel->setText( date );
}
void SummaryViewPart::slotConfigure()
{
KCMultiDialog dlg( mMainWidget, "ConfigDialog", true );
QStringList modules = configModules();
modules.prepend( "kcmkontactsummary.desktop" );
connect( &dlg, SIGNAL( configCommitted() ),
this, SLOT( updateWidgets() ) );
QStringList::ConstIterator strIt;
for ( strIt = modules.begin(); strIt != modules.end(); ++strIt )
dlg.addModule( *strIt );
dlg.exec();
}
QStringList SummaryViewPart::configModules() const
{
QStringList modules;
QMap<QString, Kontact::Summary*>::ConstIterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it ) {
QStringList cm = it.data()->configModules();
QStringList::ConstIterator strIt;
for ( strIt = cm.begin(); strIt != cm.end(); ++strIt )
if ( !(*strIt).isEmpty() && !modules.contains( *strIt ) )
modules.append( *strIt );
}
return modules;
}
void SummaryViewPart::initGUI( Kontact::Core *core )
{
QScrollView *sv = new QScrollView( core );
sv->setResizePolicy( QScrollView::AutoOneFit );
sv->setFrameStyle( QFrame::NoFrame | QFrame::Plain );
mMainWidget = new QFrame( sv->viewport() );
sv->addChild( mMainWidget );
mMainWidget->setFrameStyle( QFrame::Panel | QFrame::Sunken );
sv->setFocusPolicy( QWidget::StrongFocus );
setWidget( sv );
mMainLayout = new QVBoxLayout( mMainWidget,KDialog::marginHint(),
KDialog::spacingHint() );
mDateLabel = new QLabel( mMainWidget );
mDateLabel->setAlignment( AlignRight );
mMainLayout->insertWidget( 0, mDateLabel );
QFrame *hline = new QFrame( mMainWidget );
hline->setFrameStyle( QFrame::HLine | QFrame::Plain );
mMainLayout->insertWidget( 1, hline );
mFrame = new DropWidget( mMainWidget );
mMainLayout->insertWidget( 2, mFrame );
connect( mFrame, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
updateWidgets();
}
void SummaryViewPart::loadLayout()
{
KConfig config( "kontact_summaryrc" );
if ( !config.hasKey( "LeftColumnSummaries" ) ) {
mLeftColumnSummaries << "kontact_korganizerplugin";
mLeftColumnSummaries << "kontact_todoplugin";
mLeftColumnSummaries << "kontact_kaddressbookplugin";
} else {
mLeftColumnSummaries = config.readListEntry( "LeftColumnSummaries" );
}
if ( !config.hasKey( "RightColumnSummaries" ) ) {
mRightColumnSummaries << "kontact_newstickerplugin";
} else {
mRightColumnSummaries = config.readListEntry( "RightColumnSummaries" );
}
}
void SummaryViewPart::saveLayout()
{
KConfig config( "kontact_summaryrc" );
config.writeEntry( "LeftColumnSummaries", mLeftColumnSummaries );
config.writeEntry( "RightColumnSummaries", mRightColumnSummaries );
config.sync();
}
QString SummaryViewPart::widgetName( QWidget *widget ) const
{
QMap<QString, Kontact::Summary*>::ConstIterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it ) {
if ( it.data() == widget )
return it.key();
}
return QString::null;
}
#include "summaryview_part.moc"
<commit_msg>Kill the Horisontal scrollbar in the summaryview, since we made the parts wrap instead, it increases usability they say.<commit_after>/*
This file is part of KDE Kontact.
Copyright (C) 2003 Sven Lüppken <[email protected]>
Copyright (C) 2003 Tobias König <[email protected]>
Copyright (C) 2003 Daniel Molkentin <[email protected]>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA.
*/
#include <qframe.h>
#include <qlabel.h>
#include <qlayout.h>
#include <qtimer.h>
#include <dcopclient.h>
#include <kaction.h>
#include <kapplication.h>
#include <kconfig.h>
#include <kdcopservicestarter.h>
#include <kdebug.h>
#include <kdialog.h>
#include <klocale.h>
#include <kmessagebox.h>
#include <kservice.h>
#include <ktrader.h>
#include <kstandarddirs.h>
#include <qscrollview.h>
#include <kglobal.h>
#include <klocale.h>
#include <kcmultidialog.h>
#include <kparts/componentfactory.h>
#include <kparts/event.h>
#include <infoextension.h>
#include <sidebarextension.h>
#include "plugin.h"
#include "summary.h"
#include "summaryview_part.h"
#include "broadcaststatus.h"
using KPIM::BroadcastStatus;
namespace Kontact
{
class MainWindow;
}
SummaryViewPart::SummaryViewPart( Kontact::Core *core, const char*,
const KAboutData *aboutData,
QObject *parent, const char *name )
: KPIM::Part( parent, name ),
mCore( core ), mFrame( 0 ), mConfigAction( 0 )
{
setInstance( new KInstance( aboutData ) );
loadLayout();
initGUI( core );
connect( kapp, SIGNAL( kdisplayPaletteChanged() ), SLOT( slotAdjustPalette() ) );
slotAdjustPalette();
setDate( QDate::currentDate() );
connect( mCore, SIGNAL( dayChanged( const QDate& ) ),
SLOT( setDate( const QDate& ) ) );
KParts::InfoExtension *info = new KParts::InfoExtension( this, "Summary" );
connect( this, SIGNAL( textChanged( const QString& ) ),
info, SIGNAL( textChanged( const QString& ) ) );
mConfigAction = new KAction( i18n( "&Configure Summary View..." ),
"configure", 0, this,
SLOT( slotConfigure() ), actionCollection(),
"summaryview_configure" );
setXMLFile( "kontactsummary_part.rc" );
QTimer::singleShot( 0, this, SLOT( slotTextChanged() ) );
}
SummaryViewPart::~SummaryViewPart()
{
saveLayout();
}
bool SummaryViewPart::openFile()
{
kdDebug(5006) << "SummaryViewPart:openFile()" << endl;
return true;
}
void SummaryViewPart::partActivateEvent( KParts::PartActivateEvent *event )
{
// inform the plugins that the part has been activated so that they can
// update the displayed information
if ( event->activated() && ( event->part() == this ) ) {
QMap<QString, Kontact::Summary*>::Iterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it )
it.data()->updateSummary( false );
}
KParts::ReadOnlyPart::partActivateEvent( event );
}
void SummaryViewPart::updateWidgets()
{
mMainWidget->setUpdatesEnabled( false );
delete mFrame;
mSummaries.clear();
mFrame = new DropWidget( mMainWidget );
connect( mFrame, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
mMainLayout->insertWidget( 2, mFrame );
QStringList activeSummaries;
KConfig config( "kontact_summaryrc" );
if ( !config.hasKey( "ActiveSummaries" ) ) {
activeSummaries << "kontact_kmailplugin";
activeSummaries << "kontact_kaddressbookplugin";
activeSummaries << "kontact_korganizerplugin";
activeSummaries << "kontact_todoplugin";
activeSummaries << "kontact_newstickerplugin";
} else {
activeSummaries = config.readListEntry( "ActiveSummaries" );
}
// Collect all summary widgets with a summaryHeight > 0
QValueList<Kontact::Plugin*> plugins = mCore->pluginList();
QValueList<Kontact::Plugin*>::ConstIterator end = plugins.end();
QValueList<Kontact::Plugin*>::ConstIterator it = plugins.begin();
for ( ; it != end; ++it ) {
Kontact::Plugin *plugin = *it;
if ( activeSummaries.find( plugin->identifier() ) == activeSummaries.end() )
continue;
Kontact::Summary *summary = plugin->createSummaryWidget( mFrame );
if ( summary ) {
if ( summary->summaryHeight() > 0 ) {
mSummaries.insert( plugin->identifier(), summary );
connect( summary, SIGNAL( message( const QString& ) ),
BroadcastStatus::instance(), SLOT( setStatusMsg( const QString& ) ) );
connect( summary, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
if ( !mLeftColumnSummaries.contains( plugin->identifier() ) &&
!mRightColumnSummaries.contains( plugin->identifier() ) ) {
mLeftColumnSummaries.append( plugin->identifier() );
}
} else {
summary->hide();
}
}
}
// Add vertical line between the two rows of summary widgets.
QFrame *vline = new QFrame( mFrame );
vline->setFrameStyle( QFrame::VLine | QFrame::Plain );
QHBoxLayout *layout = new QHBoxLayout( mFrame );
mLeftColumn = new QVBoxLayout( layout, KDialog::spacingHint() );
layout->addWidget( vline );
mRightColumn = new QVBoxLayout( layout, KDialog::spacingHint() );
QStringList::Iterator strIt;
for ( strIt = mLeftColumnSummaries.begin(); strIt != mLeftColumnSummaries.end(); ++strIt ) {
if ( mSummaries.find( *strIt ) != mSummaries.end() )
mLeftColumn->addWidget( mSummaries[ *strIt ] );
}
for ( strIt = mRightColumnSummaries.begin(); strIt != mRightColumnSummaries.end(); ++strIt ) {
if ( mSummaries.find( *strIt ) != mSummaries.end() )
mRightColumn->addWidget( mSummaries[ *strIt ] );
}
mFrame->show();
mMainWidget->setUpdatesEnabled( true );
mMainWidget->update();
mLeftColumn->addStretch();
mRightColumn->addStretch();
}
void SummaryViewPart::summaryWidgetMoved( QWidget *target, QWidget *widget, int alignment )
{
if ( target == widget )
return;
if ( target == mFrame ) {
if ( mLeftColumn->findWidget( widget ) == -1 && mRightColumn->findWidget( widget ) == -1 )
return;
} else {
if ( mLeftColumn->findWidget( target ) == -1 && mRightColumn->findWidget( target ) == -1 ||
mLeftColumn->findWidget( widget ) == -1 && mRightColumn->findWidget( widget ) == -1 )
return;
}
if ( mLeftColumn->findWidget( widget ) != -1 ) {
mLeftColumn->remove( widget );
mLeftColumnSummaries.remove( widgetName( widget ) );
} else if ( mRightColumn->findWidget( widget ) != -1 ) {
mRightColumn->remove( widget );
mRightColumnSummaries.remove( widgetName( widget ) );
}
if ( target == mFrame ) {
int pos = 0;
if ( alignment & Qt::AlignTop )
pos = 0;
if ( alignment & Qt::AlignLeft ) {
if ( alignment & Qt::AlignBottom )
pos = mLeftColumnSummaries.count();
mLeftColumn->insertWidget( pos, widget );
mLeftColumnSummaries.insert( mLeftColumnSummaries.at( pos ), widgetName( widget ) );
} else {
if ( alignment & Qt::AlignBottom )
pos = mRightColumnSummaries.count();
mRightColumn->insertWidget( pos, widget );
mRightColumnSummaries.insert( mRightColumnSummaries.at( pos ), widgetName( widget ) );
}
return;
}
int targetPos = mLeftColumn->findWidget( target );
if ( targetPos != -1 ) {
if ( alignment == Qt::AlignBottom )
targetPos++;
mLeftColumn->insertWidget( targetPos, widget );
mLeftColumnSummaries.insert( mLeftColumnSummaries.at( targetPos ), widgetName( widget ) );
} else {
targetPos = mRightColumn->findWidget( target );
if ( alignment == Qt::AlignBottom )
targetPos++;
mRightColumn->insertWidget( targetPos, widget );
mRightColumnSummaries.insert( mRightColumnSummaries.at( targetPos ), widgetName( widget ) );
}
}
void SummaryViewPart::slotTextChanged()
{
emit textChanged( i18n( "What's next?" ) );
}
void SummaryViewPart::slotAdjustPalette()
{
mMainWidget->setPaletteBackgroundColor( kapp->palette().active().base() );
}
void SummaryViewPart::setDate( const QDate& newDate )
{
QString date( "<b>%1<b>" );
date = date.arg( KGlobal::locale()->formatDate( newDate ) );
mDateLabel->setText( date );
}
void SummaryViewPart::slotConfigure()
{
KCMultiDialog dlg( mMainWidget, "ConfigDialog", true );
QStringList modules = configModules();
modules.prepend( "kcmkontactsummary.desktop" );
connect( &dlg, SIGNAL( configCommitted() ),
this, SLOT( updateWidgets() ) );
QStringList::ConstIterator strIt;
for ( strIt = modules.begin(); strIt != modules.end(); ++strIt )
dlg.addModule( *strIt );
dlg.exec();
}
QStringList SummaryViewPart::configModules() const
{
QStringList modules;
QMap<QString, Kontact::Summary*>::ConstIterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it ) {
QStringList cm = it.data()->configModules();
QStringList::ConstIterator strIt;
for ( strIt = cm.begin(); strIt != cm.end(); ++strIt )
if ( !(*strIt).isEmpty() && !modules.contains( *strIt ) )
modules.append( *strIt );
}
return modules;
}
void SummaryViewPart::initGUI( Kontact::Core *core )
{
QScrollView *sv = new QScrollView( core );
sv->setResizePolicy( QScrollView::AutoOneFit );
sv->setFrameStyle( QFrame::NoFrame | QFrame::Plain );
sv->setHScrollBarMode( QScrollView::AlwaysOff );
mMainWidget = new QFrame( sv->viewport() );
sv->addChild( mMainWidget );
mMainWidget->setFrameStyle( QFrame::Panel | QFrame::Sunken );
sv->setFocusPolicy( QWidget::StrongFocus );
setWidget( sv );
mMainLayout = new QVBoxLayout( mMainWidget,KDialog::marginHint(),
KDialog::spacingHint() );
mDateLabel = new QLabel( mMainWidget );
mDateLabel->setAlignment( AlignRight );
mMainLayout->insertWidget( 0, mDateLabel );
QFrame *hline = new QFrame( mMainWidget );
hline->setFrameStyle( QFrame::HLine | QFrame::Plain );
mMainLayout->insertWidget( 1, hline );
mFrame = new DropWidget( mMainWidget );
mMainLayout->insertWidget( 2, mFrame );
connect( mFrame, SIGNAL( summaryWidgetDropped( QWidget*, QWidget*, int ) ),
this, SLOT( summaryWidgetMoved( QWidget*, QWidget*, int ) ) );
updateWidgets();
}
void SummaryViewPart::loadLayout()
{
KConfig config( "kontact_summaryrc" );
if ( !config.hasKey( "LeftColumnSummaries" ) ) {
mLeftColumnSummaries << "kontact_korganizerplugin";
mLeftColumnSummaries << "kontact_todoplugin";
mLeftColumnSummaries << "kontact_kaddressbookplugin";
} else {
mLeftColumnSummaries = config.readListEntry( "LeftColumnSummaries" );
}
if ( !config.hasKey( "RightColumnSummaries" ) ) {
mRightColumnSummaries << "kontact_newstickerplugin";
} else {
mRightColumnSummaries = config.readListEntry( "RightColumnSummaries" );
}
}
void SummaryViewPart::saveLayout()
{
KConfig config( "kontact_summaryrc" );
config.writeEntry( "LeftColumnSummaries", mLeftColumnSummaries );
config.writeEntry( "RightColumnSummaries", mRightColumnSummaries );
config.sync();
}
QString SummaryViewPart::widgetName( QWidget *widget ) const
{
QMap<QString, Kontact::Summary*>::ConstIterator it;
for ( it = mSummaries.begin(); it != mSummaries.end(); ++it ) {
if ( it.data() == widget )
return it.key();
}
return QString::null;
}
#include "summaryview_part.moc"
<|endoftext|> |
<commit_before>
/* Include the SDL main definition header */
#include "SDL_main.h"
#ifdef main
#undef main
#endif
#ifdef QWS
#include <qpe/qpeapplication.h>
#endif
extern int SDL_main(int argc, char *argv[]);
int main(int argc, char *argv[])
{
#ifdef QWS
// This initializes the Qtopia application. It needs to be done here
// because it parses command line options.
QPEApplication app(argc, argv);
QWidget dummy;
app.showMainWidget(&dummy);
#endif
return(SDL_main(argc, argv));
}
<commit_msg>*** empty log message ***<commit_after>
/* Include the SDL main definition header */
#include "SDL_main.h"
#ifdef main
#undef main
#endif
#ifdef QWS
#include <qpe/qpeapplication.h>
#endif
extern int SDL_main(int argc, char *argv[]);
int main(int argc, char *argv[])
{
#ifdef QWS
// This initializes the Qtopia application. It needs to be done here
// because it parses command line options.
QPEApplication app(argc, argv);
QWidget dummy;
app.showMainWidget(&dummy);
#endif
// Exit here because if return is used, the application
// doesn't seem to quit correctly.
exit(SDL_main(argc, argv));
}
<|endoftext|> |
<commit_before>// The MIT License (MIT)
// Copyright (c) 2012-2013 Danny Y., Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef GEARS_MATH_UINTX_UINTX_HPP
#define GEARS_MATH_UINTX_UINTX_HPP
#include <cstddef>
#include <limits>
#include <vector>
#include <string>
#include "../../meta/alias.hpp"
namespace gears {
namespace uintx_detail {
constexpr size_t pow(size_t base, size_t exponent) {
return exponent == 0 ? 1 : (base * pow(base, exponent - 1));
}
template<typename Cont>
inline void reverse(Cont& c) {
auto first = std::begin(c);
auto last = std::end(c);
if(first == last)
return;
--last;
while(first < last) {
using std::swap;
swap(*first, *last);
++first;
--last;
}
}
} // uintx_detail
template<size_t Bits = -1, typename Digit = unsigned int, typename Digits = unsigned long long>
struct uintx {
private:
using signed_type = Type<std::make_signed<Digits>>;
static constexpr size_t digit_bits = sizeof(Digits) * 8;
static constexpr size_t digit_count = Bits == size_t(-1) ? -1 : (Bits / digit_bits);
static_assert(digit_count, "Invalid bits parameter. Note: Use -1 for \"infinite\" precision");
std::vector<Digits> digits;
struct add {
Digits operator()(Digits a, Digits b) {
return a + b;
}
};
struct multiply {
Digits k;
multiply() = default;
multiply(Digits n): k(n) {}
Digits operator()(Digits a) {
return a * k;
}
};
struct carry {
Digits& c;
carry(Digits& a): c(a) {}
Digits operator()(Digits n) {
n += c;
c = n / base;
n %= base;
return n;
}
};
template<class Base>
struct operator_carry : public Base, public carry {
operator_carry(Digits& c): carry(c) {}
Digits operator()(Digits a) {
return carry::operator()(Base::operator()(a));
}
Digits operator()(Digits a, Digits b) {
return carry::operator()(Base::operator()(a, b));
}
};
struct borrow {
signed_type& b;
borrow(signed_type& b): b(b) {}
signed_type operator()(signed_type n) {
n -= b;
b = 0;
while(n < 0) {
n += base;
++b;
}
return n;
}
};
struct sub_borrow {
signed_type& borrow;
sub_borrow(signed_type& b): borrow(b) {}
Digits operator()(signed_type a, signed_type b) {
signed_type n = b - a - borrow;
borrow = 0;
while(n < 0) {
n += base;
++borrow;
}
return n;
}
};
void normalize() {
while(digits.size() > 1) {
if(digits.back() == 0)
digits.pop_back();
else
break;
}
}
void add_zeroes(Digits n) {
digits.resize(digits.size() + n);
digits.insert(digits.begin(), n, 0);
}
void check_bits() {
if(digit_count == Bits)
return;
if(digits.capacity() >= digit_count)
digits.resize(digit_count);
}
void multiply_helper(uintx& x, Digits digit) {
Digits c = 0;
operator_carry<multiply> mulwc(c);
mulwc.k = digit;
detail::map(x.digits.begin(), x.digits.end(), x.digits.begin(), mulwc);
while(c) {
x.digits.push_back(c % base);
c /= base;
}
x.normalize();
x.check_bits();
}
public:
static constexpr size_t digits10 = std::numeric_limits<Digit>::digits10;
static constexpr size_t base = detail::pow(10, digits10);
uintx(): digits(1) {}
template<typename Integer, EnableIf<std::is_integral<Integer>>...>
uintx(Integer value) {
value = abs(value);
do {
digits.push_back(value % base);
value /= base;
}
while(value > 0);
}
uintx(const std::string& s) {
size_t count = digits10 - (s.size() % digits10);
std::string str(count, '0');
str += s;
digits.reserve(str.size() / digits10 + 1);
auto size = str.size();
size_t position = 0;
while(position != size) {
digits.push_back(std::stoull(str.substr(position, digits10)));
position += digits10;
}
uintx_detail::reverse(digits);
check_bits();
}
uintx& operator+=(const uintx& other) {
if(digits.size() < other.digits.size()) {
digits.resize(other.digits.size());
}
Digits c = 0;
operator_carry<add> addwc(c);
using uintx_detail::map;
auto it = map(other.digits.begin(), other.digits.end(), digits.begin(), digits.begin(), addwc);
map(it, digits.end(), it, carry(c));
if(c)
digits.push_back(c);
normalize();
check_bits();
return *this;
}
uintx& operator-=(const uintx& other) {
signed_type b = 0;
using uintx_detail::map;
auto it = map(other.digits.begin(), other.digits.end(), digits.begin(), digits.begin(), sub_borrow(b));
map(it, digits.end(), it, borrow(b));
normalize();
check_bits();
return *this;
}
uintx& operator*=(const uintx& other) {
const uintx* first = this;
const uintx* second = &other;
auto first_size = first->digits.size();
auto second_size = second->digits.size();
if(first_size < second_size) {
using std::swap;
swap(first, second);
swap(first_size, second_size);
}
std::vector<uintx> ints(second_size);
for(unsigned i = 0; i < second_size; ++i) {
ints[i].digits = first->digits;
multiply_helper(ints[i], second->digits[i]);
}
*this = ints.front();
digits.resize(first_size + second_size);
for(unsigned i = 1; i < second_size; ++i) {
ints[i].add_zeroes(i);
*this += ints[i];
}
normalize();
check_bits();
return *this;
}
uintx operator+(const uintx& other) const {
uintx result(*this);
return (result += other);
}
uintx operator-(const uintx& other) const {
uintx result(*this);
return (result -= other);
}
uintx operator*(const uintx& other) const {
uintx result(*this);
return (result *= other);
}
};
} // gears
#endif // GEARS_MATH_UINTX_UINTX_HPP<commit_msg>Add comparison operators to uintx (Issue #3)<commit_after>// The MIT License (MIT)
// Copyright (c) 2012-2013 Danny Y., Rapptz
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef GEARS_MATH_UINTX_UINTX_HPP
#define GEARS_MATH_UINTX_UINTX_HPP
#include <cstddef>
#include <limits>
#include <vector>
#include <string>
#include "../../meta/alias.hpp"
namespace gears {
namespace uintx_detail {
constexpr size_t pow(size_t base, size_t exponent) {
return exponent == 0 ? 1 : (base * pow(base, exponent - 1));
}
template<typename Cont>
inline void reverse(Cont& c) {
auto first = std::begin(c);
auto last = std::end(c);
if(first == last)
return;
--last;
while(first < last) {
using std::swap;
swap(*first, *last);
++first;
--last;
}
}
} // uintx_detail
template<size_t Bits = -1, typename Digit = unsigned int, typename Digits = unsigned long long>
struct uintx {
private:
using signed_type = Type<std::make_signed<Digits>>;
static constexpr size_t digit_bits = sizeof(Digits) * 8;
static constexpr size_t digit_count = Bits == size_t(-1) ? -1 : (Bits / digit_bits);
static_assert(digit_count, "Invalid bits parameter. Note: Use -1 for \"infinite\" precision");
std::vector<Digits> digits;
struct add {
Digits operator()(Digits a, Digits b) {
return a + b;
}
};
struct multiply {
Digits k;
multiply() = default;
multiply(Digits n): k(n) {}
Digits operator()(Digits a) {
return a * k;
}
};
struct carry {
Digits& c;
carry(Digits& a): c(a) {}
Digits operator()(Digits n) {
n += c;
c = n / base;
n %= base;
return n;
}
};
template<class Base>
struct operator_carry : public Base, public carry {
operator_carry(Digits& c): carry(c) {}
Digits operator()(Digits a) {
return carry::operator()(Base::operator()(a));
}
Digits operator()(Digits a, Digits b) {
return carry::operator()(Base::operator()(a, b));
}
};
struct borrow {
signed_type& b;
borrow(signed_type& b): b(b) {}
signed_type operator()(signed_type n) {
n -= b;
b = 0;
while(n < 0) {
n += base;
++b;
}
return n;
}
};
struct sub_borrow {
signed_type& borrow;
sub_borrow(signed_type& b): borrow(b) {}
Digits operator()(signed_type a, signed_type b) {
signed_type n = b - a - borrow;
borrow = 0;
while(n < 0) {
n += base;
++borrow;
}
return n;
}
};
void normalize() {
while(digits.size() > 1) {
if(digits.back() == 0)
digits.pop_back();
else
break;
}
}
void add_zeroes(Digits n) {
digits.resize(digits.size() + n);
digits.insert(digits.begin(), n, 0);
}
void check_bits() {
if(digit_count == Bits)
return;
if(digits.capacity() >= digit_count)
digits.resize(digit_count);
}
void multiply_helper(uintx& x, Digits digit) {
Digits c = 0;
operator_carry<multiply> mulwc(c);
mulwc.k = digit;
detail::map(x.digits.begin(), x.digits.end(), x.digits.begin(), mulwc);
while(c) {
x.digits.push_back(c % base);
c /= base;
}
x.normalize();
x.check_bits();
}
public:
static constexpr size_t digits10 = std::numeric_limits<Digit>::digits10;
static constexpr size_t base = detail::pow(10, digits10);
uintx(): digits(1) {}
template<typename Integer, EnableIf<std::is_integral<Integer>>...>
uintx(Integer value) {
value = abs(value);
do {
digits.push_back(value % base);
value /= base;
}
while(value > 0);
}
uintx(const std::string& s) {
size_t count = digits10 - (s.size() % digits10);
std::string str(count, '0');
str += s;
digits.reserve(str.size() / digits10 + 1);
auto size = str.size();
size_t position = 0;
while(position != size) {
digits.push_back(std::stoull(str.substr(position, digits10)));
position += digits10;
}
uintx_detail::reverse(digits);
check_bits();
}
uintx& operator+=(const uintx& other) {
if(digits.size() < other.digits.size()) {
digits.resize(other.digits.size());
}
Digits c = 0;
operator_carry<add> addwc(c);
using uintx_detail::map;
auto it = map(other.digits.begin(), other.digits.end(), digits.begin(), digits.begin(), addwc);
map(it, digits.end(), it, carry(c));
if(c)
digits.push_back(c);
normalize();
check_bits();
return *this;
}
uintx& operator-=(const uintx& other) {
signed_type b = 0;
using uintx_detail::map;
auto it = map(other.digits.begin(), other.digits.end(), digits.begin(), digits.begin(), sub_borrow(b));
map(it, digits.end(), it, borrow(b));
normalize();
check_bits();
return *this;
}
uintx& operator*=(const uintx& other) {
const uintx* first = this;
const uintx* second = &other;
auto first_size = first->digits.size();
auto second_size = second->digits.size();
if(first_size < second_size) {
using std::swap;
swap(first, second);
swap(first_size, second_size);
}
std::vector<uintx> ints(second_size);
for(unsigned i = 0; i < second_size; ++i) {
ints[i].digits = first->digits;
multiply_helper(ints[i], second->digits[i]);
}
*this = ints.front();
digits.resize(first_size + second_size);
for(unsigned i = 1; i < second_size; ++i) {
ints[i].add_zeroes(i);
*this += ints[i];
}
normalize();
check_bits();
return *this;
}
uintx operator+(const uintx& other) const {
uintx result(*this);
return (result += other);
}
uintx operator-(const uintx& other) const {
uintx result(*this);
return (result -= other);
}
uintx operator*(const uintx& other) const {
uintx result(*this);
return (result *= other);
}
bool operator==(const uintx& other) const {
return digits == other.digits;
}
bool operator!=(const uintx& other) const {
return digits != other.digits;
}
bool operator<(const uintx& other) const {
if(digits.size() < other.digits.size())
return true;
if(other.digits.size() < digits.size())
return false;
for(unsigned i = digits.size() - 1; i > 0; --i) {
if(digits[i] < other.digits[i])
return true;
if(other.digits[i] < digits[i])
return false;
}
return true;
}
bool operator>(const uintx& other) const {
return !(*this < other);
}
bool operator<=(const uintx& other) const {
return !(other < *this);
}
bool operator>=(const uintx& other) const {
return !(*this < other);
}
};
} // gears
#endif // GEARS_MATH_UINTX_UINTX_HPP<|endoftext|> |
<commit_before>/*
*****************************************************************************
* ___ _ _ _ _
* / _ \ __ _| |_| |__(_) |_ ___
* | (_) / _` | / / '_ \ | _(_-<
* \___/\__,_|_\_\_.__/_|\__/__/
* Copyright (c) 2013
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
/**
* @author R. Picard
* @date 2013/03/04
*
*****************************************************************************/
#include <stdio.h>
#include "WsMethodStackWatchAdd.h"
#include "ContextCallStackList.h"
/**
* @date 2013/03/04
*
* Constructor.
******************************************************************************/
WsMethodStackWatchAdd::WsMethodStackWatchAdd():
WsMethod("AddStackWatch")
{
return;
}
/**
* @date 2013/03/04
*
* Destructor.
******************************************************************************/
WsMethodStackWatchAdd::~WsMethodStackWatchAdd(void)
{
return;
}
/**
* @date 2013/03/04
*
* Add StackWatch Method : Adds a new stackcall context. The provided caller eip
* will then be monitored with the full call stack.
******************************************************************************/
int32_t WsMethodStackWatchAdd::Call(const DynObject &Params, String *p_Answer)
{
int32_t i_Ret;
String JsonSlice, JsonAllocers;
if(p_Answer == NULL)
return(-1);
ContextCallStackList *CallStackList = ContextCallStackList::Instantiate();
if(CallStackList == NULL)
return(-1);
int64_t ContextId;
i_Ret = Params.FindInt("id", &ContextId);
if(i_Ret == 0)
{
ExeContext *Context = ExeContext::Get(ContextId);
if(Context == NULL)
i_Ret = -1;
if(i_Ret == 0)
{
const void *Caller = Context->GetCallStack().Get()[0];
if(CallStackList->HasItem(Caller) == false)
{
i_Ret = CallStackList->AddItem(Caller);
}
if(i_Ret == 0)
{
p_Answer->SetTo("{ \"status\": 0, \"data\" : {}\n");
}
}
}
return(i_Ret);
}
<commit_msg>Add missing curly brackets in StackWatchAdd json result<commit_after>/*
*****************************************************************************
* ___ _ _ _ _
* / _ \ __ _| |_| |__(_) |_ ___
* | (_) / _` | / / '_ \ | _(_-<
* \___/\__,_|_\_\_.__/_|\__/__/
* Copyright (c) 2013
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*****************************************************************************/
/**
* @author R. Picard
* @date 2013/03/04
*
*****************************************************************************/
#include <stdio.h>
#include "WsMethodStackWatchAdd.h"
#include "ContextCallStackList.h"
/**
* @date 2013/03/04
*
* Constructor.
******************************************************************************/
WsMethodStackWatchAdd::WsMethodStackWatchAdd():
WsMethod("AddStackWatch")
{
return;
}
/**
* @date 2013/03/04
*
* Destructor.
******************************************************************************/
WsMethodStackWatchAdd::~WsMethodStackWatchAdd(void)
{
return;
}
/**
* @date 2013/03/04
*
* Add StackWatch Method : Adds a new stackcall context. The provided caller eip
* will then be monitored with the full call stack.
******************************************************************************/
int32_t WsMethodStackWatchAdd::Call(const DynObject &Params, String *p_Answer)
{
int32_t i_Ret;
String JsonSlice, JsonAllocers;
if(p_Answer == NULL)
return(-1);
ContextCallStackList *CallStackList = ContextCallStackList::Instantiate();
if(CallStackList == NULL)
return(-1);
int64_t ContextId;
i_Ret = Params.FindInt("id", &ContextId);
if(i_Ret == 0)
{
ExeContext *Context = ExeContext::Get(ContextId);
if(Context == NULL)
i_Ret = -1;
if(i_Ret == 0)
{
const void *Caller = Context->GetCallStack().Get()[0];
if(CallStackList->HasItem(Caller) == false)
{
i_Ret = CallStackList->AddItem(Caller);
}
if(i_Ret == 0)
{
p_Answer->SetTo("{ \"status\": 0, \"data\" : {} }\n");
}
}
}
return(i_Ret);
}
<|endoftext|> |
<commit_before>// KTH DD2458 popuph14
// authors: [email protected]
// [email protected]
#pragma once
#include <vector>
#include <queue>
#include "graph.hpp"
// Comparator function which makes priority_queue smallest first
struct comp {
int operator() (const Node* n1,const Node* n2) {
return n1->value > n2->value;
}
};
//Perform dijkstra's algorithm from start node to all other nodes
//After returning, every node in the graph will contain the length of the shortest path from start to that node.
void dijkstra(Node* start) {
//Iniate the queue and starting length
std::priority_queue<Node*, std::vector<Node*>, comp> q;
start->value = 0;
q.push(start);
//For each remaining node
while (!q.empty()) {
Node* current = q.top();
q.pop();
//Search all adjacent nodes
for (Edge* e : current->edges) {
Node* t = e->right;
int dist = current->value + e->weight;
//If this value is better, update and queue
if (dist < t->value) {
t->value = dist;
t->previous = current;
q.push(t);
}
}
}
}
<commit_msg>Dijksta whitespacing :P<commit_after>// KTH DD2458 popuph14
// authors: [email protected]
// [email protected]
#pragma once
#include <vector>
#include <queue>
#include "graph.hpp"
// Comparator function which makes priority_queue smallest first
struct comp {
int operator() (const Node* n1,const Node* n2) {
return n1->value > n2->value;
}
};
//Perform dijkstra's algorithm from start node to all other nodes
//After returning, every node in the graph will contain the length of the shortest path from start to that node.
void dijkstra(Node* start) {
//Iniate the queue and starting length
std::priority_queue<Node*, std::vector<Node*>, comp> q;
start->value = 0;
q.push(start);
//For each remaining node
while (!q.empty()) {
Node* current = q.top();
q.pop();
//Search all adjacent nodes
for (Edge* e : current->edges) {
Node* t = e->right;
int dist = current->value + e->weight;
//If this value is better, update and queue
if (dist < t->value) {
t->value = dist;
t->previous = current;
q.push(t);
}
}
}
}
<|endoftext|> |
<commit_before>#include "mesh_def.h"
#include <vcg/complex/algorithms/local_optimization/tri_edge_collapse_quadric.h>
#include <vcg/complex/algorithms/clustering.h>
using namespace vcg;
using namespace std;
typedef SimpleTempData<MyMesh::VertContainer, math::Quadric<double> > QuadricTemp;
class QHelper
{
public:
QHelper(){}
static void Init(){}
static math::Quadric<double> &Qd(MyVertex &v) {return TD()[v];}
static math::Quadric<double> &Qd(MyVertex *v) {return TD()[*v];}
static MyVertex::ScalarType W(MyVertex * /*v*/) {return 1.0;}
static MyVertex::ScalarType W(MyVertex & /*v*/) {return 1.0;}
static void Merge(MyVertex & /*v_dest*/, MyVertex const & /*v_del*/){}
static QuadricTemp* &TDp() {static QuadricTemp *td; return td;}
static QuadricTemp &TD() {return *TDp();}
};
typedef tri::BasicVertexPair<MyVertex> VertexPair;
class MyTriEdgeCollapse: public vcg::tri::TriEdgeCollapseQuadric< MyMesh, VertexPair , MyTriEdgeCollapse, QHelper > {
public:
typedef vcg::tri::TriEdgeCollapseQuadric< MyMesh, VertexPair, MyTriEdgeCollapse, QHelper> TECQ;
inline MyTriEdgeCollapse( const VertexPair &p, int i, BaseParameterClass *pp) :TECQ(p,i,pp){}
};
void ClusteringSimplification(uintptr_t _baseM, float threshold)
{
MyMesh &m = *((MyMesh*) _baseM);
tri::Clustering<MyMesh, vcg::tri::AverageColorCell<MyMesh> > ClusteringGrid;
ClusteringGrid.Init(m.bbox,100000,threshold);
if(m.FN() ==0)
ClusteringGrid.AddPointSet(m);
else
ClusteringGrid.AddMesh(m);
ClusteringGrid.ExtractMesh(m);
printf("Completed Clustering Simplification\n");
}
void QuadricSimplification(uintptr_t _baseM, float TargetFaceRatio, int exactFaceNum, bool qualityQuadric)
{
MyMesh &m = *((MyMesh*) _baseM);
math::Quadric<double> QZero;
QZero.SetZero();
QuadricTemp TD(m.vert,QZero);
QHelper::TDp()=&TD;
tri::TriEdgeCollapseQuadricParameter pp;
if(pp.NormalCheck) pp.NormalThrRad = M_PI/4.0;
vcg::LocalOptimization<MyMesh> DeciSession(m,&pp);
DeciSession.Init<MyTriEdgeCollapse >();
int TargetFaceNum;
if(exactFaceNum==0) TargetFaceNum = m.fn * TargetFaceRatio;
else TargetFaceNum = exactFaceNum;
DeciSession.SetTargetSimplices(TargetFaceNum);
DeciSession.SetTimeBudget(0.1f); // this allow to update the progress bar 10 time for sec...
while( DeciSession.DoOptimization() && m.fn>TargetFaceNum );
DeciSession.Finalize<MyTriEdgeCollapse >();
tri::Allocator<MyMesh>::CompactEveryVector(m);
printf("Completed Simplification\n");
}
#ifdef __EMSCRIPTEN__
//Binding code
EMSCRIPTEN_BINDINGS(MLMeshingPlugin) {
emscripten::function("QuadricSimplification", &QuadricSimplification);
// emscripten::function("MontecarloSampling", &MontecarloSamplingML);
}
#endif
<commit_msg>corrected quadric simplification bug<commit_after>#include "mesh_def.h"
#include <vcg/complex/algorithms/local_optimization/tri_edge_collapse_quadric.h>
#include <vcg/complex/algorithms/clustering.h>
using namespace vcg;
using namespace std;
typedef SimpleTempData<MyMesh::VertContainer, math::Quadric<double> > QuadricTemp;
class QHelper
{
public:
QHelper(){}
static void Init(){}
static math::Quadric<double> &Qd(MyVertex &v) {return TD()[v];}
static math::Quadric<double> &Qd(MyVertex *v) {return TD()[*v];}
static MyVertex::ScalarType W(MyVertex * /*v*/) {return 1.0;}
static MyVertex::ScalarType W(MyVertex & /*v*/) {return 1.0;}
static void Merge(MyVertex & /*v_dest*/, MyVertex const & /*v_del*/){}
static QuadricTemp* &TDp() {static QuadricTemp *td; return td;}
static QuadricTemp &TD() {return *TDp();}
};
typedef tri::BasicVertexPair<MyVertex> VertexPair;
class MyTriEdgeCollapse: public vcg::tri::TriEdgeCollapseQuadric< MyMesh, VertexPair , MyTriEdgeCollapse, QHelper > {
public:
typedef vcg::tri::TriEdgeCollapseQuadric< MyMesh, VertexPair, MyTriEdgeCollapse, QHelper> TECQ;
inline MyTriEdgeCollapse( const VertexPair &p, int i, BaseParameterClass *pp) :TECQ(p,i,pp){}
};
void ClusteringSimplification(uintptr_t _baseM, float threshold)
{
MyMesh &m = *((MyMesh*) _baseM);
tri::Clustering<MyMesh, vcg::tri::AverageColorCell<MyMesh> > ClusteringGrid;
ClusteringGrid.Init(m.bbox,100000,threshold);
if(m.FN() ==0)
ClusteringGrid.AddPointSet(m);
else
ClusteringGrid.AddMesh(m);
ClusteringGrid.ExtractMesh(m);
printf("Completed Clustering Simplification\n");
}
void QuadricSimplification(uintptr_t _baseM, float TargetFaceRatio, int exactFaceNum, bool qualityQuadric)
{
MyMesh &m = *((MyMesh*) _baseM);
tri::UpdateTopology<MyMesh>::ClearFaceFace(m);
math::Quadric<double> QZero;
QZero.SetZero();
QuadricTemp TD(m.vert,QZero);
QHelper::TDp()=&TD;
tri::TriEdgeCollapseQuadricParameter pp;
if(pp.NormalCheck) pp.NormalThrRad = M_PI/4.0;
vcg::LocalOptimization<MyMesh> DeciSession(m,&pp);
DeciSession.Init<MyTriEdgeCollapse >();
int TargetFaceNum;
if(exactFaceNum==0) TargetFaceNum = m.fn * TargetFaceRatio;
else TargetFaceNum = exactFaceNum;
DeciSession.SetTargetSimplices(TargetFaceNum);
DeciSession.SetTimeBudget(0.1f); // this allow to update the progress bar 10 time for sec...
while( DeciSession.DoOptimization() && m.fn>TargetFaceNum );
DeciSession.Finalize<MyTriEdgeCollapse >();
tri::Allocator<MyMesh>::CompactEveryVector(m);
printf("Completed Simplification\n");
}
#ifdef __EMSCRIPTEN__
//Binding code
EMSCRIPTEN_BINDINGS(MLMeshingPlugin) {
emscripten::function("QuadricSimplification", &QuadricSimplification);
// emscripten::function("MontecarloSampling", &MontecarloSamplingML);
}
#endif
<|endoftext|> |
<commit_before>/**
@file cc_unique_ptr.hpp
@brief const-correct unique_ptr.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_CC_UNIQUE_PTR_HPP_
#define HORD_CC_UNIQUE_PTR_HPP_
#include <Hord/config.hpp>
#include <type_traits>
#include <utility>
#include <memory>
namespace Hord {
// Forward declarations
template<
typename _Tp,
typename _Dp = std::default_delete<_Tp>
>
class cc_unique_ptr;
/**
@addtogroup etc
@{
*/
/**
@addtogroup memory
@{
*/
/**
const-correct std::unique_ptr.
*/
template<
typename _Tp,
typename _Dp
>
class cc_unique_ptr final {
private:
using base = std::unique_ptr<_Tp, _Dp>;
public:
using pointer = typename base::pointer;
using element_type = typename base::element_type;
using deleter_type = typename base::deleter_type;
using const_pointer = element_type const*;
using reference
= typename std::add_lvalue_reference<element_type>::type;
using const_reference
= typename std::add_lvalue_reference<element_type const>::type;
private:
using d1ctor_deleter_type
= typename std::conditional<
std::is_reference<deleter_type>::value,
deleter_type,
const deleter_type&
>::type;
base m_base;
public:
// constructors
constexpr
cc_unique_ptr() noexcept = default;
constexpr
cc_unique_ptr(
std::nullptr_t
) noexcept
: m_base(nullptr)
{}
explicit
cc_unique_ptr(
pointer ptr
) noexcept
: m_base(std::move(ptr))
{}
cc_unique_ptr(
pointer ptr,
d1ctor_deleter_type deleter
) noexcept
: m_base(std::move(ptr), std::forward<d1ctor_deleter_type>(deleter))
{}
cc_unique_ptr(
pointer ptr,
typename std::remove_reference<deleter_type>::type&& deleter
) noexcept
: m_base(std::move(ptr), std::move(deleter))
{}
cc_unique_ptr(cc_unique_ptr const&) = delete;
cc_unique_ptr(
cc_unique_ptr&& upc
) noexcept
: m_base(std::move(upc.m_base))
{}
/*
typename = typename std::enable_if<
std::is_convertible<
typename std::unique_ptr<_Up, _Ep>::pointer,
pointer
>::value
&& !std::is_array<_Up>::value
&& std::is_convertible<_Ep, deleter_type>::value
&& (
!std::is_reference<deleter_type>::value ||
std::is_same<deleter_type, _Ep>::value
)
>::type
*/
template<
typename _Up,
typename _Ep
>
cc_unique_ptr(
cc_unique_ptr<_Up, _Ep>&& up
) noexcept
: m_base(std::forward<std::unique_ptr<_Up, _Ep>>(up))
{}
// destructor
// NB: The Standard specifies no noexcept, but says:
// The expression get_deleter()(get()) shall be well formed,
// shall have well-defined behavior, and shall not throw
// exceptions.
// Which suggests the unique_ptr implementation is allowed to
// throw. libc++ concurs with the specification, but libstdc++
// does not.
~cc_unique_ptr() noexcept(noexcept(m_base.~base())) = default;
// assignment
cc_unique_ptr& operator=(cc_unique_ptr const&) = delete;
cc_unique_ptr& operator=(cc_unique_ptr&&) noexcept = default;
template<
typename _Up,
typename _Ep
>
cc_unique_ptr&
operator=(
cc_unique_ptr<_Up, _Ep>&& up
) noexcept {
m_base.operator=(std::forward<std::unique_ptr<_Up, _Ep>>(up));
return *this;
}
cc_unique_ptr&
operator=(
std::nullptr_t
) noexcept {
m_base.operator=(nullptr);
return *this;
}
// observers
pointer
get() noexcept {
return m_base.get();
}
const_pointer
get() const noexcept {
return m_base.get();
}
deleter_type&
get_deleter() noexcept {
return m_base.get_deleter();
}
deleter_type const&
get_deleter() const noexcept {
return m_base.get_deleter();
}
reference
operator*() {
return m_base.operator*();
}
const_reference
operator*() const {
return m_base.operator*();
}
pointer
operator->() noexcept {
return m_base.operator->();
}
const_pointer
operator->() const noexcept {
return m_base.operator->();
}
explicit
operator bool() const noexcept {
return m_base.operator bool();
}
// modifiers
pointer
release() noexcept {
return m_base.release();
}
pointer
reset(
pointer ptr = pointer()
) noexcept {
return m_base.reset(std::forward<pointer>(ptr));
}
void
swap(
cc_unique_ptr& other
) noexcept {
m_base.swap(other.m_base);
}
};
// specialized algorithms
// NB: The Standard does not give T1-T2 comparison operators noexcept,
// but get() is specified as having noexcept, so all of these
// operators do _not_ follow the standard (because they have
// noexcept).
// operator==
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator==(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _x.get() == _y.get();
}
template<
typename _Tp, typename _Dp
>
inline bool
operator==(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !_x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator==(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !_x;
}
// operator!=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator!=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _x.get() != _y.get();
}
template<
typename _Tp, typename _Dp
>
inline bool
operator!=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return (bool)_x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator!=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return (bool)_x;
}
// operator<
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator<(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
using _CT = typename std::common_type<
typename cc_unique_ptr<_Tp1, _Dp1>::pointer,
typename cc_unique_ptr<_Tp2, _Dp2>::pointer
>::type;
return std::less<_CT>(_x.get(), _y.get());
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return std::less<typename cc_unique_ptr<_Tp, _Dp>::pointer>(
_x.get(), nullptr
);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return std::less<typename cc_unique_ptr<_Tp, _Dp>::pointer>(
nullptr, _x.get()
);
}
// operator<=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator<=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return !(_y < _x);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !(nullptr < _x);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !(_x < nullptr);
}
// operator>
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator>(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _y < _x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return nullptr < _x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return _x < nullptr;
}
// operator>=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator>=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return !(_x < _y);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !(_x < nullptr);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !(nullptr < _x);
}
/** @} */ // end of doc-group memory
/** @} */ // end of doc-group etc
} // namespace Hord
#endif // HORD_CC_UNIQUE_PTR_HPP_
<commit_msg>cc_unique_ptr: make reset() return void¹.<commit_after>/**
@file cc_unique_ptr.hpp
@brief const-correct unique_ptr.
@author Tim Howard
@copyright 2013 Tim Howard under the MIT license;
see @ref index or the accompanying LICENSE file for full text.
*/
#ifndef HORD_CC_UNIQUE_PTR_HPP_
#define HORD_CC_UNIQUE_PTR_HPP_
#include <Hord/config.hpp>
#include <type_traits>
#include <utility>
#include <memory>
namespace Hord {
// Forward declarations
template<
typename _Tp,
typename _Dp = std::default_delete<_Tp>
>
class cc_unique_ptr;
/**
@addtogroup etc
@{
*/
/**
@addtogroup memory
@{
*/
/**
const-correct std::unique_ptr.
*/
template<
typename _Tp,
typename _Dp
>
class cc_unique_ptr final {
private:
using base = std::unique_ptr<_Tp, _Dp>;
public:
using pointer = typename base::pointer;
using element_type = typename base::element_type;
using deleter_type = typename base::deleter_type;
using const_pointer = element_type const*;
using reference
= typename std::add_lvalue_reference<element_type>::type;
using const_reference
= typename std::add_lvalue_reference<element_type const>::type;
private:
using d1ctor_deleter_type
= typename std::conditional<
std::is_reference<deleter_type>::value,
deleter_type,
const deleter_type&
>::type;
base m_base;
public:
// constructors
constexpr
cc_unique_ptr() noexcept = default;
constexpr
cc_unique_ptr(
std::nullptr_t
) noexcept
: m_base(nullptr)
{}
explicit
cc_unique_ptr(
pointer ptr
) noexcept
: m_base(std::move(ptr))
{}
cc_unique_ptr(
pointer ptr,
d1ctor_deleter_type deleter
) noexcept
: m_base(std::move(ptr), std::forward<d1ctor_deleter_type>(deleter))
{}
cc_unique_ptr(
pointer ptr,
typename std::remove_reference<deleter_type>::type&& deleter
) noexcept
: m_base(std::move(ptr), std::move(deleter))
{}
cc_unique_ptr(cc_unique_ptr const&) = delete;
cc_unique_ptr(
cc_unique_ptr&& upc
) noexcept
: m_base(std::move(upc.m_base))
{}
/*
typename = typename std::enable_if<
std::is_convertible<
typename std::unique_ptr<_Up, _Ep>::pointer,
pointer
>::value
&& !std::is_array<_Up>::value
&& std::is_convertible<_Ep, deleter_type>::value
&& (
!std::is_reference<deleter_type>::value ||
std::is_same<deleter_type, _Ep>::value
)
>::type
*/
template<
typename _Up,
typename _Ep
>
cc_unique_ptr(
cc_unique_ptr<_Up, _Ep>&& up
) noexcept
: m_base(std::forward<std::unique_ptr<_Up, _Ep>>(up))
{}
// destructor
// NB: The Standard specifies no noexcept, but says:
// The expression get_deleter()(get()) shall be well formed,
// shall have well-defined behavior, and shall not throw
// exceptions.
// Which suggests the unique_ptr implementation is allowed to
// throw. libc++ concurs with the specification, but libstdc++
// does not.
~cc_unique_ptr() noexcept(noexcept(m_base.~base())) = default;
// assignment
cc_unique_ptr& operator=(cc_unique_ptr const&) = delete;
cc_unique_ptr& operator=(cc_unique_ptr&&) noexcept = default;
template<
typename _Up,
typename _Ep
>
cc_unique_ptr&
operator=(
cc_unique_ptr<_Up, _Ep>&& up
) noexcept {
m_base.operator=(std::forward<std::unique_ptr<_Up, _Ep>>(up));
return *this;
}
cc_unique_ptr&
operator=(
std::nullptr_t
) noexcept {
m_base.operator=(nullptr);
return *this;
}
// observers
pointer
get() noexcept {
return m_base.get();
}
const_pointer
get() const noexcept {
return m_base.get();
}
deleter_type&
get_deleter() noexcept {
return m_base.get_deleter();
}
deleter_type const&
get_deleter() const noexcept {
return m_base.get_deleter();
}
reference
operator*() {
return m_base.operator*();
}
const_reference
operator*() const {
return m_base.operator*();
}
pointer
operator->() noexcept {
return m_base.operator->();
}
const_pointer
operator->() const noexcept {
return m_base.operator->();
}
explicit
operator bool() const noexcept {
return m_base.operator bool();
}
// modifiers
pointer
release() noexcept {
return m_base.release();
}
void
reset(
pointer ptr = pointer()
) noexcept {
m_base.reset(std::forward<pointer>(ptr));
}
void
swap(
cc_unique_ptr& other
) noexcept {
m_base.swap(other.m_base);
}
};
// specialized algorithms
// NB: The Standard does not give T1-T2 comparison operators noexcept,
// but get() is specified as having noexcept, so all of these
// operators do _not_ follow the standard (because they have
// noexcept).
// operator==
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator==(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _x.get() == _y.get();
}
template<
typename _Tp, typename _Dp
>
inline bool
operator==(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !_x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator==(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !_x;
}
// operator!=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator!=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _x.get() != _y.get();
}
template<
typename _Tp, typename _Dp
>
inline bool
operator!=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return (bool)_x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator!=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return (bool)_x;
}
// operator<
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator<(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
using _CT = typename std::common_type<
typename cc_unique_ptr<_Tp1, _Dp1>::pointer,
typename cc_unique_ptr<_Tp2, _Dp2>::pointer
>::type;
return std::less<_CT>(_x.get(), _y.get());
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return std::less<typename cc_unique_ptr<_Tp, _Dp>::pointer>(
_x.get(), nullptr
);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return std::less<typename cc_unique_ptr<_Tp, _Dp>::pointer>(
nullptr, _x.get()
);
}
// operator<=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator<=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return !(_y < _x);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !(nullptr < _x);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator<=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !(_x < nullptr);
}
// operator>
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator>(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return _y < _x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return nullptr < _x;
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return _x < nullptr;
}
// operator>=
template<
typename _Tp1, typename _Dp1,
typename _Tp2, typename _Dp2
>
inline bool
operator>=(
cc_unique_ptr<_Tp1, _Dp1> const& _x,
cc_unique_ptr<_Tp2, _Dp2> const& _y
) noexcept {
return !(_x < _y);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>=(
cc_unique_ptr<_Tp, _Dp> const& _x,
std::nullptr_t
) noexcept {
return !(_x < nullptr);
}
template<
typename _Tp, typename _Dp
>
inline bool
operator>=(
std::nullptr_t,
cc_unique_ptr<_Tp, _Dp> const& _x
) noexcept {
return !(nullptr < _x);
}
/** @} */ // end of doc-group memory
/** @} */ // end of doc-group etc
} // namespace Hord
#endif // HORD_CC_UNIQUE_PTR_HPP_
<|endoftext|> |
<commit_before>#include "sqloxx_tests_common.hpp"
#include "derived_po.hpp"
#include "../database_connection.hpp"
#include "../detail/sql_statement_impl.hpp"
#include "../detail/sqlite_dbconn.hpp"
#include "../sql_statement.hpp"
#include <boost/filesystem.hpp>
#include <jewel/stopwatch.hpp>
#if WIN32 || __WIN32__ || __WIN32 || _WIN32_ || WIN32_ || WIN32__
# define SQLOXX_ON_WINDOWS 1
#else
# define SQLOXX_ON_WINDOWS 0
#endif
#if SQLOXX_ON_WINDOWS
# include <windows.h> // for Sleep
#endif
#include <cassert>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
using jewel::Stopwatch;
using std::cout;
using std::cerr;
using std::endl;
using std::remove;
using std::string;
using std::terminate;
using std::vector;
using sqloxx::detail::SQLStatementImpl;
using sqloxx::detail::SQLiteDBConn;
namespace filesystem = boost::filesystem;
namespace
{
void windows_friendly_remove(string const& fp)
{
# if SQLOXX_ON_WINDOWS
int const max_tries = 10000;
int const delay = 100;
char const* filename = fp.c_str();
int i;
for
( i = 0;
(remove(filename) != 0) && (i != max_tries);
++i
)
{
Sleep(delay);
}
if (i == max_tries)
{
assert (filesystem::exists(fp));
cout << "Test file could not be removed. Terminating tests."
<< endl;
terminate();
}
# else
filesystem::remove(fp);
# endif
assert (!filesystem::exists(fp));
return;
}
} // end anonymous namespace
namespace sqloxx
{
namespace tests
{
bool file_exists(filesystem::path const& filepath)
{
return filesystem::exists
( filesystem::status(filepath)
);
}
void abort_if_exists(filesystem::path const& filepath)
{
if (file_exists(filepath))
{
cerr << "File named \"" << filepath.string() << "\" already "
<< "exists. Test terminated." << endl;
terminate();
}
return;
}
void
do_speed_test()
{
string const filename("aaksjh237nsal");
int const loops = 50000;
vector<string> statements;
statements.push_back
( "insert into dummy(colA, colB) values(3, 'hi')"
);
statements.push_back
( "select colA, colB from dummy where colB = "
" 'asfkjasdlfkasdfasdf' and colB = '-90982097';"
);
statements.push_back
( "insert into dummy(colA, colB) values(198712319, 'aasdfhasdkjhash');"
);
statements.push_back
( "select colA, colB from dummy where colA = "
" 'noasdsjhasdfkjhasdkfjh' and colB = '-9987293879';"
);
vector<string>::size_type const num_statements = statements.size();
string const table_creation_string
( "create table dummy(colA int not null, colB text)"
);
// With SQLStatement
DatabaseConnection db;
db.open(filename);
db.execute_sql(table_creation_string);
cout << "Timing with SQLStatement." << endl;
db.execute_sql("begin");
Stopwatch sw1;
for (int i = 0; i != loops; ++i)
{
SQLStatement s(db, statements[i % num_statements]);
// s.step_final();
}
sw1.log();
db.execute_sql("end");
windows_friendly_remove(filename);
// With SQLStatementImpl
SQLiteDBConn sdbc;
sdbc.open(filename);
sdbc.execute_sql(table_creation_string);
cout << "Timing with SQLStatementImpl." << endl;
sdbc.execute_sql("begin");
Stopwatch sw0;
for (int i = 0; i != loops; ++i)
{
SQLStatementImpl s(sdbc, statements[i % num_statements]);
// s.step_final();
}
sw0.log();
sdbc.execute_sql("end");
windows_friendly_remove(filename);
return;
}
DatabaseConnectionFixture::DatabaseConnectionFixture():
db_filepath("Testfile_01"),
pdbc(0)
{
pdbc = new DatabaseConnection;
abort_if_exists(db_filepath);
pdbc->open(db_filepath);
assert (pdbc->is_valid());
}
DatabaseConnectionFixture::~DatabaseConnectionFixture()
{
assert (pdbc->is_valid());
delete pdbc;
windows_friendly_remove(db_filepath.string());
assert (!file_exists(db_filepath));
}
DerivedPOFixture::DerivedPOFixture():
db_filepath("Testfile_dpof"),
pdbc(0)
{
pdbc = new DerivedDatabaseConnection;
abort_if_exists(db_filepath);
pdbc->open(db_filepath);
assert (pdbc->is_valid());
DerivedPO::setup_tables(*pdbc);
}
DerivedPOFixture::~DerivedPOFixture()
{
assert (pdbc->is_valid());
delete pdbc;
windows_friendly_remove(db_filepath.string());
assert (!file_exists(db_filepath));
}
} // namespace sqloxx
} // namespace tests
<commit_msg>Small edit to SQLoxx test fixture code to make use of new JEWEL_ON_WINDOWS macro.<commit_after>#include "sqloxx_tests_common.hpp"
#include "derived_po.hpp"
#include "../database_connection.hpp"
#include "../detail/sql_statement_impl.hpp"
#include "../detail/sqlite_dbconn.hpp"
#include "../sql_statement.hpp"
#include <boost/filesystem.hpp>
#include <jewel/on_windows.hpp>
#include <jewel/stopwatch.hpp>
#if JEWEL_ON_WINDOWS
# include <windows.h> // for Sleep
#endif
#include <cassert>
#include <cstdlib>
#include <exception>
#include <iostream>
#include <string>
#include <vector>
using jewel::Stopwatch;
using std::cout;
using std::cerr;
using std::endl;
using std::remove;
using std::string;
using std::terminate;
using std::vector;
using sqloxx::detail::SQLStatementImpl;
using sqloxx::detail::SQLiteDBConn;
namespace filesystem = boost::filesystem;
namespace
{
void windows_friendly_remove(string const& fp)
{
# if JEWEL_ON_WINDOWS
int const max_tries = 10000;
int const delay = 100;
char const* filename = fp.c_str();
int i;
for
( i = 0;
(remove(filename) != 0) && (i != max_tries);
++i
)
{
Sleep(delay);
}
if (i == max_tries)
{
assert (filesystem::exists(fp));
cout << "Test file could not be removed. Terminating tests."
<< endl;
terminate();
}
# else
filesystem::remove(fp);
# endif
assert (!filesystem::exists(fp));
return;
}
} // end anonymous namespace
namespace sqloxx
{
namespace tests
{
bool file_exists(filesystem::path const& filepath)
{
return filesystem::exists
( filesystem::status(filepath)
);
}
void abort_if_exists(filesystem::path const& filepath)
{
if (file_exists(filepath))
{
cerr << "File named \"" << filepath.string() << "\" already "
<< "exists. Test terminated." << endl;
terminate();
}
return;
}
void
do_speed_test()
{
string const filename("aaksjh237nsal");
int const loops = 50000;
vector<string> statements;
statements.push_back
( "insert into dummy(colA, colB) values(3, 'hi')"
);
statements.push_back
( "select colA, colB from dummy where colB = "
" 'asfkjasdlfkasdfasdf' and colB = '-90982097';"
);
statements.push_back
( "insert into dummy(colA, colB) values(198712319, 'aasdfhasdkjhash');"
);
statements.push_back
( "select colA, colB from dummy where colA = "
" 'noasdsjhasdfkjhasdkfjh' and colB = '-9987293879';"
);
vector<string>::size_type const num_statements = statements.size();
string const table_creation_string
( "create table dummy(colA int not null, colB text)"
);
// With SQLStatement
DatabaseConnection db;
db.open(filename);
db.execute_sql(table_creation_string);
cout << "Timing with SQLStatement." << endl;
db.execute_sql("begin");
Stopwatch sw1;
for (int i = 0; i != loops; ++i)
{
SQLStatement s(db, statements[i % num_statements]);
// s.step_final();
}
sw1.log();
db.execute_sql("end");
windows_friendly_remove(filename);
// With SQLStatementImpl
SQLiteDBConn sdbc;
sdbc.open(filename);
sdbc.execute_sql(table_creation_string);
cout << "Timing with SQLStatementImpl." << endl;
sdbc.execute_sql("begin");
Stopwatch sw0;
for (int i = 0; i != loops; ++i)
{
SQLStatementImpl s(sdbc, statements[i % num_statements]);
// s.step_final();
}
sw0.log();
sdbc.execute_sql("end");
windows_friendly_remove(filename);
return;
}
DatabaseConnectionFixture::DatabaseConnectionFixture():
db_filepath("Testfile_01"),
pdbc(0)
{
pdbc = new DatabaseConnection;
abort_if_exists(db_filepath);
pdbc->open(db_filepath);
assert (pdbc->is_valid());
}
DatabaseConnectionFixture::~DatabaseConnectionFixture()
{
assert (pdbc->is_valid());
delete pdbc;
windows_friendly_remove(db_filepath.string());
assert (!file_exists(db_filepath));
}
DerivedPOFixture::DerivedPOFixture():
db_filepath("Testfile_dpof"),
pdbc(0)
{
pdbc = new DerivedDatabaseConnection;
abort_if_exists(db_filepath);
pdbc->open(db_filepath);
assert (pdbc->is_valid());
DerivedPO::setup_tables(*pdbc);
}
DerivedPOFixture::~DerivedPOFixture()
{
assert (pdbc->is_valid());
delete pdbc;
windows_friendly_remove(db_filepath.string());
assert (!file_exists(db_filepath));
}
} // namespace sqloxx
} // namespace tests
<|endoftext|> |
<commit_before>/*
* $Id$
*
* Copyright (c) 2011 Surfnet
* Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).
* Copyright (c) 2011 OpenDNSSEC AB (svb)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
*/
#include "keystate/update_keyzones_task.h"
#include "keystate/zone_del_task.h"
#include "shared/file.h"
#include "shared/duration.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "keystate/keystate.pb.h"
#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include <memory>
#include <vector>
#include <fcntl.h>
#include "protobuf-orm/pb-orm.h"
#include "daemon/orm.h"
#include "keystate/write_signzone_task.h"
static const char *module_str = "update_keyzones_task";
static bool
load_zonelist_xml(int sockfd, const char * zonelistfile,
std::auto_ptr< ::ods::keystate::ZoneListDocument >&doc)
{
// Create a zonefile and load it with zones from the xml zonelist.xml
doc.reset(new ::ods::keystate::ZoneListDocument);
if (doc.get() == NULL) {
ods_log_error_and_printf(sockfd,module_str,
"out of memory allocating ZoneListDocument");
return false;
}
if (!read_pb_message_from_xml_file(doc.get(), zonelistfile)) {
ods_log_error_and_printf(sockfd,module_str,
"unable to read the zonelist.xml file");
return false;
}
if (!doc->has_zonelist()) {
ods_printf(sockfd, "[%s] no zonelist found in zonelist.xml file\n",
module_str);
return true;
}
const ::ods::keystate::ZoneList &zonelist = doc->zonelist();
if (zonelist.zones_size() <= 0) {
ods_printf(sockfd, "[%s] no zones found in zonelist\n", module_str);
return true;
}
if (!zonelist.IsInitialized()) {
ods_log_error_and_printf(sockfd,module_str,
"a zone in the zonelist is missing mandatory "
"information");
return false;
}
return true;
}
int
perform_update_keyzones(int sockfd, engineconfig_type *config)
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::auto_ptr< ::ods::keystate::ZoneListDocument > zonelistDoc;
if (!load_zonelist_xml(sockfd, config->zonelist_filename, zonelistDoc))
return 0; // errors have already been reported.
ods_printf(sockfd, "zonelist filename set to %s\n",
config->zonelist_filename);
OrmConnRef conn;
if (!ods_orm_connect(sockfd, config, conn))
return 0; // errors have already been reported.
//TODO: SPEED: We should create an index on the EnforcerZone.name column
// Go through the list of zones from the zonelist to determine if we need
// to insert new zones to the keystates.
std::map<std::string, bool> zoneimported;
//non-empty zonelist
if (zonelistDoc->has_zonelist()) {
OrmTransactionRW transaction(conn);
if (!transaction.started()) {
ods_log_error_and_printf(sockfd, module_str,
"error starting a database transaction for updating zones");
return 0;
}
for (int i=0; i<zonelistDoc->zonelist().zones_size(); ++i) {
const ::ods::keystate::ZoneData &zl_zone =
zonelistDoc->zonelist().zones(i);
zoneimported[zl_zone.name()] = true;
ods_printf(sockfd, "Zone %s found in zonelist.xml;"
" policy set to %s\n", zl_zone.name().c_str(),
zl_zone.policy().c_str());
std::string qzone;
if (!OrmQuoteStringValue(conn, zl_zone.name(), qzone)) {
ods_log_error_and_printf(sockfd, module_str,
"quoting a string failed");
return 0;
}
/* Lookup zone in database */
::ods::keystate::EnforcerZone ks_zone;
OrmResultRef rows;
if (!OrmMessageEnumWhere(conn, ks_zone.descriptor(), rows,
"name = %s",qzone.c_str()))
{
ods_log_error_and_printf(sockfd, module_str,
"zone lookup by name failed");
return 0;
}
OrmContextRef context;
if (OrmFirst(rows)) {
/* Zone already in database, retrieve it. */
ods_printf(sockfd, "Zone: %s found in database,"
" update it\n", zl_zone.name().c_str());
if (!OrmGetMessage(rows, ks_zone, true, context)) {
ods_log_error_and_printf(sockfd, module_str,
"zone retrieval failed");
return 0;
}
}
/* Update the zone with information from the zonelist entry */
ks_zone.set_name(zl_zone.name());
ks_zone.set_policy(zl_zone.policy());
ks_zone.set_signconf_path(
zl_zone.signer_configuration());
ks_zone.mutable_adapters()->CopyFrom(
zl_zone.adapters());
if (OrmFirst(rows)) {
/* update */
if (!OrmMessageUpdate(context)) {
ods_log_error_and_printf(sockfd, module_str,
"zone update failed");
return 0;
}
} else {
/* insert */
ks_zone.set_signconf_needs_writing( false );
ods_printf(sockfd, "Zone: %s not found in database,"
" insert it\n", zl_zone.name().c_str());
pb::uint64 zoneid;
if (!OrmMessageInsert(conn, ks_zone, zoneid)) {
ods_log_error_and_printf(sockfd, module_str,
"inserting zone into the database failed");
return 0;
}
}
rows.release();
}
if (!transaction.commit()) {
ods_log_error_and_printf(sockfd, module_str,
"committing zone to the database failed");
return 0;
}
}
std::vector<std::string> non_exist_zones;
//delete non-exist zone
{
OrmTransaction transaction(conn);
if (!transaction.started()) {
ods_log_error_and_printf(sockfd, module_str,
"starting database transaction failed");
return 0;
}
{ OrmResultRef rows;
::ods::keystate::EnforcerZone enfzone;
bool ok = OrmMessageEnum(conn, enfzone.descriptor(), rows);
if (!ok) {
ods_log_error_and_printf(sockfd, module_str,
"zone enumaration failed");
return 0;
}
for (bool next=OrmFirst(rows); next; next = OrmNext(rows)) {
OrmContextRef context;
if (!OrmGetMessage(rows, enfzone, true, context)) {
rows.release();
ods_log_error_and_printf(sockfd, module_str,
"retrieving zone from database failed");
return 0;
}
//zone is not in zonelist.xml, then delete it
if (!zoneimported[enfzone.name()]) {
non_exist_zones.push_back(enfzone.name());
}
}
rows.release();
}
if (!transaction.commit()) {
ods_log_error_and_printf(sockfd, module_str,
"committing zone enumeration select failed");
return 0;
}
}
if (!non_exist_zones.empty()) {
int del_zone_count = non_exist_zones.size();
for (int i = 0; i < del_zone_count; ++i) {
ods_printf(sockfd, "Zone: %s not exist in zonelist.xml, "
"delete it from database\n",
non_exist_zones[i].c_str());
perform_zone_del(sockfd, config,
non_exist_zones[i].c_str(),
0);
}
}
//write signzones.xml
if (!perform_write_signzone_file(sockfd, config))
ods_log_error_and_printf(sockfd, module_str,
"failed to write signzones file");
return 1;
}
<commit_msg>OPENDNSSEC-455 pre process list of zones in db to prevent 50k queries.<commit_after>/*
* $Id$
*
* Copyright (c) 2011 Surfnet
* Copyright (c) 2011 .SE (The Internet Infrastructure Foundation).
* Copyright (c) 2011 OpenDNSSEC AB (svb)
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*
*/
#include "keystate/update_keyzones_task.h"
#include "keystate/zone_del_task.h"
#include "shared/file.h"
#include "shared/duration.h"
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include "keystate/keystate.pb.h"
#include "xmlext-pb/xmlext-rd.h"
#include "xmlext-pb/xmlext-wr.h"
#include <memory>
#include <vector>
#include <fcntl.h>
#include "protobuf-orm/pb-orm.h"
#include "daemon/orm.h"
#include "keystate/write_signzone_task.h"
static const char *module_str = "update_keyzones_task";
static bool
load_zonelist_xml(int sockfd, const char * zonelistfile,
std::auto_ptr< ::ods::keystate::ZoneListDocument >&doc)
{
// Create a zonefile and load it with zones from the xml zonelist.xml
doc.reset(new ::ods::keystate::ZoneListDocument);
if (doc.get() == NULL) {
ods_log_error_and_printf(sockfd,module_str,
"out of memory allocating ZoneListDocument");
return false;
}
if (!read_pb_message_from_xml_file(doc.get(), zonelistfile)) {
ods_log_error_and_printf(sockfd,module_str,
"unable to read the zonelist.xml file");
return false;
}
if (!doc->has_zonelist()) {
ods_printf(sockfd, "[%s] no zonelist found in zonelist.xml file\n",
module_str);
return true;
}
const ::ods::keystate::ZoneList &zonelist = doc->zonelist();
if (zonelist.zones_size() <= 0) {
ods_printf(sockfd, "[%s] no zones found in zonelist\n", module_str);
return true;
}
if (!zonelist.IsInitialized()) {
ods_log_error_and_printf(sockfd,module_str,
"a zone in the zonelist is missing mandatory "
"information");
return false;
}
return true;
}
static int
get_zones_from_db(OrmConnRef *conn, std::map<std::string, bool> zones_db)
{
OrmResultRef result;
::ods::keystate::EnforcerZone enfzone;
int err = !OrmMessageEnum(*conn, enfzone.descriptor(), result);
if (err) return 0;
for (bool next=OrmFirst(result); next; next = OrmNext(result)) {
OrmContextRef context;
if (!OrmGetMessage(result, enfzone, true, context)) {
err = 1;
break;
}
zones_db[enfzone.name()] = true;
}
result.release();
return err;
}
int
perform_update_keyzones(int sockfd, engineconfig_type *config)
{
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::auto_ptr< ::ods::keystate::ZoneListDocument > zonelistDoc;
if (!load_zonelist_xml(sockfd, config->zonelist_filename, zonelistDoc))
return 0; // errors have already been reported.
ods_printf(sockfd, "zonelist filename set to %s\n",
config->zonelist_filename);
OrmConnRef conn;
if (!ods_orm_connect(sockfd, config, conn))
return 0; // errors have already been reported.
//TODO: SPEED: We should create an index on the EnforcerZone.name column
// Go through the list of zones from the zonelist to determine if we need
// to insert new zones to the keystates.
std::map<std::string, bool> zoneimported;
/* first make a map with all current zones
* then iterate new zones to filter current */
std::map<std::string, bool> zones_db;
std::map<std::string, bool> zones_import;
std::map<std::string, bool> zones_delete;
std::map<std::string, bool> zones_new;
std::map<std::string, bool> zones_update;
typedef std::map<std::string, bool>::iterator item;
get_zones_from_db(&conn, zones_db);
for (int i=0; i<zonelistDoc->zonelist().zones_size(); ++i) {
const ::ods::keystate::ZoneData &zl_zone =
zonelistDoc->zonelist().zones(i);
zones_import[zl_zone.name()] = true;
}
for (item iterator = zones_import.begin(); iterator != zones_import.end(); iterator++) {
if (zones_db[iterator->first])
zones_delete[iterator->first] = true;
}
for (item iterator = zones_db.begin(); iterator != zones_db.end(); iterator++) {
if (!zones_update[iterator->first])
zones_update[iterator->first] = true;
else
zones_new[iterator->first] = true;
}
//non-empty zonelist
if (zonelistDoc->has_zonelist()) {
OrmTransactionRW transaction(conn);
if (!transaction.started()) {
ods_log_error_and_printf(sockfd, module_str,
"error starting a database transaction for updating zones");
return 0;
}
for (int i=0; i<zonelistDoc->zonelist().zones_size(); ++i) {
const ::ods::keystate::ZoneData &zl_zone =
zonelistDoc->zonelist().zones(i);
//~ zoneimported[zl_zone.name()] = true;
ods_printf(sockfd, "Zone %s found in zonelist.xml;"
" policy set to %s\n", zl_zone.name().c_str(),
zl_zone.policy().c_str());
std::string qzone;
if (!OrmQuoteStringValue(conn, zl_zone.name(), qzone)) {
ods_log_error_and_printf(sockfd, module_str,
"quoting a string failed");
return 0;
}
/* Lookup zone in database */
::ods::keystate::EnforcerZone ks_zone;
OrmResultRef rows;
/* check if qzone in zones_update */
bool update = zones_update[qzone];
if (update)
if (!OrmMessageEnumWhere(conn, ks_zone.descriptor(), rows,
"name = %s",qzone.c_str()))
{
ods_log_error_and_printf(sockfd, module_str,
"zone lookup by name failed");
return 0;
}
OrmContextRef context;
if (OrmFirst(rows)) {
/* Zone already in database, retrieve it. */
ods_printf(sockfd, "Zone: %s found in database,"
" update it\n", zl_zone.name().c_str());
if (!OrmGetMessage(rows, ks_zone, true, context)) {
ods_log_error_and_printf(sockfd, module_str,
"zone retrieval failed");
return 0;
}
}
/* Update the zone with information from the zonelist entry */
ks_zone.set_name(zl_zone.name());
ks_zone.set_policy(zl_zone.policy());
ks_zone.set_signconf_path(
zl_zone.signer_configuration());
ks_zone.mutable_adapters()->CopyFrom(
zl_zone.adapters());
if (OrmFirst(rows)) {
/* update */
if (!OrmMessageUpdate(context)) {
ods_log_error_and_printf(sockfd, module_str,
"zone update failed");
return 0;
}
} else {
/* insert */
ks_zone.set_signconf_needs_writing( false );
ods_printf(sockfd, "Zone: %s not found in database,"
" insert it\n", zl_zone.name().c_str());
pb::uint64 zoneid;
if (!OrmMessageInsert(conn, ks_zone, zoneid)) {
ods_log_error_and_printf(sockfd, module_str,
"inserting zone into the database failed");
return 0;
}
}
rows.release();
}
if (!transaction.commit()) {
ods_log_error_and_printf(sockfd, module_str,
"committing zone to the database failed");
return 0;
}
}
std::vector<std::string> non_exist_zones;
//delete non-exist zone
{
OrmTransaction transaction(conn);
if (!transaction.started()) {
ods_log_error_and_printf(sockfd, module_str,
"starting database transaction failed");
return 0;
}
{ OrmResultRef rows;
::ods::keystate::EnforcerZone enfzone;
bool ok = OrmMessageEnum(conn, enfzone.descriptor(), rows);
if (!ok) {
ods_log_error_and_printf(sockfd, module_str,
"zone enumaration failed");
return 0;
}
for (bool next=OrmFirst(rows); next; next = OrmNext(rows)) {
OrmContextRef context;
if (!OrmGetMessage(rows, enfzone, true, context)) {
rows.release();
ods_log_error_and_printf(sockfd, module_str,
"retrieving zone from database failed");
return 0;
}
//zone is not in zonelist.xml, then delete it
if (!zones_import[enfzone.name()]) {
non_exist_zones.push_back(enfzone.name());
}
}
rows.release();
}
if (!transaction.commit()) {
ods_log_error_and_printf(sockfd, module_str,
"committing zone enumeration select failed");
return 0;
}
}
if (!non_exist_zones.empty()) {
int del_zone_count = non_exist_zones.size();
for (int i = 0; i < del_zone_count; ++i) {
ods_printf(sockfd, "Zone: %s not exist in zonelist.xml, "
"delete it from database\n",
non_exist_zones[i].c_str());
perform_zone_del(sockfd, config,
non_exist_zones[i].c_str(),
0);
}
}
//write signzones.xml
if (!perform_write_signzone_file(sockfd, config))
ods_log_error_and_printf(sockfd, module_str,
"failed to write signzones file");
return 1;
}
<|endoftext|> |
<commit_before>#include <bits/stdc++.h>
#include "particles.hpp"
#include "eventQueue.hpp"
class boundingBox
{
private:
vector<Particle> particlesInBox;
eventQueue events;
public:
//Returns the event object in case of collision between particle
//and the box.
event getCollisionEventP2B(Particle partA){
int timeOfCollision=getTimeOfCollisionP2B(
partA.getMovementData(),
partA.getCordinates());
Particle partB;
partB.setMass(-1);
return event(timeOfCollision,partA,partB);
}
//Returns the event object in case of collision between the given
//particles.
event getCollisionEventP2P(Particle partA,Particle partB){
int timeOfCollision=getTimeOfCollisionP2P(
partA.getMovementData(),
partB.getMovementData(),
partA.getCordinates(),
partB.getCordinates());
return event(timeOfCollision,partA,partB);
}
//Computes all the collision events between every pair of particles.
void compute(){
events.clear();
int numParticles=(int)std::particlesInBox.size();
for(int i=0;i<numParticles;i++){
for(int j=i+1;j<numParticles;j++){
event collisionEvent=getCollisionEventP2P(
particlesInBox[i],
particlesInBox[j]);
events.push(collisionEvent);
}
}
for(int i=0;i<numParticles;i++){
event collisionEvent=getCollisionEventP2B(
particlesInBox[i]);
events.push(collisionEvent);
}
}
boundingBox(){
particlesInBox.clear();
};
//Which side does it collide with (returns an integer)
int whichSideCollides(){
//TODO
}
//Which (up)side does it collide with
bool upBoxSideCollides(int side){
if(side==0){
return true;
}
else{
return false;
}
}
//Which (low)side does it collide with
bool lowBoxSideCollides(int side){
if(side==2){
return true;
}
else{
return false;
}
}
//Which (right)side does it collide with
bool rightBoxSideCollides(int side){
if(side==1){
return true;
}
else{
return false;
}
}
//Which (left)side does it collide with
bool leftBoxSideCollides(int side){
if(side==3){
return true;
}
else{
return false;
}
}
};<commit_msg>simulation now beings in boundingBox and made changes to take radius into account.<commit_after>#include <bits/stdc++.h>
#include "particles.hpp"
#include "eventQueue.hpp"
class BoundingBox
{
private:
vector<Particle> particlesInBox;
eventQueue events;
public:
//The function that starts it all.
void startSimulation(){
//qwe
}
//Returns the event object in case of collision between particle
//and the box.
event getCollisionEventP2B(Particle partA){
int timeOfCollision=getTimeOfCollisionP2B(
partA.getMovementData(),
partA.getCordinates(),
partA.getRadius());
Particle partB;
partB.setMass(-1);
return event(timeOfCollision,partA,partB);
}
//Returns the event object in case of collision between the given
//particles.
event getCollisionEventP2P(Particle partA,Particle partB){
int timeOfCollision=getTimeOfCollisionP2P(
partA.getMovementData(),
partB.getMovementData(),
partA.getCordinates(),
partB.getCordinates(),
partA.getRadius(),
partB.getRadius());
return event(timeOfCollision,partA,partB);
}
//Computes all the collision events between every pair of particles.
void compute(){
events.clear();
int numParticles=(int)std::particlesInBox.size();
for(int i=0;i<numParticles;i++){
for(int j=i+1;j<numParticles;j++){
event collisionEvent=getCollisionEventP2P(
particlesInBox[i],
particlesInBox[j]);
events.push(collisionEvent);
}
}
for(int i=0;i<numParticles;i++){
event collisionEvent=getCollisionEventP2B(
particlesInBox[i]);
events.push(collisionEvent);
}
}
boundingBox(){
particlesInBox.clear();
};
//Function which will allow the addition of particles into the box.
void addParticle(Particle _particle){
stdd::particlesInBox.push_back(_particle);
}
//Which side does it collide with (returns an integer).
int whichSideCollides(){
//TODO
}
//Which (up)side does it collide with
bool upBoxSideCollides(int side){
if(side==0){
return true;
}
else{
return false;
}
}
//Which (low)side does it collide with
bool lowBoxSideCollides(int side){
if(side==2){
return true;
}
else{
return false;
}
}
//Which (right)side does it collide with
bool rightBoxSideCollides(int side){
if(side==1){
return true;
}
else{
return false;
}
}
//Which (left)side does it collide with
bool leftBoxSideCollides(int side){
if(side==3){
return true;
}
else{
return false;
}
}
};<|endoftext|> |
<commit_before>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <alpaka/vec/Vec.hpp> // Vec
#include <alpaka/dim/Traits.hpp> // Dim
#include <alpaka/meta/IntegerSequence.hpp> // meta::IndexSequence
#include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC
#if !BOOST_ARCH_CUDA_DEVICE
#include <boost/core/ignore_unused.hpp> // boost::ignore_unused
#endif
namespace alpaka
{
namespace meta
{
namespace detail
{
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
typename TIndexSequence>
struct NdLoop;
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<>
struct NdLoop<
meta::IndexSequence<>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
#if !BOOST_ARCH_CUDA_DEVICE
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
#else
TIndex &,
TExtentVec const &,
TFnObj const &)
#endif
-> void
{
#if !BOOST_ARCH_CUDA_DEVICE
boost::ignore_unused(idx);
boost::ignore_unused(extent);
boost::ignore_unused(f);
#endif
}
};
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
std::size_t Tdim>
struct NdLoop<
meta::IndexSequence<Tdim>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
-> void
{
static_assert(
dim::Dim<TIndex>::value > 0u,
"The dimension given to ndLoopIncIdx has to be larger than zero!");
static_assert(
dim::Dim<TIndex>::value == dim::Dim<TExtentVec>::value,
"The dimensions of the iteration vector and the extent vector have to be identical!");
static_assert(
dim::Dim<TIndex>::value > Tdim,
"The current dimension has to be in the rang [0,dim-1]!");
for(idx[Tdim] = 0u; idx[Tdim] < extent[Tdim]; ++idx[Tdim])
{
f(idx);
}
}
};
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
std::size_t Tdim,
std::size_t... Tdims>
struct NdLoop<
meta::IndexSequence<Tdim, Tdims...>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
-> void
{
static_assert(
dim::Dim<TIndex>::value > 0u,
"The dimension given to ndLoop has to be larger than zero!");
static_assert(
dim::Dim<TIndex>::value == dim::Dim<TExtentVec>::value,
"The dimensions of the iteration vector and the extent vector have to be identical!");
static_assert(
dim::Dim<TIndex>::value > Tdim,
"The current dimension has to be in the rang [0,dim-1]!");
for(idx[Tdim] = 0u; idx[Tdim] < extent[Tdim]; ++idx[Tdim])
{
detail::NdLoop<
meta::IndexSequence<Tdims...>>
::template ndLoop(
idx,
extent,
f);
}
}
};
}
//-----------------------------------------------------------------------------
//! Loops over an n-dimensional iteration index variable calling f(idx, args...) for each iteration.
//! The loops are nested in the order given by the IndexSequence with the first element being the outermost and the last index the innermost loop.
//!
#if !BOOST_ARCH_CUDA_DEVICE
//! \param indexSequence A sequence of indices being a permutation of the values [0, dim-1], where every values occurs at most once.
#endif
//! \param extent N-dimensional loop extent.
//! \param f The function called at each iteration.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TExtentVec,
typename TFnObj,
std::size_t... Tdims>
ALPAKA_FN_HOST_ACC auto ndLoop(
#if !BOOST_ARCH_CUDA_DEVICE
meta::IndexSequence<Tdims...> const & indexSequence,
#else
meta::IndexSequence<Tdims...> const &,
#endif
TExtentVec const & extent,
TFnObj const & f)
-> void
{
#if !BOOST_ARCH_CUDA_DEVICE
boost::ignore_unused(indexSequence);
#endif
static_assert(
dim::Dim<TExtentVec>::value > 0u,
"The dimension of the extent given to ndLoop has to be larger than zero!");
static_assert(
meta::IntegerSequenceValuesInRange<meta::IndexSequence<Tdims...>, std::size_t, 0, dim::Dim<TExtentVec>::value>::value,
"The values in the IndexSequence have to in the rang [0,dim-1]!");
static_assert(
meta::IntegerSequenceValuesUnique<meta::IndexSequence<Tdims...>>::value,
"The values in the IndexSequence have to be unique!");
auto idx(
vec::Vec<dim::Dim<TExtentVec>, size::Size<TExtentVec>>::zeros());
detail::NdLoop<
meta::IndexSequence<Tdims...>>
::template ndLoop(
idx,
extent,
f);
}
//-----------------------------------------------------------------------------
//! Loops over an n-dimensional iteration index variable calling f(idx, args...) for each iteration.
//! The loops are nested from index zero outmost to index (dim-1) innermost.
//!
//! \param extent N-dimensional loop extent.
//! \param f The function called at each iteration.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC auto ndLoopIncIdx(
TExtentVec const & extent,
TFnObj const & f)
-> void
{
ndLoop(
meta::MakeIndexSequence<dim::Dim<TExtentVec>::value>(),
extent,
f);
}
}
}
<commit_msg>fix comment<commit_after>/**
* \file
* Copyright 2014-2015 Benjamin Worpitz
*
* This file is part of alpaka.
*
* alpaka is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* alpaka is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with alpaka.
* If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <alpaka/vec/Vec.hpp> // Vec
#include <alpaka/dim/Traits.hpp> // Dim
#include <alpaka/meta/IntegerSequence.hpp> // meta::IndexSequence
#include <alpaka/core/Common.hpp> // ALPAKA_FN_HOST_ACC
#if !BOOST_ARCH_CUDA_DEVICE
#include <boost/core/ignore_unused.hpp> // boost::ignore_unused
#endif
namespace alpaka
{
namespace meta
{
namespace detail
{
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
typename TIndexSequence>
struct NdLoop;
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<>
struct NdLoop<
meta::IndexSequence<>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
#if !BOOST_ARCH_CUDA_DEVICE
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
#else
TIndex &,
TExtentVec const &,
TFnObj const &)
#endif
-> void
{
#if !BOOST_ARCH_CUDA_DEVICE
boost::ignore_unused(idx);
boost::ignore_unused(extent);
boost::ignore_unused(f);
#endif
}
};
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
std::size_t Tdim>
struct NdLoop<
meta::IndexSequence<Tdim>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
-> void
{
static_assert(
dim::Dim<TIndex>::value > 0u,
"The dimension given to ndLoopIncIdx has to be larger than zero!");
static_assert(
dim::Dim<TIndex>::value == dim::Dim<TExtentVec>::value,
"The dimensions of the iteration vector and the extent vector have to be identical!");
static_assert(
dim::Dim<TIndex>::value > Tdim,
"The current dimension has to be in the rang [0,dim-1]!");
for(idx[Tdim] = 0u; idx[Tdim] < extent[Tdim]; ++idx[Tdim])
{
f(idx);
}
}
};
//#############################################################################
//! N-dimensional loop iteration template.
//#############################################################################
template<
std::size_t Tdim,
std::size_t... Tdims>
struct NdLoop<
meta::IndexSequence<Tdim, Tdims...>>
{
//-----------------------------------------------------------------------------
//!
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TIndex,
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC static auto ndLoop(
TIndex & idx,
TExtentVec const & extent,
TFnObj const & f)
-> void
{
static_assert(
dim::Dim<TIndex>::value > 0u,
"The dimension given to ndLoop has to be larger than zero!");
static_assert(
dim::Dim<TIndex>::value == dim::Dim<TExtentVec>::value,
"The dimensions of the iteration vector and the extent vector have to be identical!");
static_assert(
dim::Dim<TIndex>::value > Tdim,
"The current dimension has to be in the rang [0,dim-1]!");
for(idx[Tdim] = 0u; idx[Tdim] < extent[Tdim]; ++idx[Tdim])
{
detail::NdLoop<
meta::IndexSequence<Tdims...>>
::template ndLoop(
idx,
extent,
f);
}
}
};
}
//-----------------------------------------------------------------------------
//! Loops over an n-dimensional iteration index variable calling f(idx, args...) for each iteration.
//! The loops are nested in the order given by the IndexSequence with the first element being the outermost and the last index the innermost loop.
//!
#if !BOOST_ARCH_CUDA_DEVICE
//! \param indexSequence A sequence of indices being a permutation of the values [0, dim-1], where every values occurs at most once.
#endif
//! \param extent N-dimensional loop extent.
//! \param f The function called at each iteration.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TExtentVec,
typename TFnObj,
std::size_t... Tdims>
ALPAKA_FN_HOST_ACC auto ndLoop(
#if !BOOST_ARCH_CUDA_DEVICE
meta::IndexSequence<Tdims...> const & indexSequence,
#else
meta::IndexSequence<Tdims...> const &,
#endif
TExtentVec const & extent,
TFnObj const & f)
-> void
{
#if !BOOST_ARCH_CUDA_DEVICE
boost::ignore_unused(indexSequence);
#endif
static_assert(
dim::Dim<TExtentVec>::value > 0u,
"The dimension of the extent given to ndLoop has to be larger than zero!");
static_assert(
meta::IntegerSequenceValuesInRange<meta::IndexSequence<Tdims...>, std::size_t, 0, dim::Dim<TExtentVec>::value>::value,
"The values in the IndexSequence have to be in the range [0,dim-1]!");
static_assert(
meta::IntegerSequenceValuesUnique<meta::IndexSequence<Tdims...>>::value,
"The values in the IndexSequence have to be unique!");
auto idx(
vec::Vec<dim::Dim<TExtentVec>, size::Size<TExtentVec>>::zeros());
detail::NdLoop<
meta::IndexSequence<Tdims...>>
::template ndLoop(
idx,
extent,
f);
}
//-----------------------------------------------------------------------------
//! Loops over an n-dimensional iteration index variable calling f(idx, args...) for each iteration.
//! The loops are nested from index zero outmost to index (dim-1) innermost.
//!
//! \param extent N-dimensional loop extent.
//! \param f The function called at each iteration.
//-----------------------------------------------------------------------------
ALPAKA_NO_HOST_ACC_WARNING
template<
typename TExtentVec,
typename TFnObj>
ALPAKA_FN_HOST_ACC auto ndLoopIncIdx(
TExtentVec const & extent,
TFnObj const & f)
-> void
{
ndLoop(
meta::MakeIndexSequence<dim::Dim<TExtentVec>::value>(),
extent,
f);
}
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: monst.cxx,v $
* $Revision: 1.6 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include <stdlib.h>
#include "monst.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include "shapes.hxx"
#include <vcl/outdev.hxx>
#include <tools/time.hxx>
Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) :
GegnerListe(0,0),
pBitMonst1(0L),
pBitMonst2(0L),
pBitMonst3(0L),
pBitMonst4(0L),
pBitMonst1b(0L),
pBitMonst2b(0L),
pBitMonst3b(0L),
pBitMonst4b(0L),
pBitMonst5(0L),
pBitMonst5a(0L),
pBitMonst5b(0L),
pBombe(pBom),
pFighter(pFig),
bDown(FALSE),
bLeft(TRUE),
bAuseMode(FALSE),
nDown(MOVEY)
{
pBitMonst1 = ImplLoadImage( MONSTER1, pRes );
pBitMonst2 = ImplLoadImage( MONSTER2, pRes );
pBitMonst3 = ImplLoadImage( MONSTER3, pRes );
pBitMonst4 = ImplLoadImage( MONSTER4, pRes );
pBitMonst1b = ImplLoadImage( MONSTER1B, pRes );
pBitMonst2b = ImplLoadImage( MONSTER2B, pRes );
pBitMonst3b = ImplLoadImage( MONSTER3B, pRes );
pBitMonst4b = ImplLoadImage( MONSTER4B, pRes );
pBitMonst5 = ImplLoadImage( MONSTER5, pRes );
pBitMonst5a = ImplLoadImage( MONSTER5A, pRes );
pBitMonst5b = ImplLoadImage( MONSTER5B, pRes );
aOutSize = pBitMonst1->GetSizePixel();
SetRandWert( 100 );
}
Gegner::~Gegner()
{
ClearAll();
delete pBitMonst1;
delete pBitMonst2;
delete pBitMonst3;
delete pBitMonst4;
delete pBitMonst1b;
delete pBitMonst2b;
delete pBitMonst3b;
delete pBitMonst4b;
delete pBitMonst5;
delete pBitMonst5a;
delete pBitMonst5b;
}
void Gegner::InsertGegner(USHORT nType, USHORT x, USHORT y)
{
Gegner_Impl* pWork = new Gegner_Impl();
pWork->aType = (enum GegnerType)nType;
pWork->aMode = MOVE1;
pWork->aXY = Point(x,y);
pWork->aX = x;
pWork->nHits = 0;
switch(pWork->aType)
{
case GEGNER1:
pWork->nPoints = 50;
pWork->nMaxHits = 1;
break;
case GEGNER2:
pWork->nPoints = 75;
pWork->nMaxHits = 2;
break;
case GEGNER3:
pWork->nPoints = 150;
pWork->nMaxHits = 3;
break;
case GEGNER4:
pWork->nPoints = 225;
pWork->nMaxHits = 5;
break;
case GEGNER5:
pWork->nPoints = 500;
pWork->nMaxHits = 3;
pWork->aMode = HIDE;
break;
}
Insert(pWork);
}
void Gegner::Move()
{
BOOL bNextDown = FALSE;
unsigned long i;
for(i=0; i<Count(); i++)
{
if(bDown)
{
SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown));
}
else if(bLeft)
{
SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i)));
if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX)
bNextDown = TRUE;
}
else
{
SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i)));
if(GegnerX(i)-MOVEX <= 0)
bNextDown = TRUE;
}
}
if(bDown)
{
if(bLeft)
bLeft = FALSE;
else
bLeft = TRUE;
}
bDown = FALSE;
if(bNextDown)
bDown = TRUE;
}
void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart)
{
Time aTime;
srand(aTime.GetTime() % 1000);
nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X();
unsigned long i;
for(i=0; i<Count();i++)
{
switch(GegType(i))
{
case GEGNER1:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst1);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst1b);
SetMode(i,MOVE1);
}
break;
case GEGNER2:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst2);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst2b);
SetMode(i,MOVE1);
}
break;
case GEGNER3:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst3);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst3b);
SetMode(i,MOVE1);
}
break;
case GEGNER4:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst4);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst4b);
SetMode(i,MOVE1);
}
break;
case GEGNER5:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE2);
}
}
if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5a);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE3);
}
}
if(GegMode(i) == MOVE3)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5b);
DecDelay(i);
pBombe->InsertBombe(Point(GegnerX(i),
GegnerY(i)+aOutSize.Height()/2));
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE4);
}
}
if(GegMode(i) == MOVE4)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5a);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
if ( rand() % 5 < 2 )
SetMode(i,MOVE3);
else
SetMode(i,MOVE5);
}
}
if(GegMode(i) == MOVE5)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5);
DecDelay(i);
if(!GetDelay(i))
{
if ( rand() % 5 < 2 )
{
SetMode(i,MOVE1);
SetDelay(i);
}
else
SetMode(i,HIDE);
}
}
break;
}
SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY),
Point(GegnerX(i)+aOutSize.Width()-KOLLXY,
GegnerY(i)+aOutSize.Height()-KOLLXY)));
if(bAuseMode && GegMode(i) == MOVE1)
{
if(GegnerX(i) < pFighter->GetHalf() &&
GegnerX(i)+aOutSize.Width() > pFighter->GetHalf())
pBombe->InsertBombe(Point(pFighter->GetPoint().X(),
GegnerY(i)+aOutSize.Height()/2));
}
else
{
int ran = rand();
int nScaledLimit;
// NOTE: the two expressions are the same in floatingpoint but not in integer
int nRandMax = RAND_MAX;
if ( nRandMax < 32767 )
nScaledLimit = GetRandWert() / ( 32767 / nRandMax );
else
nScaledLimit = GetRandWert() * ( nRandMax / 32767);
if(GegType(i) != GEGNER5)
{
if(ran < nScaledLimit )
pBombe->InsertBombe(Point(GegnerX(i),
GegnerY(i)+aOutSize.Height()/2));
}
else if(GegMode(i) == HIDE)
{
if(ran < (nScaledLimit *3) /2)
{
SetMode(i,MOVE1);
SetDelay(i);
}
}
}
}
Move();
}
long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl)
{
long nWert = -1;
Rectangle aWork;
unsigned long i;
for( i=0; i<Count();i++)
{
aWork = GegnerKoll(i);
if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) &&
(aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
GegMode(i) != DELETED)
{
nWert = 0;
if(GegnerDest(i))
{
SetMode(i,DELETED);
if(nWert == -1)
nWert = GegnerPoints(i);
else
nWert += GegnerPoints(i);
}
pExpl->InsertExpl(GegnerPos(i));
}
}
return nWert;
}
BOOL Gegner::GegnerDest(long nWert)
{
GegnerHit(nWert);
if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits)
return TRUE;
return FALSE;
}
Rectangle Gegner::GetKoll(long nWert)
{
return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2,
GegnerY(nWert)+aOutSize.Height()),
Point(GegnerX(nWert)+aOutSize.Width()/2,
GegnerY(nWert)+aOutSize.Height()));
}
BOOL Gegner::RemoveGegner()
{
for(long i=Count()-1; i>=0; i--)
{
Gegner_Impl* pWork = GetObject(i);
if(pWork->aMode == DELETED)
{
Remove(pWork);
delete pWork;
}
}
if(Count())
return FALSE;
else
return TRUE;
}
void Gegner::ClearAll()
{
unsigned long i;
for( i=0; i<Count(); i++ )
delete GetObject(i);
Clear();
}
<commit_msg>INTEGRATION: CWS pj90 (1.5.160); FILE MERGED 2008/04/19 08:44:44 pjanik 1.5.160.2: RESYNC: (1.5-1.6); FILE MERGED 2008/04/19 08:39:45 pjanik 1.5.160.1: #i85735#: Use long instead of USHORT.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: monst.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include <stdlib.h>
#include "monst.hxx"
#include "invader.hrc"
#include "expl.hxx"
#include "shapes.hxx"
#include <vcl/outdev.hxx>
#include <tools/time.hxx>
Gegner::Gegner(Fighter* pFig, Bombe* pBom, ResMgr* pRes) :
GegnerListe(0,0),
pBitMonst1(0L),
pBitMonst2(0L),
pBitMonst3(0L),
pBitMonst4(0L),
pBitMonst1b(0L),
pBitMonst2b(0L),
pBitMonst3b(0L),
pBitMonst4b(0L),
pBitMonst5(0L),
pBitMonst5a(0L),
pBitMonst5b(0L),
pBombe(pBom),
pFighter(pFig),
bDown(FALSE),
bLeft(TRUE),
bAuseMode(FALSE),
nDown(MOVEY)
{
pBitMonst1 = ImplLoadImage( MONSTER1, pRes );
pBitMonst2 = ImplLoadImage( MONSTER2, pRes );
pBitMonst3 = ImplLoadImage( MONSTER3, pRes );
pBitMonst4 = ImplLoadImage( MONSTER4, pRes );
pBitMonst1b = ImplLoadImage( MONSTER1B, pRes );
pBitMonst2b = ImplLoadImage( MONSTER2B, pRes );
pBitMonst3b = ImplLoadImage( MONSTER3B, pRes );
pBitMonst4b = ImplLoadImage( MONSTER4B, pRes );
pBitMonst5 = ImplLoadImage( MONSTER5, pRes );
pBitMonst5a = ImplLoadImage( MONSTER5A, pRes );
pBitMonst5b = ImplLoadImage( MONSTER5B, pRes );
aOutSize = pBitMonst1->GetSizePixel();
SetRandWert( 100 );
}
Gegner::~Gegner()
{
ClearAll();
delete pBitMonst1;
delete pBitMonst2;
delete pBitMonst3;
delete pBitMonst4;
delete pBitMonst1b;
delete pBitMonst2b;
delete pBitMonst3b;
delete pBitMonst4b;
delete pBitMonst5;
delete pBitMonst5a;
delete pBitMonst5b;
}
void Gegner::InsertGegner(long nType, long x, long y)
{
Gegner_Impl* pWork = new Gegner_Impl();
pWork->aType = (enum GegnerType)nType;
pWork->aMode = MOVE1;
pWork->aXY = Point(x,y);
pWork->aX = x;
pWork->nHits = 0;
switch(pWork->aType)
{
case GEGNER1:
pWork->nPoints = 50;
pWork->nMaxHits = 1;
break;
case GEGNER2:
pWork->nPoints = 75;
pWork->nMaxHits = 2;
break;
case GEGNER3:
pWork->nPoints = 150;
pWork->nMaxHits = 3;
break;
case GEGNER4:
pWork->nPoints = 225;
pWork->nMaxHits = 5;
break;
case GEGNER5:
pWork->nPoints = 500;
pWork->nMaxHits = 3;
pWork->aMode = HIDE;
break;
}
Insert(pWork);
}
void Gegner::Move()
{
BOOL bNextDown = FALSE;
unsigned long i;
for(i=0; i<Count(); i++)
{
if(bDown)
{
SetGegnerPos(i,Point(GegnerX(i),GegnerY(i)+nDown));
}
else if(bLeft)
{
SetGegnerPos(i,Point(GegnerX(i)+MOVEX,GegnerY(i)));
if(GegnerX(i)+MOVEX+aOutSize.Width() > nMaxX)
bNextDown = TRUE;
}
else
{
SetGegnerPos(i,Point(GegnerX(i)-MOVEX,GegnerY(i)));
if(GegnerX(i)-MOVEX <= 0)
bNextDown = TRUE;
}
}
if(bDown)
{
if(bLeft)
bLeft = FALSE;
else
bLeft = TRUE;
}
bDown = FALSE;
if(bNextDown)
bDown = TRUE;
}
void Gegner::DrawGegner(OutputDevice* pDev,Point* pStart)
{
Time aTime;
srand(aTime.GetTime() % 1000);
nMaxX = pDev->GetOutputSizePixel().Width()-pStart->X();
unsigned long i;
for(i=0; i<Count();i++)
{
switch(GegType(i))
{
case GEGNER1:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst1);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst1b);
SetMode(i,MOVE1);
}
break;
case GEGNER2:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst2);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst2b);
SetMode(i,MOVE1);
}
break;
case GEGNER3:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst3);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst3b);
SetMode(i,MOVE1);
}
break;
case GEGNER4:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst4);
SetMode(i,MOVE2);
}
else if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst4b);
SetMode(i,MOVE1);
}
break;
case GEGNER5:
if(GegMode(i) == MOVE1)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE2);
}
}
if(GegMode(i) == MOVE2)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5a);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE3);
}
}
if(GegMode(i) == MOVE3)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5b);
DecDelay(i);
pBombe->InsertBombe(Point(GegnerX(i),
GegnerY(i)+aOutSize.Height()/2));
if(!GetDelay(i))
{
SetDelay(i);
SetMode(i,MOVE4);
}
}
if(GegMode(i) == MOVE4)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5a);
DecDelay(i);
if(!GetDelay(i))
{
SetDelay(i);
if ( rand() % 5 < 2 )
SetMode(i,MOVE3);
else
SetMode(i,MOVE5);
}
}
if(GegMode(i) == MOVE5)
{
pDev->DrawImage(Point(pStart->X()+GegnerX(i),
pStart->Y()+GegnerY(i)),*pBitMonst5);
DecDelay(i);
if(!GetDelay(i))
{
if ( rand() % 5 < 2 )
{
SetMode(i,MOVE1);
SetDelay(i);
}
else
SetMode(i,HIDE);
}
}
break;
}
SetKoll(i,Rectangle(Point(GegnerX(i)+KOLLXY,GegnerY(i)+KOLLXY),
Point(GegnerX(i)+aOutSize.Width()-KOLLXY,
GegnerY(i)+aOutSize.Height()-KOLLXY)));
if(bAuseMode && GegMode(i) == MOVE1)
{
if(GegnerX(i) < pFighter->GetHalf() &&
GegnerX(i)+aOutSize.Width() > pFighter->GetHalf())
pBombe->InsertBombe(Point(pFighter->GetPoint().X(),
GegnerY(i)+aOutSize.Height()/2));
}
else
{
int ran = rand();
int nScaledLimit;
// NOTE: the two expressions are the same in floatingpoint but not in integer
int nRandMax = RAND_MAX;
if ( nRandMax < 32767 )
nScaledLimit = GetRandWert() / ( 32767 / nRandMax );
else
nScaledLimit = GetRandWert() * ( nRandMax / 32767);
if(GegType(i) != GEGNER5)
{
if(ran < nScaledLimit )
pBombe->InsertBombe(Point(GegnerX(i),
GegnerY(i)+aOutSize.Height()/2));
}
else if(GegMode(i) == HIDE)
{
if(ran < (nScaledLimit *3) /2)
{
SetMode(i,MOVE1);
SetDelay(i);
}
}
}
}
Move();
}
long Gegner::Kollision(Rectangle& rRect, Explosion* pExpl)
{
long nWert = -1;
Rectangle aWork;
unsigned long i;
for( i=0; i<Count();i++)
{
aWork = GegnerKoll(i);
if((aWork.Left() <= rRect.Left() && aWork.Right() >= rRect.Right()) &&
(aWork.Top() <= rRect.Top() && aWork.Bottom() >= rRect.Bottom()) &&
GegMode(i) != DELETED)
{
nWert = 0;
if(GegnerDest(i))
{
SetMode(i,DELETED);
if(nWert == -1)
nWert = GegnerPoints(i);
else
nWert += GegnerPoints(i);
}
pExpl->InsertExpl(GegnerPos(i));
}
}
return nWert;
}
BOOL Gegner::GegnerDest(long nWert)
{
GegnerHit(nWert);
if(GetObject(nWert)->nHits >= GetObject(nWert)->nMaxHits)
return TRUE;
return FALSE;
}
Rectangle Gegner::GetKoll(long nWert)
{
return Rectangle(Point(GegnerX(nWert)+aOutSize.Width()/2,
GegnerY(nWert)+aOutSize.Height()),
Point(GegnerX(nWert)+aOutSize.Width()/2,
GegnerY(nWert)+aOutSize.Height()));
}
BOOL Gegner::RemoveGegner()
{
for(long i=Count()-1; i>=0; i--)
{
Gegner_Impl* pWork = GetObject(i);
if(pWork->aMode == DELETED)
{
Remove(pWork);
delete pWork;
}
}
if(Count())
return FALSE;
else
return TRUE;
}
void Gegner::ClearAll()
{
unsigned long i;
for( i=0; i<Count(); i++ )
delete GetObject(i);
Clear();
}
<|endoftext|> |
<commit_before>#include "properties/QuaternionProperty.h"
#include "i6engine/math/i6eVector.h"
#include "properties/Vec3Property.h"
#include "widgets/PropertyWindow.h"
#include <QLabel>
#include <QDoubleSpinBox>
namespace i6engine {
namespace particleEditor {
namespace properties {
QuaternionProperty::QuaternionProperty(QWidget * par, QString label, QString name, Quaternion value) : Property(par, label, name), _layout(nullptr), _value(value), _vec3Property(nullptr), _doubleSpinBox(nullptr) {
QWidget * widget = new QWidget(this);
Vec3 axis;
double angle;
value.toAxisAngle(axis, angle);
_layout = new QGridLayout(widget);
widget->setLayout(_layout);
_vec3Property = new Vec3Property(widget, "Axis", "Axis", axis.toOgre());
_layout->addWidget(_vec3Property, 0, 0);
connect(_vec3Property, SIGNAL(changed(QString)), this, SLOT(changedValue()));
QLabel * l = new QLabel("Angle", widget);
_layout->addWidget(l, 1, 0);
_doubleSpinBox = new QDoubleSpinBox(this);
_doubleSpinBox->setMinimum(-360.0);
_doubleSpinBox->setMaximum(360.0);
_doubleSpinBox->setValue(angle);
_layout->addWidget(_doubleSpinBox, 2, 0);
connect(_doubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(changedValue()));
horizontalLayout->addWidget(widget);
}
QuaternionProperty::~QuaternionProperty() {
}
void QuaternionProperty::setQuaternion(Quaternion value) {
_value = value;
Vec3 axis;
double angle;
value.toAxisAngle(axis, angle);
_vec3Property->setVector3(axis.toOgre());
_doubleSpinBox->setValue(angle);
}
void QuaternionProperty::changedValue() {
_value = Quaternion(Vec3(_vec3Property->getVector3()), _doubleSpinBox->value());
triggerChangedSignal();
}
} /* namespace properties */
} /* namespace particleEditor */
} /* namespace i6engine */
<commit_msg>ISIXE-1726 fixed size of quaternion property in ParticleEditor<commit_after>#include "properties/QuaternionProperty.h"
#include "i6engine/math/i6eVector.h"
#include "properties/Vec3Property.h"
#include "widgets/PropertyWindow.h"
#include <QLabel>
#include <QDoubleSpinBox>
namespace i6engine {
namespace particleEditor {
namespace properties {
QuaternionProperty::QuaternionProperty(QWidget * par, QString label, QString name, Quaternion value) : Property(par, label, name), _layout(nullptr), _value(value), _vec3Property(nullptr), _doubleSpinBox(nullptr) {
QWidget * widget = new QWidget(this);
Vec3 axis;
double angle;
value.toAxisAngle(axis, angle);
_layout = new QGridLayout(widget);
widget->setLayout(_layout);
_vec3Property = new Vec3Property(widget, "Axis", "Axis", axis.toOgre());
_layout->addWidget(_vec3Property, 0, 0);
connect(_vec3Property, SIGNAL(changed(QString)), this, SLOT(changedValue()));
_vec3Property->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
QLabel * l = new QLabel("Angle", widget);
_layout->addWidget(l, 1, 0);
_doubleSpinBox = new QDoubleSpinBox(this);
_doubleSpinBox->setMinimum(-360.0);
_doubleSpinBox->setMaximum(360.0);
_doubleSpinBox->setValue(angle);
_layout->addWidget(_doubleSpinBox, 2, 0);
connect(_doubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(changedValue()));
l->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
_doubleSpinBox->setSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Fixed);
horizontalLayout->addWidget(widget);
}
QuaternionProperty::~QuaternionProperty() {
}
void QuaternionProperty::setQuaternion(Quaternion value) {
_value = value;
Vec3 axis;
double angle;
value.toAxisAngle(axis, angle);
_vec3Property->setVector3(axis.toOgre());
_doubleSpinBox->setValue(angle);
}
void QuaternionProperty::changedValue() {
_value = Quaternion(Vec3(_vec3Property->getVector3()), _doubleSpinBox->value());
triggerChangedSignal();
}
} /* namespace properties */
} /* namespace particleEditor */
} /* namespace i6engine */
<|endoftext|> |
<commit_before>
#pragma once
#include "http_parser.hpp"
#include "response.hpp"
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <memory>
#include <string>
#include <functional>
#include <iostream>
namespace cinatra
{
typedef std::function<bool(const Request&, Response&)> handler_t;
class Connection
: public std::enable_shared_from_this<Connection>
{
public:
Connection(boost::asio::io_service& service)
:service_(service), socket_(service)
{}
~Connection()
{}
boost::asio::ip::tcp::socket& socket(){ return socket_; }
void start()
{
boost::asio::spawn(service_,
std::bind(&Connection::do_work,
shared_from_this(), std::placeholders::_1));
}
void set_request_handler(handler_t handler)
{
request_handler_ = handler;
}
private:
void do_work(const boost::asio::yield_context& yield)
{
for (;;)
{
try
{
std::array<char, 8192> buffer;
HTTPParser parser;
while (!parser.is_completed())
{
std::size_t n = socket_.async_read_some(boost::asio::buffer(buffer), yield);
if (!parser.feed(buffer.data(), n))
{
// TODO:רõ쳣.
throw std::invalid_argument("bad request");
}
}
Request req = parser.get_request();
bool keep_alive{};
bool close_connection{};
if (parser.check_version(1, 0))
{
// HTTP/1.0
if (req.header.val_ncase_equal("Connetion", "Keep-Alive"))
{
keep_alive = true;
close_connection = false;
}
else
{
keep_alive = false;
close_connection = true;
}
}
else if (parser.check_version(1, 1))
{
// HTTP/1.1
if (req.header.val_ncase_equal("Connetion", "close"))
{
keep_alive = false;
close_connection = true;
}
else if (req.header.val_ncase_equal("Connetion", "Keep-Alive"))
{
keep_alive = true;
close_connection = false;
}
else
{
keep_alive = false;
close_connection = false;
}
if (req.header.get_count("host") == 0)
{
// TODO:רõ쳣.
throw std::invalid_argument("bad request");
}
}
else
{
throw std::invalid_argument("bad request");
}
Response res;
auto self = shared_from_this();
res.direct_write_func_ =
[&yield, self, this]
(const char* data, std::size_t len)->bool
{
boost::system::error_code ec;
boost::asio::async_write(socket_, boost::asio::buffer(data, len), yield[ec]);
if (ec)
{
// TODO: log ec.message().
std::cout << "direct_write_func error" << ec.message() << std::endl;
return false;
}
return true;
};
if (keep_alive)
{
res.header.add("Connetion", "Keep-Alive");
}
bool found = false;
if (request_handler_)
{
found = request_handler_(req, res);
}
//TODO: routerûҵƥģpublic dirǷиļ.
//TODO: ûҵ404.
//ûûָContent-TypeĬótext/html
if (res.header.get_count("Content-Type") == 0)
{
res.header.add("Content-Type", "text/html");
}
if (!res.is_complete_)
{
res.end();
}
if (!res.is_chunked_encoding_)
{
// chunkedӦö.
std::string header_str = res.get_header_str();
boost::asio::async_write(socket_, boost::asio::buffer(header_str), yield);
boost::asio::async_write(socket_, res.buffer_,
boost::asio::transfer_exactly(res.buffer_.size()), yield);
}
if (close_connection)
{
break;
}
}
catch (std::exception& e)
{
// TODO: log err and response 500
std::cout << "error: " << e.what() << std::endl;
break;
}
}
boost::system::error_code ignored_ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
}
private:
boost::asio::io_service& service_;
boost::asio::ip::tcp::socket socket_;
handler_t request_handler_;
};
}
<commit_msg>添加fixme<commit_after>
#pragma once
#include "http_parser.hpp"
#include "response.hpp"
#include <boost/asio.hpp>
#include <boost/asio/spawn.hpp>
#include <memory>
#include <string>
#include <functional>
#include <iostream>
namespace cinatra
{
typedef std::function<bool(const Request&, Response&)> handler_t;
class Connection
: public std::enable_shared_from_this<Connection>
{
public:
Connection(boost::asio::io_service& service)
:service_(service), socket_(service)
{}
~Connection()
{}
boost::asio::ip::tcp::socket& socket(){ return socket_; }
void start()
{
boost::asio::spawn(service_,
std::bind(&Connection::do_work,
shared_from_this(), std::placeholders::_1));
}
void set_request_handler(handler_t handler)
{
request_handler_ = handler;
}
private:
void do_work(const boost::asio::yield_context& yield)
{
for (;;)
{
try
{
std::array<char, 8192> buffer;
HTTPParser parser;
while (!parser.is_completed())
{
std::size_t n = socket_.async_read_some(boost::asio::buffer(buffer), yield);
if (!parser.feed(buffer.data(), n))
{
// TODO:רõ쳣.
throw std::invalid_argument("bad request");
}
}
Request req = parser.get_request();
bool keep_alive{};
bool close_connection{};
if (parser.check_version(1, 0))
{
// HTTP/1.0
if (req.header.val_ncase_equal("Connetion", "Keep-Alive"))
{
keep_alive = true;
close_connection = false;
}
else
{
keep_alive = false;
close_connection = true;
}
}
else if (parser.check_version(1, 1))
{
// HTTP/1.1
if (req.header.val_ncase_equal("Connetion", "close"))
{
keep_alive = false;
close_connection = true;
}
else if (req.header.val_ncase_equal("Connetion", "Keep-Alive"))
{
keep_alive = true;
close_connection = false;
}
else
{
keep_alive = false;
close_connection = false;
}
if (req.header.get_count("host") == 0)
{
// TODO:רõ쳣.
throw std::invalid_argument("bad request");
}
}
else
{
throw std::invalid_argument("bad request");
}
Response res;
auto self = shared_from_this();
res.direct_write_func_ =
[&yield, self, this]
(const char* data, std::size_t len)->bool
{
boost::system::error_code ec;
boost::asio::async_write(socket_, boost::asio::buffer(data, len), yield[ec]);
if (ec)
{
// TODO: log ec.message().
std::cout << "direct_write_func error" << ec.message() << std::endl;
return false;
}
return true;
};
if (keep_alive)
{
res.header.add("Connetion", "Keep-Alive");
}
bool found = false;
if (request_handler_)
{
found = request_handler_(req, res);
}
//TODO: routerûҵƥģpublic dirǷиļ.
//TODO: ûҵ404.
//ûûָContent-TypeĬótext/html
if (res.header.get_count("Content-Type") == 0)
{
res.header.add("Content-Type", "text/html");
}
if (!res.is_complete_)
{
res.end();
}
if (!res.is_chunked_encoding_)
{
// chunkedӦö.
std::string header_str = res.get_header_str();
boost::asio::async_write(socket_, boost::asio::buffer(header_str), yield);
boost::asio::async_write(socket_, res.buffer_,
boost::asio::transfer_exactly(res.buffer_.size()), yield);
}
if (close_connection)
{
break;
}
}
catch (std::exception& e)
{
// FIXME: readõeofʱclose
// TODO: log err and response 500
std::cout << "error: " << e.what() << std::endl;
break;
}
}
boost::system::error_code ignored_ec;
socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
}
private:
boost::asio::io_service& service_;
boost::asio::ip::tcp::socket socket_;
handler_t request_handler_;
};
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.cpp
* CollisionPrevention controller.
*
*/
#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;
CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
ModuleParams(parent)
{
}
CollisionPrevention::~CollisionPrevention()
{
//unadvertise publishers
if (_mavlink_log_pub != nullptr) {
orb_unadvertise(_mavlink_log_pub);
}
}
void CollisionPrevention::_publishConstrainedSetpoint(const Vector2f &original_setpoint,
const Vector2f &adapted_setpoint)
{
collision_constraints_s constraints{}; /**< collision constraints message */
//fill in values
constraints.timestamp = hrt_absolute_time();
constraints.original_setpoint[0] = original_setpoint(0);
constraints.original_setpoint[1] = original_setpoint(1);
constraints.adapted_setpoint[0] = adapted_setpoint(0);
constraints.adapted_setpoint[1] = adapted_setpoint(1);
// publish constraints
if (_constraints_pub != nullptr) {
orb_publish(ORB_ID(collision_constraints), _constraints_pub, &constraints);
} else {
_constraints_pub = orb_advertise(ORB_ID(collision_constraints), &constraints);
}
}
void CollisionPrevention::_publishObstacleDistance(obstacle_distance_s &obstacle)
{
// publish fused obtacle distance message with data from offboard obstacle_distance and distance sensor
if (_obstacle_distance_pub != nullptr) {
orb_publish(ORB_ID(obstacle_distance_fused), _obstacle_distance_pub, &obstacle);
} else {
_obstacle_distance_pub = orb_advertise(ORB_ID(obstacle_distance_fused), &obstacle);
}
}
void CollisionPrevention::_updateOffboardObstacleDistance(obstacle_distance_s &obstacle)
{
_sub_obstacle_distance.update();
const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance.get();
// Update with offboard data if the data is not stale
if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US) {
obstacle = obstacle_distance;
}
}
void CollisionPrevention::_updateDistanceSensor(obstacle_distance_s &obstacle)
{
for (unsigned i = 0; i < ORB_MULTI_MAX_INSTANCES; i++) {
distance_sensor_s distance_sensor;
_sub_distance_sensor[i].copy(&distance_sensor);
// consider only instaces with updated, valid data and orientations useful for collision prevention
if ((hrt_elapsed_time(&distance_sensor.timestamp) < RANGE_STREAM_TIMEOUT_US) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_DOWNWARD_FACING) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_UPWARD_FACING)) {
if (obstacle.increment > 0) {
// data from companion
obstacle.timestamp = math::min(obstacle.timestamp, distance_sensor.timestamp);
obstacle.max_distance = math::max((int)obstacle.max_distance,
(int)distance_sensor.max_distance * 100);
obstacle.min_distance = math::min((int)obstacle.min_distance,
(int)distance_sensor.min_distance * 100);
// since the data from the companion are already in the distances data structure,
// keep the increment that is sent
obstacle.angle_offset = 0.f; //companion not sending this field (needs mavros update)
} else {
obstacle.timestamp = distance_sensor.timestamp;
obstacle.max_distance = distance_sensor.max_distance * 100; // convert to cm
obstacle.min_distance = distance_sensor.min_distance * 100; // convert to cm
memset(&obstacle.distances[0], UINT16_MAX, sizeof(obstacle.distances));
obstacle.increment = math::degrees(distance_sensor.h_fov);
obstacle.angle_offset = 0.f;
}
if ((distance_sensor.current_distance > distance_sensor.min_distance) &&
(distance_sensor.current_distance < distance_sensor.max_distance)) {
float sensor_yaw_body_rad = _sensorOrientationToYawOffset(distance_sensor, obstacle.angle_offset);
matrix::Quatf attitude = Quatf(_sub_vehicle_attitude.get().q);
// convert the sensor orientation from body to local frame in the range [0, 360]
float sensor_yaw_local_deg = math::degrees(wrap_2pi(Eulerf(attitude).psi() + sensor_yaw_body_rad));
// calculate the field of view boundary bin indices
int lower_bound = (int)floor((sensor_yaw_local_deg - math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
int upper_bound = (int)floor((sensor_yaw_local_deg + math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
// if increment is lower than 5deg, use an offset
const int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
if (((lower_bound < 0 || upper_bound < 0) || (lower_bound >= distances_array_size
|| upper_bound >= distances_array_size)) && obstacle.increment < 5.f) {
obstacle.angle_offset = sensor_yaw_local_deg ;
upper_bound = abs(upper_bound - lower_bound);
lower_bound = 0;
}
for (int bin = lower_bound; bin <= upper_bound; ++bin) {
int wrap_bin = bin;
if (wrap_bin < 0) {
// wrap bin index around the array
wrap_bin = (int)floor(360.f / obstacle.increment) + bin;
}
if (wrap_bin >= distances_array_size) {
// wrap bin index around the array
wrap_bin = bin - distances_array_size;
}
// rotate vehicle attitude into the sensor body frame
matrix::Quatf attitude_sensor_frame = attitude;
attitude_sensor_frame.rotate(Vector3f(0.f, 0.f, sensor_yaw_body_rad));
// compensate measurement for vehicle tilt and convert to cm
obstacle.distances[wrap_bin] = math::min((int)obstacle.distances[wrap_bin],
(int)(100 * distance_sensor.current_distance * cosf(Eulerf(attitude_sensor_frame).theta())));
}
}
}
}
_publishObstacleDistance(obstacle);
}
void CollisionPrevention::_calculateConstrainedSetpoint(Vector2f &setpoint,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
obstacle_distance_s obstacle = {};
_updateOffboardObstacleDistance(obstacle);
_updateDistanceSensor(obstacle);
//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
//that way the root does not have to be calculated for every range bin but once at the end.
float setpoint_length = setpoint.norm();
Vector2f setpoint_sqrd = setpoint * setpoint_length;
//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
float max_slide_angle_rad = 0.5f;
if (hrt_elapsed_time(&obstacle.timestamp) < RANGE_STREAM_TIMEOUT_US) {
if (setpoint_length > 0.001f) {
int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
for (int i = 0; i < distances_array_size; i++) {
if (obstacle.distances[i] < obstacle.max_distance &&
obstacle.distances[i] > obstacle.min_distance && (float)i * obstacle.increment < 360.f) {
float distance = obstacle.distances[i] / 100.0f; //convert to meters
float angle = math::radians((float)i * obstacle.increment);
if (obstacle.angle_offset > 0.f) {
angle += math::radians(obstacle.angle_offset);
}
//split current setpoint into parallel and orthogonal components with respect to the current bin direction
Vector2f bin_direction = {cos(angle), sin(angle)};
Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
float sp_parallel = setpoint_sqrd.dot(bin_direction);
float sp_orth = setpoint_sqrd.dot(orth_direction);
float curr_vel_parallel = math::max(0.f, curr_vel.dot(bin_direction));
//calculate max allowed velocity with a P-controller (same gain as in the position controller)
float delay_distance = curr_vel_parallel * _param_mpc_col_prev_dly.get();
float vel_max_posctrl = math::max(0.f,
_param_mpc_xy_p.get() * (distance - _param_mpc_col_prev_d.get() - delay_distance));
float vel_max_sqrd = vel_max_posctrl * vel_max_posctrl;
//limit the setpoint to respect vel_max by subtracting from the parallel component
if (sp_parallel > vel_max_sqrd) {
Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
float setpoint_temp_length = setpoint_temp.norm();
//limit sliding angle
float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);
if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);
if (sp_orth > 0) {
setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;
} else {
setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
}
}
setpoint_sqrd = setpoint_temp;
}
}
}
//take the squared root
if (setpoint_sqrd.norm() > 0.001f) {
setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());
} else {
setpoint.zero();
}
}
} else {
// if distance data are stale, switch to Loiter and disable Collision Prevention
// such that it is still possible to fly in Position Control Mode
_publishVehicleCmdDoLoiter();
mavlink_log_critical(&_mavlink_log_pub, "No range data received, loitering.");
float col_prev_d = -1.f;
param_set(param_find("MPC_COL_PREV_D"), &col_prev_d);
mavlink_log_critical(&_mavlink_log_pub, "Collision Prevention disabled.");
}
}
void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
//calculate movement constraints based on range data
Vector2f new_setpoint = original_setpoint;
_calculateConstrainedSetpoint(new_setpoint, curr_pos, curr_vel);
//warn user if collision prevention starts to interfere
bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
|| new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
|| new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
|| new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);
if (currently_interfering && (currently_interfering != _interfering)) {
mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
}
_interfering = currently_interfering;
_publishConstrainedSetpoint(original_setpoint, new_setpoint);
original_setpoint = new_setpoint;
}
void CollisionPrevention::_publishVehicleCmdDoLoiter()
{
vehicle_command_s command{};
command.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
command.param1 = (float)1; // base mode
command.param3 = (float)0; // sub mode
command.target_system = 1;
command.target_component = 1;
command.source_system = 1;
command.source_component = 1;
command.confirmation = false;
command.from_external = false;
command.param2 = (float)PX4_CUSTOM_MAIN_MODE_AUTO;
command.param3 = (float)PX4_CUSTOM_SUB_MODE_AUTO_LOITER;
// publish the vehicle command
if (_pub_vehicle_command == nullptr) {
_pub_vehicle_command = orb_advertise_queue(ORB_ID(vehicle_command), &command,
vehicle_command_s::ORB_QUEUE_LENGTH);
} else {
orb_publish(ORB_ID(vehicle_command), _pub_vehicle_command, &command);
}
}
<commit_msg>CollisionPrevention: use the maximum timestamp between offboard and distance sensor such that if one of the two fails the vehicle goes into failsafe, do not switch off CollisionPrevention if it fails<commit_after>/****************************************************************************
*
* Copyright (c) 2018 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file CollisionPrevention.cpp
* CollisionPrevention controller.
*
*/
#include <CollisionPrevention/CollisionPrevention.hpp>
using namespace matrix;
using namespace time_literals;
CollisionPrevention::CollisionPrevention(ModuleParams *parent) :
ModuleParams(parent)
{
}
CollisionPrevention::~CollisionPrevention()
{
//unadvertise publishers
if (_mavlink_log_pub != nullptr) {
orb_unadvertise(_mavlink_log_pub);
}
}
void CollisionPrevention::_publishConstrainedSetpoint(const Vector2f &original_setpoint,
const Vector2f &adapted_setpoint)
{
collision_constraints_s constraints{}; /**< collision constraints message */
//fill in values
constraints.timestamp = hrt_absolute_time();
constraints.original_setpoint[0] = original_setpoint(0);
constraints.original_setpoint[1] = original_setpoint(1);
constraints.adapted_setpoint[0] = adapted_setpoint(0);
constraints.adapted_setpoint[1] = adapted_setpoint(1);
// publish constraints
if (_constraints_pub != nullptr) {
orb_publish(ORB_ID(collision_constraints), _constraints_pub, &constraints);
} else {
_constraints_pub = orb_advertise(ORB_ID(collision_constraints), &constraints);
}
}
void CollisionPrevention::_publishObstacleDistance(obstacle_distance_s &obstacle)
{
// publish fused obtacle distance message with data from offboard obstacle_distance and distance sensor
if (_obstacle_distance_pub != nullptr) {
orb_publish(ORB_ID(obstacle_distance_fused), _obstacle_distance_pub, &obstacle);
} else {
_obstacle_distance_pub = orb_advertise(ORB_ID(obstacle_distance_fused), &obstacle);
}
}
void CollisionPrevention::_updateOffboardObstacleDistance(obstacle_distance_s &obstacle)
{
_sub_obstacle_distance.update();
const obstacle_distance_s &obstacle_distance = _sub_obstacle_distance.get();
// Update with offboard data if the data is not stale
if (hrt_elapsed_time(&obstacle_distance.timestamp) < RANGE_STREAM_TIMEOUT_US) {
obstacle = obstacle_distance;
}
}
void CollisionPrevention::_updateDistanceSensor(obstacle_distance_s &obstacle)
{
for (unsigned i = 0; i < ORB_MULTI_MAX_INSTANCES; i++) {
distance_sensor_s distance_sensor;
_sub_distance_sensor[i].copy(&distance_sensor);
// consider only instaces with updated, valid data and orientations useful for collision prevention
if ((hrt_elapsed_time(&distance_sensor.timestamp) < RANGE_STREAM_TIMEOUT_US) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_DOWNWARD_FACING) &&
(distance_sensor.orientation != distance_sensor_s::ROTATION_UPWARD_FACING)) {
if (obstacle.increment > 0) {
// data from companion
obstacle.timestamp = math::max(obstacle.timestamp, distance_sensor.timestamp);
obstacle.max_distance = math::max((int)obstacle.max_distance,
(int)distance_sensor.max_distance * 100);
obstacle.min_distance = math::min((int)obstacle.min_distance,
(int)distance_sensor.min_distance * 100);
// since the data from the companion are already in the distances data structure,
// keep the increment that is sent
obstacle.angle_offset = 0.f; //companion not sending this field (needs mavros update)
} else {
obstacle.timestamp = distance_sensor.timestamp;
obstacle.max_distance = distance_sensor.max_distance * 100; // convert to cm
obstacle.min_distance = distance_sensor.min_distance * 100; // convert to cm
memset(&obstacle.distances[0], UINT16_MAX, sizeof(obstacle.distances));
obstacle.increment = math::degrees(distance_sensor.h_fov);
obstacle.angle_offset = 0.f;
}
if ((distance_sensor.current_distance > distance_sensor.min_distance) &&
(distance_sensor.current_distance < distance_sensor.max_distance)) {
float sensor_yaw_body_rad = _sensorOrientationToYawOffset(distance_sensor, obstacle.angle_offset);
matrix::Quatf attitude = Quatf(_sub_vehicle_attitude.get().q);
// convert the sensor orientation from body to local frame in the range [0, 360]
float sensor_yaw_local_deg = math::degrees(wrap_2pi(Eulerf(attitude).psi() + sensor_yaw_body_rad));
// calculate the field of view boundary bin indices
int lower_bound = (int)floor((sensor_yaw_local_deg - math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
int upper_bound = (int)floor((sensor_yaw_local_deg + math::degrees(distance_sensor.h_fov / 2.0f)) /
obstacle.increment);
// if increment is lower than 5deg, use an offset
const int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
if (((lower_bound < 0 || upper_bound < 0) || (lower_bound >= distances_array_size
|| upper_bound >= distances_array_size)) && obstacle.increment < 5.f) {
obstacle.angle_offset = sensor_yaw_local_deg ;
upper_bound = abs(upper_bound - lower_bound);
lower_bound = 0;
}
for (int bin = lower_bound; bin <= upper_bound; ++bin) {
int wrap_bin = bin;
if (wrap_bin < 0) {
// wrap bin index around the array
wrap_bin = (int)floor(360.f / obstacle.increment) + bin;
}
if (wrap_bin >= distances_array_size) {
// wrap bin index around the array
wrap_bin = bin - distances_array_size;
}
// rotate vehicle attitude into the sensor body frame
matrix::Quatf attitude_sensor_frame = attitude;
attitude_sensor_frame.rotate(Vector3f(0.f, 0.f, sensor_yaw_body_rad));
// compensate measurement for vehicle tilt and convert to cm
obstacle.distances[wrap_bin] = math::min((int)obstacle.distances[wrap_bin],
(int)(100 * distance_sensor.current_distance * cosf(Eulerf(attitude_sensor_frame).theta())));
}
}
}
}
_publishObstacleDistance(obstacle);
}
void CollisionPrevention::_calculateConstrainedSetpoint(Vector2f &setpoint,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
obstacle_distance_s obstacle = {};
_updateOffboardObstacleDistance(obstacle);
_updateDistanceSensor(obstacle);
//The maximum velocity formula contains a square root, therefore the whole calculation is done with squared norms.
//that way the root does not have to be calculated for every range bin but once at the end.
float setpoint_length = setpoint.norm();
Vector2f setpoint_sqrd = setpoint * setpoint_length;
//Limit the deviation of the adapted setpoint from the originally given joystick input (slightly less than 90 degrees)
float max_slide_angle_rad = 0.5f;
if (hrt_elapsed_time(&obstacle.timestamp) < RANGE_STREAM_TIMEOUT_US) {
if (setpoint_length > 0.001f) {
int distances_array_size = sizeof(obstacle.distances) / sizeof(obstacle.distances[0]);
for (int i = 0; i < distances_array_size; i++) {
if (obstacle.distances[i] < obstacle.max_distance &&
obstacle.distances[i] > obstacle.min_distance && (float)i * obstacle.increment < 360.f) {
float distance = obstacle.distances[i] / 100.0f; //convert to meters
float angle = math::radians((float)i * obstacle.increment);
if (obstacle.angle_offset > 0.f) {
angle += math::radians(obstacle.angle_offset);
}
//split current setpoint into parallel and orthogonal components with respect to the current bin direction
Vector2f bin_direction = {cos(angle), sin(angle)};
Vector2f orth_direction = {-bin_direction(1), bin_direction(0)};
float sp_parallel = setpoint_sqrd.dot(bin_direction);
float sp_orth = setpoint_sqrd.dot(orth_direction);
float curr_vel_parallel = math::max(0.f, curr_vel.dot(bin_direction));
//calculate max allowed velocity with a P-controller (same gain as in the position controller)
float delay_distance = curr_vel_parallel * _param_mpc_col_prev_dly.get();
float vel_max_posctrl = math::max(0.f,
_param_mpc_xy_p.get() * (distance - _param_mpc_col_prev_d.get() - delay_distance));
float vel_max_sqrd = vel_max_posctrl * vel_max_posctrl;
//limit the setpoint to respect vel_max by subtracting from the parallel component
if (sp_parallel > vel_max_sqrd) {
Vector2f setpoint_temp = setpoint_sqrd - (sp_parallel - vel_max_sqrd) * bin_direction;
float setpoint_temp_length = setpoint_temp.norm();
//limit sliding angle
float angle_diff_temp_orig = acos(setpoint_temp.dot(setpoint) / (setpoint_temp_length * setpoint_length));
float angle_diff_temp_bin = acos(setpoint_temp.dot(bin_direction) / setpoint_temp_length);
if (angle_diff_temp_orig > max_slide_angle_rad && setpoint_temp_length > 0.001f) {
float angle_temp_bin_cropped = angle_diff_temp_bin - (angle_diff_temp_orig - max_slide_angle_rad);
float orth_len = vel_max_sqrd * tan(angle_temp_bin_cropped);
if (sp_orth > 0) {
setpoint_temp = vel_max_sqrd * bin_direction + orth_len * orth_direction;
} else {
setpoint_temp = vel_max_sqrd * bin_direction - orth_len * orth_direction;
}
}
setpoint_sqrd = setpoint_temp;
}
}
}
//take the squared root
if (setpoint_sqrd.norm() > 0.001f) {
setpoint = setpoint_sqrd / std::sqrt(setpoint_sqrd.norm());
} else {
setpoint.zero();
}
}
} else {
// if distance data are stale, switch to Loiter
_publishVehicleCmdDoLoiter();
mavlink_log_critical(&_mavlink_log_pub, "No range data received, loitering.");
}
}
void CollisionPrevention::modifySetpoint(Vector2f &original_setpoint, const float max_speed,
const Vector2f &curr_pos, const Vector2f &curr_vel)
{
//calculate movement constraints based on range data
Vector2f new_setpoint = original_setpoint;
_calculateConstrainedSetpoint(new_setpoint, curr_pos, curr_vel);
//warn user if collision prevention starts to interfere
bool currently_interfering = (new_setpoint(0) < original_setpoint(0) - 0.05f * max_speed
|| new_setpoint(0) > original_setpoint(0) + 0.05f * max_speed
|| new_setpoint(1) < original_setpoint(1) - 0.05f * max_speed
|| new_setpoint(1) > original_setpoint(1) + 0.05f * max_speed);
if (currently_interfering && (currently_interfering != _interfering)) {
mavlink_log_critical(&_mavlink_log_pub, "Collision Warning");
}
_interfering = currently_interfering;
_publishConstrainedSetpoint(original_setpoint, new_setpoint);
original_setpoint = new_setpoint;
}
void CollisionPrevention::_publishVehicleCmdDoLoiter()
{
vehicle_command_s command{};
command.command = vehicle_command_s::VEHICLE_CMD_DO_SET_MODE;
command.param1 = (float)1; // base mode
command.param3 = (float)0; // sub mode
command.target_system = 1;
command.target_component = 1;
command.source_system = 1;
command.source_component = 1;
command.confirmation = false;
command.from_external = false;
command.param2 = (float)PX4_CUSTOM_MAIN_MODE_AUTO;
command.param3 = (float)PX4_CUSTOM_SUB_MODE_AUTO_LOITER;
// publish the vehicle command
if (_pub_vehicle_command == nullptr) {
_pub_vehicle_command = orb_advertise_queue(ORB_ID(vehicle_command), &command,
vehicle_command_s::ORB_QUEUE_LENGTH);
} else {
orb_publish(ORB_ID(vehicle_command), _pub_vehicle_command, &command);
}
}
<|endoftext|> |
<commit_before>//===- ObjectTransformLayerTest.cpp - Unit tests for ObjectTransformLayer -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
#include "llvm/ADT/SmallVector.h"
#include "gtest/gtest.h"
using namespace llvm::orc;
namespace {
// Stand-in for RuntimeDyld::MemoryManager
typedef int MockMemoryManager;
// Stand-in for RuntimeDyld::SymbolResolver
typedef int MockSymbolResolver;
// stand-in for object::ObjectFile
typedef int MockObjectFile;
// stand-in for llvm::MemoryBuffer set
typedef int MockMemoryBufferSet;
// Mock transform that operates on unique pointers to object files, and
// allocates new object files rather than mutating the given ones.
struct AllocatingTransform {
std::unique_ptr<MockObjectFile>
operator()(std::unique_ptr<MockObjectFile> Obj) const {
return std::make_unique<MockObjectFile>(*Obj + 1);
}
};
// Mock base layer for verifying behavior of transform layer.
// Each method "T foo(args)" is accompanied by two auxiliary methods:
// - "void expectFoo(args)", to be called before calling foo on the transform
// layer; saves values of args, which mock layer foo then verifies against.
// - "void verifyFoo(T)", to be called after foo, which verifies that the
// transform layer called the base layer and forwarded any return value.
class MockBaseLayer {
public:
typedef int ObjSetHandleT;
MockBaseLayer() : MockSymbol(nullptr) { resetExpectations(); }
template <typename ObjSetT, typename MemoryManagerPtrT,
typename SymbolResolverPtrT>
ObjSetHandleT addObjectSet(ObjSetT &Objects, MemoryManagerPtrT MemMgr,
SymbolResolverPtrT Resolver) {
EXPECT_EQ(MockManager, *MemMgr) << "MM should pass through";
EXPECT_EQ(MockResolver, *Resolver) << "Resolver should pass through";
int I = 0;
for (auto &ObjPtr : Objects) {
EXPECT_EQ(MockObjects[I++] + 1, *ObjPtr) << "Transform should be applied";
}
EXPECT_EQ(MockObjects.size(), I) << "Number of objects should match";
LastCalled = "addObjectSet";
MockObjSetHandle = 111;
return MockObjSetHandle;
}
template <typename ObjSetT>
void expectAddObjectSet(ObjSetT &Objects, MockMemoryManager *MemMgr,
MockSymbolResolver *Resolver) {
MockManager = *MemMgr;
MockResolver = *Resolver;
for (auto &ObjPtr : Objects) {
MockObjects.push_back(*ObjPtr);
}
}
void verifyAddObjectSet(ObjSetHandleT Returned) {
EXPECT_EQ("addObjectSet", LastCalled);
EXPECT_EQ(MockObjSetHandle, Returned) << "Return should pass through";
resetExpectations();
}
void removeObjectSet(ObjSetHandleT H) {
EXPECT_EQ(MockObjSetHandle, H);
LastCalled = "removeObjectSet";
}
void expectRemoveObjectSet(ObjSetHandleT H) { MockObjSetHandle = H; }
void verifyRemoveObjectSet() {
EXPECT_EQ("removeObjectSet", LastCalled);
resetExpectations();
}
JITSymbol findSymbol(const std::string &Name, bool ExportedSymbolsOnly) {
EXPECT_EQ(MockName, Name) << "Name should pass through";
EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through";
LastCalled = "findSymbol";
MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None);
return MockSymbol;
}
void expectFindSymbol(const std::string &Name, bool ExportedSymbolsOnly) {
MockName = Name;
MockBool = ExportedSymbolsOnly;
}
void verifyFindSymbol(llvm::orc::JITSymbol Returned) {
EXPECT_EQ("findSymbol", LastCalled);
EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress())
<< "Return should pass through";
resetExpectations();
}
JITSymbol findSymbolIn(ObjSetHandleT H, const std::string &Name,
bool ExportedSymbolsOnly) {
EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through";
EXPECT_EQ(MockName, Name) << "Name should pass through";
EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through";
LastCalled = "findSymbolIn";
MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None);
return MockSymbol;
}
void expectFindSymbolIn(ObjSetHandleT H, const std::string &Name,
bool ExportedSymbolsOnly) {
MockObjSetHandle = H;
MockName = Name;
MockBool = ExportedSymbolsOnly;
}
void verifyFindSymbolIn(llvm::orc::JITSymbol Returned) {
EXPECT_EQ("findSymbolIn", LastCalled);
EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress())
<< "Return should pass through";
resetExpectations();
}
void emitAndFinalize(ObjSetHandleT H) {
EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through";
LastCalled = "emitAndFinalize";
}
void expectEmitAndFinalize(ObjSetHandleT H) { MockObjSetHandle = H; }
void verifyEmitAndFinalize() {
EXPECT_EQ("emitAndFinalize", LastCalled);
resetExpectations();
}
void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
TargetAddress TargetAddr) {
EXPECT_EQ(MockObjSetHandle, H);
EXPECT_EQ(MockLocalAddress, LocalAddress);
EXPECT_EQ(MockTargetAddress, TargetAddr);
LastCalled = "mapSectionAddress";
}
void expectMapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
TargetAddress TargetAddr) {
MockObjSetHandle = H;
MockLocalAddress = LocalAddress;
MockTargetAddress = TargetAddr;
}
void verifyMapSectionAddress() {
EXPECT_EQ("mapSectionAddress", LastCalled);
resetExpectations();
}
template <typename OwningMBSet>
void takeOwnershipOfBuffers(ObjSetHandleT H, OwningMBSet MBs) {
EXPECT_EQ(MockObjSetHandle, H);
EXPECT_EQ(MockBufferSet, *MBs);
LastCalled = "takeOwnershipOfBuffers";
}
void expectTakeOwnershipOfBuffers(ObjSetHandleT H, MockMemoryBufferSet *MBs) {
MockObjSetHandle = H;
MockBufferSet = *MBs;
}
void verifyTakeOwnershipOfBuffers() {
EXPECT_EQ("takeOwnershipOfBuffers", LastCalled);
resetExpectations();
}
private:
// Backing fields for remembering parameter/return values
std::string LastCalled;
MockMemoryManager MockManager;
MockSymbolResolver MockResolver;
std::vector<MockObjectFile> MockObjects;
ObjSetHandleT MockObjSetHandle;
std::string MockName;
bool MockBool;
JITSymbol MockSymbol;
const void *MockLocalAddress;
TargetAddress MockTargetAddress;
MockMemoryBufferSet MockBufferSet;
// Clear remembered parameters between calls
void resetExpectations() {
LastCalled = "nothing";
MockManager = 0;
MockResolver = 0;
MockObjects.clear();
MockObjSetHandle = 0;
MockName = "bogus";
MockSymbol = JITSymbol(nullptr);
MockLocalAddress = nullptr;
MockTargetAddress = 0;
MockBufferSet = 0;
}
};
// Test each operation on ObjectTransformLayer.
TEST(ObjectTransformLayerTest, Main) {
MockBaseLayer M;
// Create one object transform layer using a transform (as a functor)
// that allocates new objects, and deals in unique pointers.
ObjectTransformLayer<MockBaseLayer, AllocatingTransform> T1(M);
// Create a second object transform layer using a transform (as a lambda)
// that mutates objects in place, and deals in naked pointers
ObjectTransformLayer<MockBaseLayer,
std::function<MockObjectFile *(MockObjectFile *)>>
T2(M, [](MockObjectFile *Obj) {
++(*Obj);
return Obj;
});
// Instantiate some mock objects to use below
MockObjectFile MockObject1 = 211;
MockObjectFile MockObject2 = 222;
MockMemoryManager MockManager = 233;
MockSymbolResolver MockResolver = 244;
// Test addObjectSet with T1 (allocating, unique pointers)
std::vector<std::unique_ptr<MockObjectFile>> Objs1;
Objs1.push_back(std::make_unique<MockObjectFile>(MockObject1));
Objs1.push_back(std::make_unique<MockObjectFile>(MockObject2));
auto MM = std::make_unique<MockMemoryManager>(MockManager);
auto SR = std::make_unique<MockSymbolResolver>(MockResolver);
M.expectAddObjectSet(Objs1, MM.get(), SR.get());
auto H = T1.addObjectSet(Objs1, std::move(MM), std::move(SR));
M.verifyAddObjectSet(H);
// Test addObjectSet with T2 (mutating, naked pointers)
llvm::SmallVector<MockObjectFile *, 2> Objs2;
Objs2.push_back(&MockObject1);
Objs2.push_back(&MockObject2);
M.expectAddObjectSet(Objs2, &MockManager, &MockResolver);
H = T2.addObjectSet(Objs2, &MockManager, &MockResolver);
M.verifyAddObjectSet(H);
EXPECT_EQ(212, MockObject1) << "Expected mutation";
EXPECT_EQ(223, MockObject2) << "Expected mutation";
// Test removeObjectSet
M.expectRemoveObjectSet(H);
T1.removeObjectSet(H);
M.verifyRemoveObjectSet();
// Test findSymbol
std::string Name = "foo";
bool ExportedOnly = true;
M.expectFindSymbol(Name, ExportedOnly);
JITSymbol Symbol = T2.findSymbol(Name, ExportedOnly);
M.verifyFindSymbol(Symbol);
// Test findSymbolIn
Name = "bar";
ExportedOnly = false;
M.expectFindSymbolIn(H, Name, ExportedOnly);
Symbol = T1.findSymbolIn(H, Name, ExportedOnly);
M.verifyFindSymbolIn(Symbol);
// Test emitAndFinalize
M.expectEmitAndFinalize(H);
T2.emitAndFinalize(H);
M.verifyEmitAndFinalize();
// Test mapSectionAddress
char Buffer[24];
TargetAddress MockAddress = 255;
M.expectMapSectionAddress(H, Buffer, MockAddress);
T1.mapSectionAddress(H, Buffer, MockAddress);
M.verifyMapSectionAddress();
// Test takeOwnershipOfBuffers, using unique pointer to buffer set
auto MockBufferSetPtr = std::make_unique<MockMemoryBufferSet>(366);
M.expectTakeOwnershipOfBuffers(H, MockBufferSetPtr.get());
T2.takeOwnershipOfBuffers(H, std::move(MockBufferSetPtr));
M.verifyTakeOwnershipOfBuffers();
// Test takeOwnershipOfBuffers, using naked pointer to buffer set
MockMemoryBufferSet MockBufferSet = 266;
M.expectTakeOwnershipOfBuffers(H, &MockBufferSet);
T1.takeOwnershipOfBuffers(H, &MockBufferSet);
M.verifyTakeOwnershipOfBuffers();
// Verify transform getter (non-const)
MockObjectFile Mutatee = 277;
MockObjectFile *Out = T2.getTransform()(&Mutatee);
EXPECT_EQ(&Mutatee, Out) << "Expected in-place transform";
EXPECT_EQ(278, Mutatee) << "Expected incrementing transform";
// Verify transform getter (const)
auto OwnedObj = std::make_unique<MockObjectFile>(288);
const auto &T1C = T1;
OwnedObj = T1C.getTransform()(std::move(OwnedObj));
EXPECT_EQ(289, *OwnedObj) << "Expected incrementing transform";
}
}
<commit_msg>Don't use std::make_unique.<commit_after>//===- ObjectTransformLayerTest.cpp - Unit tests for ObjectTransformLayer -===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "llvm/ExecutionEngine/Orc/ObjectTransformLayer.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "gtest/gtest.h"
using namespace llvm::orc;
namespace {
// Stand-in for RuntimeDyld::MemoryManager
typedef int MockMemoryManager;
// Stand-in for RuntimeDyld::SymbolResolver
typedef int MockSymbolResolver;
// stand-in for object::ObjectFile
typedef int MockObjectFile;
// stand-in for llvm::MemoryBuffer set
typedef int MockMemoryBufferSet;
// Mock transform that operates on unique pointers to object files, and
// allocates new object files rather than mutating the given ones.
struct AllocatingTransform {
std::unique_ptr<MockObjectFile>
operator()(std::unique_ptr<MockObjectFile> Obj) const {
return llvm::make_unique<MockObjectFile>(*Obj + 1);
}
};
// Mock base layer for verifying behavior of transform layer.
// Each method "T foo(args)" is accompanied by two auxiliary methods:
// - "void expectFoo(args)", to be called before calling foo on the transform
// layer; saves values of args, which mock layer foo then verifies against.
// - "void verifyFoo(T)", to be called after foo, which verifies that the
// transform layer called the base layer and forwarded any return value.
class MockBaseLayer {
public:
typedef int ObjSetHandleT;
MockBaseLayer() : MockSymbol(nullptr) { resetExpectations(); }
template <typename ObjSetT, typename MemoryManagerPtrT,
typename SymbolResolverPtrT>
ObjSetHandleT addObjectSet(ObjSetT &Objects, MemoryManagerPtrT MemMgr,
SymbolResolverPtrT Resolver) {
EXPECT_EQ(MockManager, *MemMgr) << "MM should pass through";
EXPECT_EQ(MockResolver, *Resolver) << "Resolver should pass through";
size_t I = 0;
for (auto &ObjPtr : Objects) {
EXPECT_EQ(MockObjects[I++] + 1, *ObjPtr) << "Transform should be applied";
}
EXPECT_EQ(MockObjects.size(), I) << "Number of objects should match";
LastCalled = "addObjectSet";
MockObjSetHandle = 111;
return MockObjSetHandle;
}
template <typename ObjSetT>
void expectAddObjectSet(ObjSetT &Objects, MockMemoryManager *MemMgr,
MockSymbolResolver *Resolver) {
MockManager = *MemMgr;
MockResolver = *Resolver;
for (auto &ObjPtr : Objects) {
MockObjects.push_back(*ObjPtr);
}
}
void verifyAddObjectSet(ObjSetHandleT Returned) {
EXPECT_EQ("addObjectSet", LastCalled);
EXPECT_EQ(MockObjSetHandle, Returned) << "Return should pass through";
resetExpectations();
}
void removeObjectSet(ObjSetHandleT H) {
EXPECT_EQ(MockObjSetHandle, H);
LastCalled = "removeObjectSet";
}
void expectRemoveObjectSet(ObjSetHandleT H) { MockObjSetHandle = H; }
void verifyRemoveObjectSet() {
EXPECT_EQ("removeObjectSet", LastCalled);
resetExpectations();
}
JITSymbol findSymbol(const std::string &Name, bool ExportedSymbolsOnly) {
EXPECT_EQ(MockName, Name) << "Name should pass through";
EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through";
LastCalled = "findSymbol";
MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None);
return MockSymbol;
}
void expectFindSymbol(const std::string &Name, bool ExportedSymbolsOnly) {
MockName = Name;
MockBool = ExportedSymbolsOnly;
}
void verifyFindSymbol(llvm::orc::JITSymbol Returned) {
EXPECT_EQ("findSymbol", LastCalled);
EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress())
<< "Return should pass through";
resetExpectations();
}
JITSymbol findSymbolIn(ObjSetHandleT H, const std::string &Name,
bool ExportedSymbolsOnly) {
EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through";
EXPECT_EQ(MockName, Name) << "Name should pass through";
EXPECT_EQ(MockBool, ExportedSymbolsOnly) << "Flag should pass through";
LastCalled = "findSymbolIn";
MockSymbol = JITSymbol(122, llvm::JITSymbolFlags::None);
return MockSymbol;
}
void expectFindSymbolIn(ObjSetHandleT H, const std::string &Name,
bool ExportedSymbolsOnly) {
MockObjSetHandle = H;
MockName = Name;
MockBool = ExportedSymbolsOnly;
}
void verifyFindSymbolIn(llvm::orc::JITSymbol Returned) {
EXPECT_EQ("findSymbolIn", LastCalled);
EXPECT_EQ(MockSymbol.getAddress(), Returned.getAddress())
<< "Return should pass through";
resetExpectations();
}
void emitAndFinalize(ObjSetHandleT H) {
EXPECT_EQ(MockObjSetHandle, H) << "Handle should pass through";
LastCalled = "emitAndFinalize";
}
void expectEmitAndFinalize(ObjSetHandleT H) { MockObjSetHandle = H; }
void verifyEmitAndFinalize() {
EXPECT_EQ("emitAndFinalize", LastCalled);
resetExpectations();
}
void mapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
TargetAddress TargetAddr) {
EXPECT_EQ(MockObjSetHandle, H);
EXPECT_EQ(MockLocalAddress, LocalAddress);
EXPECT_EQ(MockTargetAddress, TargetAddr);
LastCalled = "mapSectionAddress";
}
void expectMapSectionAddress(ObjSetHandleT H, const void *LocalAddress,
TargetAddress TargetAddr) {
MockObjSetHandle = H;
MockLocalAddress = LocalAddress;
MockTargetAddress = TargetAddr;
}
void verifyMapSectionAddress() {
EXPECT_EQ("mapSectionAddress", LastCalled);
resetExpectations();
}
template <typename OwningMBSet>
void takeOwnershipOfBuffers(ObjSetHandleT H, OwningMBSet MBs) {
EXPECT_EQ(MockObjSetHandle, H);
EXPECT_EQ(MockBufferSet, *MBs);
LastCalled = "takeOwnershipOfBuffers";
}
void expectTakeOwnershipOfBuffers(ObjSetHandleT H, MockMemoryBufferSet *MBs) {
MockObjSetHandle = H;
MockBufferSet = *MBs;
}
void verifyTakeOwnershipOfBuffers() {
EXPECT_EQ("takeOwnershipOfBuffers", LastCalled);
resetExpectations();
}
private:
// Backing fields for remembering parameter/return values
std::string LastCalled;
MockMemoryManager MockManager;
MockSymbolResolver MockResolver;
std::vector<MockObjectFile> MockObjects;
ObjSetHandleT MockObjSetHandle;
std::string MockName;
bool MockBool;
JITSymbol MockSymbol;
const void *MockLocalAddress;
TargetAddress MockTargetAddress;
MockMemoryBufferSet MockBufferSet;
// Clear remembered parameters between calls
void resetExpectations() {
LastCalled = "nothing";
MockManager = 0;
MockResolver = 0;
MockObjects.clear();
MockObjSetHandle = 0;
MockName = "bogus";
MockSymbol = JITSymbol(nullptr);
MockLocalAddress = nullptr;
MockTargetAddress = 0;
MockBufferSet = 0;
}
};
// Test each operation on ObjectTransformLayer.
TEST(ObjectTransformLayerTest, Main) {
MockBaseLayer M;
// Create one object transform layer using a transform (as a functor)
// that allocates new objects, and deals in unique pointers.
ObjectTransformLayer<MockBaseLayer, AllocatingTransform> T1(M);
// Create a second object transform layer using a transform (as a lambda)
// that mutates objects in place, and deals in naked pointers
ObjectTransformLayer<MockBaseLayer,
std::function<MockObjectFile *(MockObjectFile *)>>
T2(M, [](MockObjectFile *Obj) {
++(*Obj);
return Obj;
});
// Instantiate some mock objects to use below
MockObjectFile MockObject1 = 211;
MockObjectFile MockObject2 = 222;
MockMemoryManager MockManager = 233;
MockSymbolResolver MockResolver = 244;
// Test addObjectSet with T1 (allocating, unique pointers)
std::vector<std::unique_ptr<MockObjectFile>> Objs1;
Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject1));
Objs1.push_back(llvm::make_unique<MockObjectFile>(MockObject2));
auto MM = llvm::make_unique<MockMemoryManager>(MockManager);
auto SR = llvm::make_unique<MockSymbolResolver>(MockResolver);
M.expectAddObjectSet(Objs1, MM.get(), SR.get());
auto H = T1.addObjectSet(Objs1, std::move(MM), std::move(SR));
M.verifyAddObjectSet(H);
// Test addObjectSet with T2 (mutating, naked pointers)
llvm::SmallVector<MockObjectFile *, 2> Objs2;
Objs2.push_back(&MockObject1);
Objs2.push_back(&MockObject2);
M.expectAddObjectSet(Objs2, &MockManager, &MockResolver);
H = T2.addObjectSet(Objs2, &MockManager, &MockResolver);
M.verifyAddObjectSet(H);
EXPECT_EQ(212, MockObject1) << "Expected mutation";
EXPECT_EQ(223, MockObject2) << "Expected mutation";
// Test removeObjectSet
M.expectRemoveObjectSet(H);
T1.removeObjectSet(H);
M.verifyRemoveObjectSet();
// Test findSymbol
std::string Name = "foo";
bool ExportedOnly = true;
M.expectFindSymbol(Name, ExportedOnly);
JITSymbol Symbol = T2.findSymbol(Name, ExportedOnly);
M.verifyFindSymbol(Symbol);
// Test findSymbolIn
Name = "bar";
ExportedOnly = false;
M.expectFindSymbolIn(H, Name, ExportedOnly);
Symbol = T1.findSymbolIn(H, Name, ExportedOnly);
M.verifyFindSymbolIn(Symbol);
// Test emitAndFinalize
M.expectEmitAndFinalize(H);
T2.emitAndFinalize(H);
M.verifyEmitAndFinalize();
// Test mapSectionAddress
char Buffer[24];
TargetAddress MockAddress = 255;
M.expectMapSectionAddress(H, Buffer, MockAddress);
T1.mapSectionAddress(H, Buffer, MockAddress);
M.verifyMapSectionAddress();
// Test takeOwnershipOfBuffers, using unique pointer to buffer set
auto MockBufferSetPtr = llvm::make_unique<MockMemoryBufferSet>(366);
M.expectTakeOwnershipOfBuffers(H, MockBufferSetPtr.get());
T2.takeOwnershipOfBuffers(H, std::move(MockBufferSetPtr));
M.verifyTakeOwnershipOfBuffers();
// Test takeOwnershipOfBuffers, using naked pointer to buffer set
MockMemoryBufferSet MockBufferSet = 266;
M.expectTakeOwnershipOfBuffers(H, &MockBufferSet);
T1.takeOwnershipOfBuffers(H, &MockBufferSet);
M.verifyTakeOwnershipOfBuffers();
// Verify transform getter (non-const)
MockObjectFile Mutatee = 277;
MockObjectFile *Out = T2.getTransform()(&Mutatee);
EXPECT_EQ(&Mutatee, Out) << "Expected in-place transform";
EXPECT_EQ(278, Mutatee) << "Expected incrementing transform";
// Verify transform getter (const)
auto OwnedObj = llvm::make_unique<MockObjectFile>(288);
const auto &T1C = T1;
OwnedObj = T1C.getTransform()(std::move(OwnedObj));
EXPECT_EQ(289, *OwnedObj) << "Expected incrementing transform";
}
}
<|endoftext|> |
<commit_before>/*
* Copyright 2014-2021 CNRS INRIA
*/
#ifndef __eigenpy_quaternion_hpp__
#define __eigenpy_quaternion_hpp__
#include "eigenpy/eigenpy.hpp"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "eigenpy/exception.hpp"
namespace boost { namespace python { namespace converter {
/// \brief Template specialization of rvalue_from_python_data
template<typename Quaternion>
struct rvalue_from_python_data<Eigen::QuaternionBase<Quaternion> const &>
: rvalue_from_python_data_eigen<Quaternion const &>
{
EIGENPY_RVALUE_FROM_PYTHON_DATA_INIT(Quaternion const &)
};
template <class Quaternion>
struct implicit<Quaternion, Eigen::QuaternionBase<Quaternion> >
{
typedef Quaternion Source;
typedef Eigen::QuaternionBase<Quaternion> Target;
static void* convertible(PyObject* obj)
{
// Find a converter which can produce a Source instance from
// obj. The user has told us that Source can be converted to
// Target, and instantiating construct() below, ensures that
// at compile-time.
return implicit_rvalue_convertible_from_python(obj, registered<Source>::converters)
? obj : 0;
}
static void construct(PyObject* obj, rvalue_from_python_stage1_data* data)
{
void* storage = ((rvalue_from_python_storage<Target>*)data)->storage.bytes;
arg_from_python<Source> get_source(obj);
bool convertible = get_source.convertible();
BOOST_VERIFY(convertible);
new (storage) Source(get_source());
// record successful construction
data->convertible = storage;
}
};
}}} // namespace boost::python::converter
namespace eigenpy
{
class ExceptionIndex : public Exception
{
public:
ExceptionIndex(int index,int imin,int imax) : Exception("")
{
std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<".";
message = oss.str();
}
};
namespace bp = boost::python;
template<typename QuaternionDerived> class QuaternionVisitor;
template<typename Scalar, int Options>
struct call< Eigen::Quaternion<Scalar,Options> >
{
typedef Eigen::Quaternion<Scalar,Options> Quaternion;
static inline void expose()
{
QuaternionVisitor<Quaternion>::expose();
}
static inline bool isApprox(const Quaternion & self, const Quaternion & other,
const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
{
return self.isApprox(other,prec);
}
};
template<typename Quaternion>
class QuaternionVisitor
: public bp::def_visitor< QuaternionVisitor<Quaternion> >
{
typedef Eigen::QuaternionBase<Quaternion> QuaternionBase;
typedef typename QuaternionBase::Scalar Scalar;
typedef typename Quaternion::Coefficients Coefficients;
typedef typename QuaternionBase::Vector3 Vector3;
typedef Coefficients Vector4;
typedef typename QuaternionBase::Matrix3 Matrix3;
typedef typename QuaternionBase::AngleAxisType AngleAxis;
BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxQuaternion_overload,call<Quaternion>::isApprox,2,3)
public:
template<class PyClass>
void visit(PyClass& cl) const
{
cl
.def(bp::init<Matrix3>((bp::arg("self"),bp::arg("R")),
"Initialize from rotation matrix.\n"
"\tR : a rotation matrix 3x3.")[bp::return_value_policy<bp::return_by_value>()])
.def(bp::init<AngleAxis>((bp::arg("self"),bp::arg("aa")),
"Initialize from an angle axis.\n"
"\taa: angle axis object."))
.def(bp::init<Quaternion>((bp::arg("self"),bp::arg("quat")),
"Copy constructor.\n"
"\tquat: a quaternion.")[bp::return_value_policy<bp::return_by_value>()])
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors,
bp::default_call_policies(),
(bp::arg("u"),bp::arg("v"))),
"Initialize from two vectors u and v")
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromOneVector,
bp::default_call_policies(),
(bp::arg("vec4"))),
"Initialize from a vector 4D.\n"
"\tvec4 : a 4D vector representing quaternion coefficients in the order xyzw.")
.def("__init__",bp::make_constructor(&QuaternionVisitor::DefaultConstructor),
"Default constructor")
.def(bp::init<Scalar,Scalar,Scalar,Scalar>
((bp::arg("self"),bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")),
"Initialize from coefficients.\n\n"
"... note:: The order of coefficients is *w*, *x*, *y*, *z*. "
"The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!"))
.add_property("x",
&QuaternionVisitor::getCoeff<0>,
&QuaternionVisitor::setCoeff<0>,"The x coefficient.")
.add_property("y",
&QuaternionVisitor::getCoeff<1>,
&QuaternionVisitor::setCoeff<1>,"The y coefficient.")
.add_property("z",
&QuaternionVisitor::getCoeff<2>,
&QuaternionVisitor::setCoeff<2>,"The z coefficient.")
.add_property("w",
&QuaternionVisitor::getCoeff<3>,
&QuaternionVisitor::setCoeff<3>,"The w coefficient.")
.def("isApprox",
&call<Quaternion>::isApprox,
isApproxQuaternion_overload(bp::args("self","other","prec"),
"Returns true if *this is approximately equal to other, within the precision determined by prec."))
/* --- Methods --- */
.def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs,
bp::arg("self"),
"Returns a vector of the coefficients (x,y,z,w)",
bp::return_internal_reference<>())
.def("matrix",&Quaternion::matrix,
bp::arg("self"),
"Returns an equivalent 3x3 rotation matrix. Similar to toRotationMatrix.")
.def("toRotationMatrix",&Quaternion::toRotationMatrix,
// bp::arg("self"), // Bug in Boost.Python
"Returns an equivalent 3x3 rotation matrix.")
.def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("self"),bp::arg("a"),bp::arg("b"))),
"Set *this to be the quaternion which transforms a into b through a rotation."
,bp::return_self<>())
.def("conjugate",&Quaternion::conjugate,
bp::arg("self"),
"Returns the conjugated quaternion.\n"
"The conjugate of a quaternion represents the opposite rotation.")
.def("inverse",&Quaternion::inverse,
bp::arg("self"),
"Returns the quaternion describing the inverse rotation.")
.def("setIdentity",&Quaternion::setIdentity,
bp::arg("self"),
"Set *this to the idendity rotation.",bp::return_self<>())
.def("norm",&Quaternion::norm,
bp::arg("self"),
"Returns the norm of the quaternion's coefficients.")
.def("normalize",&Quaternion::normalize,
bp::arg("self"),
"Normalizes the quaternion *this.")
.def("normalized",&Quaternion::normalized,
bp::arg("self"),
"Returns a normalized copy of *this.")
.def("squaredNorm",&Quaternion::squaredNorm,
bp::arg("self"),
"Returns the squared norm of the quaternion's coefficients.")
.def("dot",&Quaternion::template dot<Quaternion>,
(bp::arg("self"),bp::arg("other")),
"Returns the dot product of *this with an other Quaternion.\n"
"Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.")
.def("_transformVector",&Quaternion::_transformVector,
(bp::arg("self"),bp::arg("vector")),
"Rotation of a vector by a quaternion.")
.def("vec",&vec,
bp::arg("self"),
"Returns a vector expression of the imaginary part (x,y,z).")
.def("angularDistance",
// (bp::arg("self"),bp::arg("other")), // Bug in Boost.Python
&Quaternion::template angularDistance<Quaternion>,
"Returns the angle (in radian) between two rotations.")
.def("slerp",&slerp,bp::args("self","t","other"),
"Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].")
/* --- Operators --- */
.def(bp::self * bp::self)
.def(bp::self *= bp::self)
.def(bp::self * bp::other<Vector3>())
.def("__eq__",&QuaternionVisitor::__eq__)
.def("__ne__",&QuaternionVisitor::__ne__)
.def("__abs__",&Quaternion::norm)
.def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__")
.def("__setitem__",&QuaternionVisitor::__setitem__)
.def("__getitem__",&QuaternionVisitor::__getitem__)
.def("assign",&assign<Quaternion>,
bp::args("self","quat"),
"Set *this from an quaternion quat and returns a reference to *this.",
bp::return_self<>())
.def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=,
bp::args("self","aa"),
"Set *this from an angle-axis aa and returns a reference to *this.",
bp::return_self<>())
.def("__str__",&print)
.def("__repr__",&print)
// .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>,
// bp::args("a","b"),
// "Returns the quaternion which transform a into b through a rotation.")
.def("FromTwoVectors",&FromTwoVectors,
bp::args("a","b"),
"Returns the quaternion which transforms a into b through a rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("FromTwoVectors")
.def("Identity",&Identity,
"Returns a quaternion representing an identity rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("Identity")
;
}
private:
template<int i>
static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; }
template<int i>
static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; }
static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b)
{ return self.setFromTwoVectors(a,b); }
template<typename OtherQuat>
static Quaternion & assign(Quaternion & self, const OtherQuat & quat)
{ return self = quat; }
static Quaternion* Identity()
{
Quaternion* q(new Quaternion); q->setIdentity();
return q;
}
static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v)
{
Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v);
return q;
}
static Quaternion* DefaultConstructor()
{
return new Quaternion;
}
static Quaternion* FromOneVector(const Vector4& v)
{
Quaternion* q(new Quaternion(v[3],v[0],v[1],v[2]));
return q;
}
static bool __eq__(const Quaternion & u, const Quaternion & v)
{
return u.coeffs() == v.coeffs();
}
static bool __ne__(const Quaternion& u, const Quaternion& v)
{
return !__eq__(u,v);
}
static Scalar __getitem__(const Quaternion & self, int idx)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
return self.coeffs()[idx];
}
static void __setitem__(Quaternion& self, int idx, const Scalar value)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
self.coeffs()[idx] = value;
}
static int __len__() { return 4; }
static Vector3 vec(const Quaternion & self) { return self.vec(); }
static std::string print(const Quaternion & self)
{
std::stringstream ss;
ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl;
return ss.str();
}
static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other)
{ return self.slerp(t,other); }
public:
static void expose()
{
bp::class_<Quaternion>("Quaternion",
"Quaternion representing rotation.\n\n"
"Supported operations "
"('q is a Quaternion, 'v' is a Vector3): "
"'q*q' (rotation composition), "
"'q*=q', "
"'q*v' (rotating 'v' by 'q'), "
"'q==q', 'q!=q', 'q[0..3]'.",
bp::no_init)
.def(QuaternionVisitor<Quaternion>());
// Cast to Eigen::QuaternionBase and vice-versa
bp::implicitly_convertible<Quaternion,QuaternionBase >();
// bp::implicitly_convertible<QuaternionBase,Quaternion >();
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_quaternion_hpp__
<commit_msg>geometry: fix Quaternion init from Eigen::Ref<commit_after>/*
* Copyright 2014-2021 CNRS INRIA
*/
#ifndef __eigenpy_quaternion_hpp__
#define __eigenpy_quaternion_hpp__
#include "eigenpy/eigenpy.hpp"
#include <Eigen/Core>
#include <Eigen/Geometry>
#include "eigenpy/exception.hpp"
namespace boost { namespace python { namespace converter {
/// \brief Template specialization of rvalue_from_python_data
template<typename Quaternion>
struct rvalue_from_python_data<Eigen::QuaternionBase<Quaternion> const &>
: rvalue_from_python_data_eigen<Quaternion const &>
{
EIGENPY_RVALUE_FROM_PYTHON_DATA_INIT(Quaternion const &)
};
template <class Quaternion>
struct implicit<Quaternion, Eigen::QuaternionBase<Quaternion> >
{
typedef Quaternion Source;
typedef Eigen::QuaternionBase<Quaternion> Target;
static void* convertible(PyObject* obj)
{
// Find a converter which can produce a Source instance from
// obj. The user has told us that Source can be converted to
// Target, and instantiating construct() below, ensures that
// at compile-time.
return implicit_rvalue_convertible_from_python(obj, registered<Source>::converters)
? obj : 0;
}
static void construct(PyObject* obj, rvalue_from_python_stage1_data* data)
{
void* storage = ((rvalue_from_python_storage<Target>*)data)->storage.bytes;
arg_from_python<Source> get_source(obj);
bool convertible = get_source.convertible();
BOOST_VERIFY(convertible);
new (storage) Source(get_source());
// record successful construction
data->convertible = storage;
}
};
}}} // namespace boost::python::converter
namespace eigenpy
{
class ExceptionIndex : public Exception
{
public:
ExceptionIndex(int index,int imin,int imax) : Exception("")
{
std::ostringstream oss; oss << "Index " << index << " out of range " << imin << ".."<< imax <<".";
message = oss.str();
}
};
namespace bp = boost::python;
template<typename QuaternionDerived> class QuaternionVisitor;
template<typename Scalar, int Options>
struct call< Eigen::Quaternion<Scalar,Options> >
{
typedef Eigen::Quaternion<Scalar,Options> Quaternion;
static inline void expose()
{
QuaternionVisitor<Quaternion>::expose();
}
static inline bool isApprox(const Quaternion & self, const Quaternion & other,
const Scalar & prec = Eigen::NumTraits<Scalar>::dummy_precision())
{
return self.isApprox(other,prec);
}
};
template<typename Quaternion>
class QuaternionVisitor
: public bp::def_visitor< QuaternionVisitor<Quaternion> >
{
typedef Eigen::QuaternionBase<Quaternion> QuaternionBase;
typedef typename QuaternionBase::Scalar Scalar;
typedef typename Quaternion::Coefficients Coefficients;
typedef typename QuaternionBase::Vector3 Vector3;
typedef Coefficients Vector4;
typedef typename QuaternionBase::Matrix3 Matrix3;
typedef typename QuaternionBase::AngleAxisType AngleAxis;
BOOST_PYTHON_FUNCTION_OVERLOADS(isApproxQuaternion_overload,call<Quaternion>::isApprox,2,3)
public:
template<class PyClass>
void visit(PyClass& cl) const
{
cl
.def(bp::init<Matrix3>((bp::arg("self"),bp::arg("R")),
"Initialize from rotation matrix.\n"
"\tR : a rotation matrix 3x3.")[bp::return_value_policy<bp::return_by_value>()])
.def(bp::init<AngleAxis>((bp::arg("self"),bp::arg("aa")),
"Initialize from an angle axis.\n"
"\taa: angle axis object."))
.def(bp::init<Quaternion>((bp::arg("self"),bp::arg("quat")),
"Copy constructor.\n"
"\tquat: a quaternion.")[bp::return_value_policy<bp::return_by_value>()])
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromTwoVectors,
bp::default_call_policies(),
(bp::arg("u"),bp::arg("v"))),
"Initialize from two vectors u and v")
.def("__init__",bp::make_constructor(&QuaternionVisitor::FromOneVector,
bp::default_call_policies(),
(bp::arg("vec4"))),
"Initialize from a vector 4D.\n"
"\tvec4 : a 4D vector representing quaternion coefficients in the order xyzw.")
.def("__init__",bp::make_constructor(&QuaternionVisitor::DefaultConstructor),
"Default constructor")
.def(bp::init<Scalar,Scalar,Scalar,Scalar>
((bp::arg("self"),bp::arg("w"),bp::arg("x"),bp::arg("y"),bp::arg("z")),
"Initialize from coefficients.\n\n"
"... note:: The order of coefficients is *w*, *x*, *y*, *z*. "
"The [] operator numbers them differently, 0...4 for *x* *y* *z* *w*!"))
.add_property("x",
&QuaternionVisitor::getCoeff<0>,
&QuaternionVisitor::setCoeff<0>,"The x coefficient.")
.add_property("y",
&QuaternionVisitor::getCoeff<1>,
&QuaternionVisitor::setCoeff<1>,"The y coefficient.")
.add_property("z",
&QuaternionVisitor::getCoeff<2>,
&QuaternionVisitor::setCoeff<2>,"The z coefficient.")
.add_property("w",
&QuaternionVisitor::getCoeff<3>,
&QuaternionVisitor::setCoeff<3>,"The w coefficient.")
.def("isApprox",
&call<Quaternion>::isApprox,
isApproxQuaternion_overload(bp::args("self","other","prec"),
"Returns true if *this is approximately equal to other, within the precision determined by prec."))
/* --- Methods --- */
.def("coeffs",(const Vector4 & (Quaternion::*)()const)&Quaternion::coeffs,
bp::arg("self"),
"Returns a vector of the coefficients (x,y,z,w)",
bp::return_internal_reference<>())
.def("matrix",&Quaternion::matrix,
bp::arg("self"),
"Returns an equivalent 3x3 rotation matrix. Similar to toRotationMatrix.")
.def("toRotationMatrix",&Quaternion::toRotationMatrix,
// bp::arg("self"), // Bug in Boost.Python
"Returns an equivalent 3x3 rotation matrix.")
.def("setFromTwoVectors",&setFromTwoVectors,((bp::arg("self"),bp::arg("a"),bp::arg("b"))),
"Set *this to be the quaternion which transforms a into b through a rotation."
,bp::return_self<>())
.def("conjugate",&Quaternion::conjugate,
bp::arg("self"),
"Returns the conjugated quaternion.\n"
"The conjugate of a quaternion represents the opposite rotation.")
.def("inverse",&Quaternion::inverse,
bp::arg("self"),
"Returns the quaternion describing the inverse rotation.")
.def("setIdentity",&Quaternion::setIdentity,
bp::arg("self"),
"Set *this to the idendity rotation.",bp::return_self<>())
.def("norm",&Quaternion::norm,
bp::arg("self"),
"Returns the norm of the quaternion's coefficients.")
.def("normalize",&Quaternion::normalize,
bp::arg("self"),
"Normalizes the quaternion *this.")
.def("normalized",&Quaternion::normalized,
bp::arg("self"),
"Returns a normalized copy of *this.")
.def("squaredNorm",&Quaternion::squaredNorm,
bp::arg("self"),
"Returns the squared norm of the quaternion's coefficients.")
.def("dot",&Quaternion::template dot<Quaternion>,
(bp::arg("self"),bp::arg("other")),
"Returns the dot product of *this with an other Quaternion.\n"
"Geometrically speaking, the dot product of two unit quaternions corresponds to the cosine of half the angle between the two rotations.")
.def("_transformVector",&Quaternion::_transformVector,
(bp::arg("self"),bp::arg("vector")),
"Rotation of a vector by a quaternion.")
.def("vec",&vec,
bp::arg("self"),
"Returns a vector expression of the imaginary part (x,y,z).")
.def("angularDistance",
// (bp::arg("self"),bp::arg("other")), // Bug in Boost.Python
&Quaternion::template angularDistance<Quaternion>,
"Returns the angle (in radian) between two rotations.")
.def("slerp",&slerp,bp::args("self","t","other"),
"Returns the spherical linear interpolation between the two quaternions *this and other at the parameter t in [0;1].")
/* --- Operators --- */
.def(bp::self * bp::self)
.def(bp::self *= bp::self)
.def(bp::self * bp::other<Vector3>())
.def("__eq__",&QuaternionVisitor::__eq__)
.def("__ne__",&QuaternionVisitor::__ne__)
.def("__abs__",&Quaternion::norm)
.def("__len__",&QuaternionVisitor::__len__).staticmethod("__len__")
.def("__setitem__",&QuaternionVisitor::__setitem__)
.def("__getitem__",&QuaternionVisitor::__getitem__)
.def("assign",&assign<Quaternion>,
bp::args("self","quat"),
"Set *this from an quaternion quat and returns a reference to *this.",
bp::return_self<>())
.def("assign",(Quaternion & (Quaternion::*)(const AngleAxis &))&Quaternion::operator=,
bp::args("self","aa"),
"Set *this from an angle-axis aa and returns a reference to *this.",
bp::return_self<>())
.def("__str__",&print)
.def("__repr__",&print)
// .def("FromTwoVectors",&Quaternion::template FromTwoVectors<Vector3,Vector3>,
// bp::args("a","b"),
// "Returns the quaternion which transform a into b through a rotation.")
.def("FromTwoVectors",&FromTwoVectors,
bp::args("a","b"),
"Returns the quaternion which transforms a into b through a rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("FromTwoVectors")
.def("Identity",&Identity,
"Returns a quaternion representing an identity rotation.",
bp::return_value_policy<bp::manage_new_object>())
.staticmethod("Identity")
;
}
private:
template<int i>
static void setCoeff(Quaternion & self, Scalar value) { self.coeffs()[i] = value; }
template<int i>
static Scalar getCoeff(Quaternion & self) { return self.coeffs()[i]; }
static Quaternion & setFromTwoVectors(Quaternion & self, const Vector3 & a, const Vector3 & b)
{ return self.setFromTwoVectors(a,b); }
template<typename OtherQuat>
static Quaternion & assign(Quaternion & self, const OtherQuat & quat)
{ return self = quat; }
static Quaternion* Identity()
{
Quaternion* q(new Quaternion); q->setIdentity();
return q;
}
static Quaternion* FromTwoVectors(const Vector3& u, const Vector3& v)
{
Quaternion* q(new Quaternion); q->setFromTwoVectors(u,v);
return q;
}
static Quaternion* DefaultConstructor()
{
return new Quaternion;
}
static Quaternion* FromOneVector(const Eigen::Ref<Vector4> v)
{
Quaternion* q(new Quaternion(v[3],v[0],v[1],v[2]));
return q;
}
static bool __eq__(const Quaternion & u, const Quaternion & v)
{
return u.coeffs() == v.coeffs();
}
static bool __ne__(const Quaternion& u, const Quaternion& v)
{
return !__eq__(u,v);
}
static Scalar __getitem__(const Quaternion & self, int idx)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
return self.coeffs()[idx];
}
static void __setitem__(Quaternion& self, int idx, const Scalar value)
{
if((idx<0) || (idx>=4)) throw eigenpy::ExceptionIndex(idx,0,3);
self.coeffs()[idx] = value;
}
static int __len__() { return 4; }
static Vector3 vec(const Quaternion & self) { return self.vec(); }
static std::string print(const Quaternion & self)
{
std::stringstream ss;
ss << "(x,y,z,w) = " << self.coeffs().transpose() << std::endl;
return ss.str();
}
static Quaternion slerp(const Quaternion & self, const Scalar t, const Quaternion & other)
{ return self.slerp(t,other); }
public:
static void expose()
{
bp::class_<Quaternion>("Quaternion",
"Quaternion representing rotation.\n\n"
"Supported operations "
"('q is a Quaternion, 'v' is a Vector3): "
"'q*q' (rotation composition), "
"'q*=q', "
"'q*v' (rotating 'v' by 'q'), "
"'q==q', 'q!=q', 'q[0..3]'.",
bp::no_init)
.def(QuaternionVisitor<Quaternion>());
// Cast to Eigen::QuaternionBase and vice-versa
bp::implicitly_convertible<Quaternion,QuaternionBase >();
// bp::implicitly_convertible<QuaternionBase,Quaternion >();
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_quaternion_hpp__
<|endoftext|> |
<commit_before>/*
* @file ellis/core/decoder.hpp
*
* @brief Ellis TBD C++ header.
*/
#pragma once
#ifndef ELLIS_CORE_DECODER_HPP_
#define ELLIS_CORE_DECODER_HPP_
#include <ellis/core/defs.hpp>
#include <ellis/core/disposition.hpp>
#include <ellis/core/err.hpp>
#include <ellis/core/node.hpp>
#include <memory>
namespace ellis {
std::ostream & operator<<(std::ostream & os, const array_node & v);
/**
* This abstract base class (interface) is used to decode/unpack/deserialize
* JSON-encoded data from the provided buffers into a reconstructed in-memory
* ellis node.
*/
class decoder {
public:
/**
* This function is called by the data stream to tell the decoder it may
* decode up to bytecount bytes of data from the provided buffer.
*
* The callee should attempt to decode the given data to construct an ellis
* node, and update the size parameter to specify the number of bytes that
* remain unused and available, if there are any. Whatever bytes are left
* will be reclaimed by the stream for use by the next consumer.
*
* If there has been a non-recoverable error in the decoding process, the
* ERROR status will be returned (with details provided); otherwise, if an
* ellis node has been completely decoded, a status of SUCCESS is returned
* (with node provided); otherwise a status of CONTINUE will be returned (to
* indicate that additional bytes must be provided via additional calls to
* consume_buffer).
*
* If a status of SUCCESS or ERROR is returned, then the decoder must be
* reset before any further calls to consume_buffer().
*/
virtual node_progress consume_buffer(
const byte *buf,
size_t *bytecount) = 0;
/**
* Tell the decoder there are no more bytes coming. The decoder will
* decide whether a node can be created based on prior bytes, in which
* case SUCCESS will be returned (with node provided), or whether
* this would result in a truncated or malformed node, in which case
* ERROR will be returned (with details provided).
*
* @return must be either SUCCESS (with value) or ERROR (with details).
*/
virtual node_progress chop() = 0;
/**
* Reset the encoder to start encoding a new ellis node.
*
* This should result in the same behavior as constructing a new decoder,
* but may be more efficient.
*/
virtual void reset() = 0;
virtual ~decoder() {}
};
} /* namespace ellis */
#endif /* ELLIS_CORE_DECODER_HPP_ */
<commit_msg>include: small doc fix<commit_after>/*
* @file ellis/core/decoder.hpp
*
* @brief Ellis TBD C++ header.
*/
#pragma once
#ifndef ELLIS_CORE_DECODER_HPP_
#define ELLIS_CORE_DECODER_HPP_
#include <ellis/core/defs.hpp>
#include <ellis/core/disposition.hpp>
#include <ellis/core/err.hpp>
#include <ellis/core/node.hpp>
#include <memory>
namespace ellis {
std::ostream & operator<<(std::ostream & os, const array_node & v);
/**
* This abstract base class (interface) is used to decode/unpack/deserialize
* JSON-encoded data from the provided buffers into a reconstructed in-memory
* ellis node.
*/
class decoder {
public:
/**
* This function is called by the data stream to tell the decoder it may
* decode up to bytecount bytes of data from the provided buffer.
*
* The callee should attempt to decode the given data to construct an ellis
* node, and update the bytecount parameter to specify the number of bytes
* that remain unused and available, if there are any. Whatever bytes are
* left will be reclaimed by the stream for use by the next consumer.
*
* If there has been a non-recoverable error in the decoding process, the
* ERROR status will be returned (with details provided); otherwise, if an
* ellis node has been completely decoded, a status of SUCCESS is returned
* (with node provided); otherwise a status of CONTINUE will be returned (to
* indicate that additional bytes must be provided via additional calls to
* consume_buffer).
*
* If a status of SUCCESS or ERROR is returned, then the decoder must be
* reset before any further calls to consume_buffer().
*/
virtual node_progress consume_buffer(
const byte *buf,
size_t *bytecount) = 0;
/**
* Tell the decoder there are no more bytes coming. The decoder will
* decide whether a node can be created based on prior bytes, in which
* case SUCCESS will be returned (with node provided), or whether
* this would result in a truncated or malformed node, in which case
* ERROR will be returned (with details provided).
*
* @return must be either SUCCESS (with value) or ERROR (with details).
*/
virtual node_progress chop() = 0;
/**
* Reset the encoder to start encoding a new ellis node.
*
* This should result in the same behavior as constructing a new decoder,
* but may be more efficient.
*/
virtual void reset() = 0;
virtual ~decoder() {}
};
} /* namespace ellis */
#endif /* ELLIS_CORE_DECODER_HPP_ */
<|endoftext|> |
<commit_before>/*
* WhenFunctor.hpp
*
* Created on: Feb 14, 2014
* Author: eran
*/
#ifndef WHENFUNCTOR_HPP_
#define WHENFUNCTOR_HPP_
#include "fakeit/StubbingImpl.h"
#include "fakeit/Stubbing.h"
namespace fakeit {
class WhenFunctor {
public:
struct StubbingProgress {
friend class WhenFunctor;
virtual ~StubbingProgress() THROWS {
if (std::uncaught_exception()) {
return;
}
if (!_isActive) {
return;
}
_xaction.apply();
}
StubbingProgress(StubbingProgress& other) :
_isActive(other._isActive), _xaction(other._xaction) {
other._isActive = false; // all other ctors should init _isActive to true;
}
StubbingProgress(Xaction& xaction) :
_isActive(true), _xaction(xaction) {
}
protected:
private:
bool _isActive;
Xaction& _xaction;
};
template<typename C, typename R, typename ... arglist>
struct FunctionProgress: public virtual StubbingProgress, public virtual FunctionStubbingProgress<R, arglist...> //
{
friend class WhenFunctor;
virtual ~FunctionProgress() = default;
FirstFunctionStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr{ new DoMock<R, arglist...>(method) };
return Do(ptr);
}
void AlwaysDo(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr{ new DoMock<R, arglist...>(method) };
AlwaysDo(ptr);
}
FunctionProgress(FunctionProgress& other) :
StubbingProgress(other), root(other.root) {
}
FunctionProgress(FunctionStubbingRoot<C, R, arglist...>& xaction) :
StubbingProgress(xaction), root(xaction) {
}
protected:
virtual FirstFunctionStubbingProgress<R, arglist...>& Do(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.AppendAction(ptr);
return *this;
}
virtual void AlwaysDo(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.LastAction(ptr);
}
private:
FunctionStubbingRoot<C, R, arglist...>& root;
// FunctionProgress & operator=(const FunctionProgress & other) = delete;
};
template<typename C, typename R, typename ... arglist>
struct ProcedureProgress: public StubbingProgress,
public virtual ProcedureStubbingProgress<R, arglist...> {
friend class WhenFunctor;
virtual ~ProcedureProgress() override = default;
FirstProcedureStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr{ new DoMock<R, arglist...>(method) };
return Do(ptr);
}
void AlwaysDo(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr{ new DoMock<R, arglist...>(method) };
AlwaysDo(ptr);
}
ProcedureProgress(ProcedureProgress& other) :
StubbingProgress(other) , root(other.root){
}
ProcedureProgress(ProcedureStubbingRoot<C, R, arglist...>& xaction) :
StubbingProgress(xaction), root(xaction) {
}
protected:
virtual FirstProcedureStubbingProgress<R, arglist...>& Do(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.AppendAction(ptr);
return *this;
}
virtual void AlwaysDo(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.LastAction(ptr);
}
private:
ProcedureStubbingRoot<C, R, arglist...>& root;
// ProcedureProgress & operator=(const ProcedureProgress & other) = delete;
};
WhenFunctor() {
}
template<typename C, typename R, typename ... arglist>
ProcedureProgress<C, R, arglist...> operator()(const ProcedureStubbingRoot<C, R, arglist...>& stubbingProgress) {
ProcedureStubbingRoot<C, R, arglist...>& rootWithoutConst = const_cast<ProcedureStubbingRoot<C, R, arglist...>&>(stubbingProgress);
//return dynamic_cast<FirstProcedureStubbingProgress<R, arglist...>&>(rootWithoutConst);
ProcedureProgress<C,R,arglist...> a(rootWithoutConst);
return a;
}
template<typename C, typename R, typename ... arglist>
FunctionProgress<C, R, arglist...> operator()(const FunctionStubbingRoot<C, R, arglist...>& stubbingProgress) {
FunctionStubbingRoot<C, R, arglist...>& rootWithoutConst = const_cast<FunctionStubbingRoot<C, R, arglist...>&>(stubbingProgress);
//return dynamic_cast<FirstFunctionStubbingProgress<R, arglist...>&>(rootWithoutConst);
FunctionProgress<C,R,arglist...> a(rootWithoutConst);
return a;
}
}static When;
}
#endif /* WHENFUNCTOR_HPP_ */
<commit_msg>cleanup<commit_after>/*
* WhenFunctor.hpp
*
* Created on: Feb 14, 2014
* Author: eran
*/
#ifndef WHENFUNCTOR_HPP_
#define WHENFUNCTOR_HPP_
#include "fakeit/StubbingImpl.h"
#include "fakeit/Stubbing.h"
namespace fakeit {
class WhenFunctor {
public:
struct StubbingProgress {
friend class WhenFunctor;
virtual ~StubbingProgress() THROWS {
if (std::uncaught_exception()) {
return;
}
if (!_isActive) {
return;
}
_xaction.apply();
}
StubbingProgress(StubbingProgress& other) :
_isActive(other._isActive), _xaction(other._xaction) {
other._isActive = false; // all other ctors should init _isActive to true;
}
StubbingProgress(Xaction& xaction) :
_isActive(true), _xaction(xaction) {
}
protected:
private:
bool _isActive;
Xaction& _xaction;
};
template<typename C, typename R, typename ... arglist>
struct FunctionProgress: public StubbingProgress, public FunctionStubbingProgress<R, arglist...> //
{
friend class WhenFunctor;
virtual ~FunctionProgress() = default;
// TODO:remove these 2 methods, they are in base class
FirstFunctionStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return Do(ptr);
}
void AlwaysDo(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
AlwaysDo(ptr);
}
FunctionProgress(FunctionProgress& other) :
StubbingProgress(other), root(other.root) {
}
FunctionProgress(FunctionStubbingRoot<C, R, arglist...>& xaction) :
StubbingProgress(xaction), root(xaction) {
}
protected:
virtual FirstFunctionStubbingProgress<R, arglist...>& Do(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.AppendAction(ptr);
return *this;
}
virtual void AlwaysDo(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.LastAction(ptr);
}
private:
FunctionStubbingRoot<C, R, arglist...>& root;
// FunctionProgress & operator=(const FunctionProgress & other) = delete;
};
template<typename C, typename R, typename ... arglist>
struct ProcedureProgress: public StubbingProgress, public ProcedureStubbingProgress<R, arglist...> {
friend class WhenFunctor;
virtual ~ProcedureProgress() override = default;
// TODO:remove these 2 methods, they are in base class
FirstProcedureStubbingProgress<R, arglist...>& Do(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
return Do(ptr);
}
void AlwaysDo(std::function<R(arglist...)> method) override {
std::shared_ptr<BehaviorMock<R, arglist...>> ptr { new DoMock<R, arglist...>(method) };
AlwaysDo(ptr);
}
ProcedureProgress(ProcedureProgress& other) :
StubbingProgress(other), root(other.root) {
}
ProcedureProgress(ProcedureStubbingRoot<C, R, arglist...>& xaction) :
StubbingProgress(xaction), root(xaction) {
}
protected:
virtual FirstProcedureStubbingProgress<R, arglist...>& Do(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.AppendAction(ptr);
return *this;
}
virtual void AlwaysDo(std::shared_ptr<BehaviorMock<R, arglist...> > ptr) override {
root.LastAction(ptr);
}
private:
ProcedureStubbingRoot<C, R, arglist...>& root;
// ProcedureProgress & operator=(const ProcedureProgress & other) = delete;
};
WhenFunctor() {
}
template<typename C, typename R, typename ... arglist>
ProcedureProgress<C, R, arglist...> operator()(const ProcedureStubbingRoot<C, R, arglist...>& stubbingProgress) {
ProcedureStubbingRoot<C, R, arglist...>& rootWithoutConst = const_cast<ProcedureStubbingRoot<C, R, arglist...>&>(stubbingProgress);
//return dynamic_cast<FirstProcedureStubbingProgress<R, arglist...>&>(rootWithoutConst);
ProcedureProgress<C, R, arglist...> a(rootWithoutConst);
return a;
}
template<typename C, typename R, typename ... arglist>
FunctionProgress<C, R, arglist...> operator()(const FunctionStubbingRoot<C, R, arglist...>& stubbingProgress) {
FunctionStubbingRoot<C, R, arglist...>& rootWithoutConst = const_cast<FunctionStubbingRoot<C, R, arglist...>&>(stubbingProgress);
//return dynamic_cast<FirstFunctionStubbingProgress<R, arglist...>&>(rootWithoutConst);
FunctionProgress<C, R, arglist...> a(rootWithoutConst);
return a;
}
}static When;
}
#endif /* WHENFUNCTOR_HPP_ */
<|endoftext|> |
<commit_before>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file descriptor.hpp
* \date July 2015
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__DESCRIPTOR_HPP
#define FL__UTIL__DESCRIPTOR_HPP
#include <string>
#include <tuple>
namespace fl
{
/**
* \ingroup util
*
* Descriptor represents the description of a construct. In various cases a
* class is composed on compile-time. It is often hard to know what the final
* composition constituents are after compilation. The Descriptor provides
* the name of composed class and a full description of it.
*/
class Descriptor
{
public:
/**
* \brief Generates the name of this construct (compile time generated
* class). This is used to determine the name of the class.
*
* This function returns the name of this composition including its
* constitutent parts. The resulting name is often of a template class
* definition form, e.g. in case of a Kalman filter
*
* \code
* GaussianFilter<
* LinearStateTransitionModel<State, Noise, Input>,
* LinearGaussianObservationModel<Obsrv, State, Noise>>
* \endcode
*
* \return Name of \c *this construct
*/
virtual std::string name() const = 0;
/**
* \brief Generates of the description this construct (compile time
* generated class). This is used to determine the name of the class.
*
* This function generates the full description of this class which is
* composed on compile-time. The description typically contains the
* descriptions of all constituent parts of this class.
*
* \return Full description of \c *this construct
*/
virtual std::string description() const = 0;
protected:
/** \cond internal */
/**
* \brief indent a given text
*
* \param [in] text Text to indent
* \param [in] levels Levels of indentation
*
* \return indented text by the number of level
*/
virtual std::string indent(const std::string& text, int levels = 1) const
{
std::istringstream iss(text);
std::string indented_text;
std::string line;
while(std::getline(iss, line))
{
indented_text += "\n" + std::string(4 * levels, ' ') + line;
}
return indented_text;
}
/**
* Creates list with the correct indentation out of the passed elements.
*/
template <typename ... Elements>
std::string list_arguments(const Elements& ... elements) const
{
std::tuple<const Elements&...> element_tuple{elements...};
std::string list_string;
list_impl<sizeof...(Elements), 0>(
element_tuple, "", ",", ",", list_string);
return list_string;
}
/**
* Creates list of descriptions with the correct indentation
*/
template <typename ... Elements>
std::string list_descriptions(const Elements& ... elements) const
{
std::tuple<const Elements&...> element_tuple{elements...};
std::string list_string;
list_impl<sizeof...(Elements), 0>(
element_tuple, "- ", ",", ", and", list_string);
return list_string;
}
/** \endcond */
private:
template <int Size, int k, typename ... Elements>
void list_impl(const std::tuple<const Elements&...>& element_tuple,
const std::string& bullet,
const std::string& delimiter,
const std::string& final_delimiter,
std::string& list_string) const
{
auto&& element = std::get<k>(element_tuple);
list_string += indent(bullet + element);
if (k + 2 < Size)
{
list_string += delimiter;
}
else if (k + 1 < Size)
{
list_string += final_delimiter;
}
if (Size == k + 1) return;
list_impl<Size, k + (k + 1 < Size ? 1 : 0)>(
element_tuple,
bullet,
delimiter,
final_delimiter,
list_string);
}
};
}
#endif
<commit_msg>made indent() public such that it can be used in compositions. However it remains the in the internal scope since it is an implementation detail<commit_after>/*
* This is part of the FL library, a C++ Bayesian filtering library
* (https://github.com/filtering-library)
*
* Copyright (c) 2014 Jan Issac ([email protected])
* Copyright (c) 2014 Manuel Wuthrich ([email protected])
*
* This Source Code Form is subject to the terms of the MIT License (MIT).
* A copy of the license can be found in the LICENSE file distributed with this
* source code.
*/
/**
* \file descriptor.hpp
* \date July 2015
* \author Jan Issac ([email protected])
*/
#ifndef FL__UTIL__DESCRIPTOR_HPP
#define FL__UTIL__DESCRIPTOR_HPP
#include <string>
#include <tuple>
namespace fl
{
/**
* \ingroup util
*
* Descriptor represents the description of a construct. In various cases a
* class is composed on compile-time. It is often hard to know what the final
* composition constituents are after compilation. The Descriptor provides
* the name of composed class and a full description of it.
*/
class Descriptor
{
public:
/**
* \brief Generates the name of this construct (compile time generated
* class). This is used to determine the name of the class.
*
* This function returns the name of this composition including its
* constitutent parts. The resulting name is often of a template class
* definition form, e.g. in case of a Kalman filter
*
* \code
* GaussianFilter<
* LinearStateTransitionModel<State, Noise, Input>,
* LinearGaussianObservationModel<Obsrv, State, Noise>>
* \endcode
*
* \return Name of \c *this construct
*/
virtual std::string name() const = 0;
/**
* \brief Generates of the description this construct (compile time
* generated class). This is used to determine the name of the class.
*
* This function generates the full description of this class which is
* composed on compile-time. The description typically contains the
* descriptions of all constituent parts of this class.
*
* \return Full description of \c *this construct
*/
virtual std::string description() const = 0;
/** \cond internal */
/**
* \brief indent a given text
*
* \param [in] text Text to indent
* \param [in] levels Levels of indentation
*
* \return indented text by the number of level
*/
virtual std::string indent(const std::string& text, int levels = 1) const
{
std::istringstream iss(text);
std::string indented_text;
std::string line;
while(std::getline(iss, line))
{
indented_text += "\n" + std::string(4 * levels, ' ') + line;
}
return indented_text;
}
protected:
/**
* Creates list with the correct indentation out of the passed elements.
*/
template <typename ... Elements>
std::string list_arguments(const Elements& ... elements) const
{
std::tuple<const Elements&...> element_tuple{elements...};
std::string list_string;
list_impl<sizeof...(Elements), 0>(
element_tuple, "", ",", ",", list_string);
return list_string;
}
/**
* Creates list of descriptions with the correct indentation
*/
template <typename ... Elements>
std::string list_descriptions(const Elements& ... elements) const
{
std::tuple<const Elements&...> element_tuple{elements...};
std::string list_string;
list_impl<sizeof...(Elements), 0>(
element_tuple, "- ", ",", ", and", list_string);
return list_string;
}
/** \endcond */
private:
template <int Size, int k, typename ... Elements>
void list_impl(const std::tuple<const Elements&...>& element_tuple,
const std::string& bullet,
const std::string& delimiter,
const std::string& final_delimiter,
std::string& list_string) const
{
auto&& element = std::get<k>(element_tuple);
list_string += indent(bullet + element);
if (k + 2 < Size)
{
list_string += delimiter;
}
else if (k + 1 < Size)
{
list_string += final_delimiter;
}
if (Size == k + 1) return;
list_impl<Size, k + (k + 1 < Size ? 1 : 0)>(
element_tuple,
bullet,
delimiter,
final_delimiter,
list_string);
}
};
}
#endif
<|endoftext|> |
<commit_before>#ifndef INC_METTLE_LOG_SUMMARY_HPP
#define INC_METTLE_LOG_SUMMARY_HPP
#include <iomanip>
#include "core.hpp"
#include "indent.hpp"
#include "term.hpp"
namespace mettle {
namespace log {
class summary : public file_logger {
public:
summary(indenting_ostream &out, file_logger *log) : out_(out), log_(log) {}
void started_run() {
if(log_) log_->started_run();
runs_++;
total_ = skips_ = file_index_ = 0;
}
void ended_run() {
if(log_) log_->ended_run();
}
void started_suite(const std::vector<std::string> &suites) {
if(log_) log_->started_suite(suites);
}
void ended_suite(const std::vector<std::string> &suites) {
if(log_) log_->ended_suite(suites);
}
void started_test(const test_name &test) {
if(log_) log_->started_test(test);
total_++;
}
void passed_test(const test_name &test, const test_output &output,
test_duration duration) {
if(log_) log_->passed_test(test, output, duration);
}
void failed_test(const test_name &test, const std::string &message,
const test_output &output, test_duration duration) {
if(log_) log_->failed_test(test, message, output, duration);
failures_[test].push_back({runs_, message});
}
void skipped_test(const test_name &test, const std::string &message) {
if(log_) log_->skipped_test(test, message);
skips_++;
}
void started_file(const std::string &file) {
if(log_) log_->started_file(file);
}
void ended_file(const std::string &file) {
if(log_) log_->ended_file(file);
file_index_++;
}
void failed_file(const std::string &file, const std::string &message) {
if(log_) log_->failed_file(file, message);
failed_files_[{file_index_++, file}].push_back({runs_, message});
}
void summarize() {
assert(runs_ > 0 && "number of runs can't be zero");
if(log_)
out_ << std::endl;
using namespace term;
size_t passes = total_ - skips_ - failures_.size();
out_ << format(sgr::bold) << passes << "/" << total_ << " tests passed";
if(skips_)
out_ << " (" << skips_ << " skipped)";
if(!failed_files_.empty()) {
std::string s = failed_files_.size() > 1 ? "s" : "";
out_ << " [" << failed_files_.size() << " file" << s << " "
<< format(fg(color::red)) << "FAILED" << format(fg(color::normal))
<< "]";
}
out_ << reset() << std::endl;
scoped_indent indent(out_);
for(const auto &i : failures_)
summarize_failure(i.first.full_name(), i.second);
for(const auto &i : failed_files_)
summarize_failure("`" + i.first.name + "`", i.second);
}
bool good() const {
return failures_.empty();
}
private:
struct file_info {
size_t index;
std::string name;
bool operator <(const file_info &rhs) const {
return index < rhs.index;
}
};
struct failure {
size_t run;
std::string message;
};
void summarize_failure(const std::string &where,
const std::vector<const failure> &failures) {
using namespace term;
out_ << where << " " << format(sgr::bold, fg(color::red)) << "FAILED"
<< reset();
if(runs_ > 1) {
format fail_count_fmt(
sgr::bold, fg(failures.size() == runs_ ? color::red : color::yellow)
);
out_ << " " << fail_count_fmt << "[" << failures.size() << "/" << runs_
<< "]" << reset();
}
out_ << std::endl;
scoped_indent si(out_);
if(runs_ == 1) {
auto &&message = failures[0].message;
if(!message.empty())
out_ << message << std::endl;
}
else {
int run_width = std::ceil(std::log10(runs_));
for(const auto &i : failures) {
out_ << format(sgr::bold, fg(color::yellow)) << "[#"
<< std::setw(run_width) << i.run << "]" << reset() << " ";
scoped_indent si(out_, indent_style::visual, run_width + 4);
out_ << i.message << std::endl;
}
}
}
indenting_ostream &out_;
file_logger *log_;
size_t total_ = 0, skips_ = 0, runs_ = 0, file_index_ = 0;
std::map<test_name, std::vector<const failure>> failures_;
std::map<file_info, std::vector<const failure>> failed_files_;
};
}
} // namespace mettle
#endif
<commit_msg>Show skipped tests in the summary<commit_after>#ifndef INC_METTLE_LOG_SUMMARY_HPP
#define INC_METTLE_LOG_SUMMARY_HPP
#include <iomanip>
#include "core.hpp"
#include "indent.hpp"
#include "term.hpp"
namespace mettle {
namespace log {
class summary : public file_logger {
public:
summary(indenting_ostream &out, file_logger *log) : out_(out), log_(log) {}
void started_run() {
if(log_) log_->started_run();
runs_++;
total_ = file_index_ = 0;
}
void ended_run() {
if(log_) log_->ended_run();
}
void started_suite(const std::vector<std::string> &suites) {
if(log_) log_->started_suite(suites);
}
void ended_suite(const std::vector<std::string> &suites) {
if(log_) log_->ended_suite(suites);
}
void started_test(const test_name &test) {
if(log_) log_->started_test(test);
total_++;
}
void passed_test(const test_name &test, const test_output &output,
test_duration duration) {
if(log_) log_->passed_test(test, output, duration);
}
void failed_test(const test_name &test, const std::string &message,
const test_output &output, test_duration duration) {
if(log_) log_->failed_test(test, message, output, duration);
failures_[test].push_back({runs_, message});
}
void skipped_test(const test_name &test, const std::string &message) {
if(log_) log_->skipped_test(test, message);
skips_.emplace(test, message);
}
void started_file(const std::string &file) {
if(log_) log_->started_file(file);
}
void ended_file(const std::string &file) {
if(log_) log_->ended_file(file);
file_index_++;
}
void failed_file(const std::string &file, const std::string &message) {
if(log_) log_->failed_file(file, message);
failed_files_[{file_index_++, file}].push_back({runs_, message});
}
void summarize() const {
assert(runs_ > 0 && "number of runs can't be zero");
if(log_)
out_ << std::endl;
using namespace term;
size_t passes = total_ - skips_.size() - failures_.size();
out_ << format(sgr::bold) << passes << "/" << total_ << " tests passed";
if(!skips_.empty())
out_ << " (" << skips_.size() << " skipped)";
if(!failed_files_.empty()) {
std::string s = failed_files_.size() > 1 ? "s" : "";
out_ << " [" << failed_files_.size() << " file" << s << " "
<< format(fg(color::red)) << "FAILED" << format(fg(color::normal))
<< "]";
}
out_ << reset() << std::endl;
scoped_indent indent(out_);
// XXX: Interleave skips and failures in the appropriate order?
for(const auto &i : skips_)
summarize_skip(i.first.full_name(), i.second);
for(const auto &i : failures_)
summarize_failure(i.first.full_name(), i.second);
for(const auto &i : failed_files_)
summarize_failure("`" + i.first.name + "`", i.second);
}
bool good() const {
return failures_.empty();
}
private:
struct file_info {
size_t index;
std::string name;
bool operator <(const file_info &rhs) const {
return index < rhs.index;
}
};
struct failure {
size_t run;
std::string message;
};
void summarize_skip(const std::string &test,
const std::string &message) const {
using namespace term;
out_ << test << " " << format(sgr::bold, fg(color::blue)) << "SKIPPED"
<< reset() << std::endl;
if(!message.empty()) {
scoped_indent si(out_);
out_ << message << std::endl;
}
}
void summarize_failure(const std::string &where,
const std::vector<const failure> &failures) const {
using namespace term;
out_ << where << " " << format(sgr::bold, fg(color::red)) << "FAILED"
<< reset();
if(runs_ > 1) {
format fail_count_fmt(
sgr::bold, fg(failures.size() == runs_ ? color::red : color::yellow)
);
out_ << " " << fail_count_fmt << "[" << failures.size() << "/" << runs_
<< "]" << reset();
}
out_ << std::endl;
scoped_indent si(out_);
if(runs_ == 1) {
auto &&message = failures[0].message;
if(!message.empty())
out_ << message << std::endl;
}
else {
int run_width = std::ceil(std::log10(runs_));
for(const auto &i : failures) {
out_ << format(sgr::bold, fg(color::yellow)) << "[#"
<< std::setw(run_width) << i.run << "]" << reset() << " ";
scoped_indent si(out_, indent_style::visual, run_width + 4);
out_ << i.message << std::endl;
}
}
}
indenting_ostream &out_;
file_logger *log_;
size_t total_ = 0, runs_ = 0, file_index_ = 0;
std::map<test_name, std::vector<const failure>> failures_;
std::map<test_name, std::string> skips_;
std::map<file_info, std::vector<const failure>> failed_files_;
};
}
} // namespace mettle
#endif
<|endoftext|> |
<commit_before>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id: polygon_symbolizer.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef POLYGON_SYMBOLIZER_HPP
#define POLYGON_SYMBOLIZER_HPP
#include "symbolizer.hpp"
#include "image_reader.hpp"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pixfmt_rgba.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
namespace mapnik
{
struct polygon_symbolizer : public symbolizer
{
private:
Color fill_;
public:
polygon_symbolizer(const Color& fill)
: symbolizer(),
fill_(fill) {}
virtual ~polygon_symbolizer() {}
void render(geometry_type& geom,Image32& image) const
{
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
double r=fill_.red()/255.0;
double g=fill_.green()/255.0;
double b=fill_.blue()/255.0;
double a=fill_.alpha()/255.0;
renderer ren(renb);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(geom);
ren.color(agg::rgba(r, g, b, a));
agg::render_scanlines(ras, sl, ren);
}
private:
polygon_symbolizer(const polygon_symbolizer&);
polygon_symbolizer& operator=(const polygon_symbolizer&);
};
struct pattern_symbolizer : public symbolizer
{
private:
ImageData32 pattern_;
public:
pattern_symbolizer(std::string const& file,
std::string const& type,
unsigned width,unsigned height)
: symbolizer(),
pattern_(width,height)
{
try
{
std::auto_ptr<ImageReader> reader(get_image_reader(type,file));
reader->read(0,0,pattern_);
}
catch (...)
{
std::cerr<<"exception caught..."<<std::endl;
}
}
virtual ~pattern_symbolizer() {}
void render(geometry_type& geom,Image32& image) const
{
/*
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
unsigned w=pattern_.width();
unsigned h=pattern_.height();
agg::row_ptr_cache<agg::int8u> pattern_rbuf((agg::int8u*)pattern_.getBytes(),w,h,w*4);
typedef agg::wrap_mode_repeat wrap_x_type;
typedef agg::wrap_mode_repeat wrap_y_type;
typedef agg::image_accessor_wrap<agg::pixfmt_rgba32,
wrap_x_type,
wrap_y_type> img_source_type;
typedef agg::span_pattern_rgba<agg::rgba8,
agg::order_rgba,
wrap_x_type,
wrap_y_type> span_gen_type;
typedef agg::renderer_scanline_aa<ren_base,
agg::span_allocator<agg::rgba8>,
span_gen_type> renderer_type;
unsigned offset_x = 0;
unsigned offset_y = 0;
agg::span_allocator<agg::rgba8> sa;
span_gen_type sg(pattern_rbuf,offset_x, offset_y);
renderer_type rp(renb,sa, sg);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(geom);
agg::render_scanlines(ras, sl, rp);
*/
}
private:
pattern_symbolizer(const pattern_symbolizer&);
pattern_symbolizer& operator=(const pattern_symbolizer&);
};
}
#endif // POLYGON_SYMBOLIZER_HPP
<commit_msg>fixed pattern fill symbolizer<commit_after>/* This file is part of Mapnik (c++ mapping toolkit)
* Copyright (C) 2005 Artem Pavlenko
*
* Mapnik is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
//$Id: polygon_symbolizer.hpp 39 2005-04-10 20:39:53Z pavlenko $
#ifndef POLYGON_SYMBOLIZER_HPP
#define POLYGON_SYMBOLIZER_HPP
#include "symbolizer.hpp"
#include "image_reader.hpp"
#include "agg_basics.h"
#include "agg_rendering_buffer.h"
#include "agg_rasterizer_scanline_aa.h"
#include "agg_scanline_p.h"
#include "agg_scanline_u.h"
#include "agg_renderer_scanline.h"
#include "agg_pixfmt_rgba.h"
#include "agg_path_storage.h"
#include "agg_span_allocator.h"
#include "agg_span_pattern_rgba.h"
#include "agg_image_accessors.h"
namespace mapnik
{
struct polygon_symbolizer : public symbolizer
{
private:
Color fill_;
public:
polygon_symbolizer(const Color& fill)
: symbolizer(),
fill_(fill) {}
virtual ~polygon_symbolizer() {}
void render(geometry_type& geom,Image32& image) const
{
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
typedef agg::renderer_scanline_aa_solid<ren_base> renderer;
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
unsigned r=fill_.red();
unsigned g=fill_.green();
unsigned b=fill_.blue();
unsigned a=fill_.alpha();
renderer ren(renb);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(geom);
ren.color(agg::rgba8(r, g, b, a));
agg::render_scanlines(ras, sl, ren);
}
private:
polygon_symbolizer(const polygon_symbolizer&);
polygon_symbolizer& operator=(const polygon_symbolizer&);
};
struct pattern_symbolizer : public symbolizer
{
private:
ImageData32 pattern_;
public:
pattern_symbolizer(std::string const& file,
std::string const& type,
unsigned width,unsigned height)
: symbolizer(),
pattern_(width,height)
{
try
{
std::auto_ptr<ImageReader> reader(get_image_reader(type,file));
reader->read(0,0,pattern_);
}
catch (...)
{
std::cerr<<"exception caught..."<<std::endl;
}
}
virtual ~pattern_symbolizer() {}
void render(geometry_type& geom,Image32& image) const
{
typedef agg::renderer_base<agg::pixfmt_rgba32> ren_base;
agg::row_ptr_cache<agg::int8u> buf(image.raw_data(),image.width(),image.height(),
image.width()*4);
agg::pixfmt_rgba32 pixf(buf);
ren_base renb(pixf);
unsigned w=pattern_.width();
unsigned h=pattern_.height();
agg::row_ptr_cache<agg::int8u> pattern_rbuf((agg::int8u*)pattern_.getBytes(),w,h,w*4);
typedef agg::wrap_mode_repeat wrap_x_type;
typedef agg::wrap_mode_repeat wrap_y_type;
typedef agg::image_accessor_wrap<agg::pixfmt_rgba32,
wrap_x_type,
wrap_y_type> img_source_type;
typedef agg::span_pattern_rgba<img_source_type> span_gen_type;
typedef agg::renderer_scanline_aa<ren_base,
agg::span_allocator<agg::rgba8>,
span_gen_type> renderer_type;
double x0,y0;
geom.vertex(&x0,&y0);
geom.rewind(0);
unsigned offset_x = unsigned(image.width() - x0);
unsigned offset_y = unsigned(image.height() - y0);
agg::span_allocator<agg::rgba8> sa;
img_source_type img_src(pattern_rbuf);
span_gen_type sg(img_src, offset_x, offset_y);
renderer_type rp(renb,sa, sg);
agg::rasterizer_scanline_aa<> ras;
agg::scanline_u8 sl;
ras.clip_box(0,0,image.width(),image.height());
ras.add_path(geom);
agg::render_scanlines(ras, sl, rp);
}
private:
pattern_symbolizer(const pattern_symbolizer&);
pattern_symbolizer& operator=(const pattern_symbolizer&);
};
}
#endif // POLYGON_SYMBOLIZER_HPP
<|endoftext|> |
<commit_before>#pragma once
#include <utility>
#include "reflection_info.hpp"
namespace shadow
{
////////////////////////////////////////////////////////////////////////////////
// user facing API types carrying information and functionality for the
// reflection system
class reflection_manager;
// holds one value with type/reflection information
class variable
{
private:
// holds type erased value
any value_;
// these identify the type erased value
const reflection_manager* manager_;
std::size_t type_index_;
};
// represents a type with reflection information and functionality
class type
{
public:
type(const type_info* info) : info_(info)
{
}
type* operator->()
{
return this;
}
const type* operator->() const
{
return this;
}
public:
std::string
name() const
{
return info_->name;
}
std::size_t
size() const
{
return info_->size;
}
private:
const type_info* info_;
};
template <class InfoType, class ProxyType>
class info_iterator_
{
public:
typedef ProxyType value_type;
typedef typename std::iterator_traits<const InfoType*>::difference_type
difference_type;
typedef ProxyType reference;
typedef ProxyType pointer;
typedef typename std::iterator_traits<const InfoType*>::iterator_category
iterator_category;
public:
info_iterator_() = default;
info_iterator_(const InfoType* current) : current_(current)
{
}
public:
ProxyType operator*() const
{
return ProxyType(current_);
}
ProxyType operator->() const
{
return ProxyType(current_);
}
info_iterator_& operator++()
{
++current_;
return *this;
}
info_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
bool
operator==(const info_iterator_& other) const
{
return current_ == other.current_;
}
bool
operator!=(const info_iterator_& other) const
{
return current_ != other.current_;
}
private:
const InfoType* current_;
};
// represents a free function with reflection information
class free_function
{
private:
const free_function_info* info_;
};
}
namespace shadow
{
class reflection_manager
{
public:
typedef info_iterator_<type_info, type> type_iterator;
public:
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(
initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder()))
{
}
private:
// generic initialization helper function
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType)
{
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
#pragma clang diagnostic pop
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
};
}
namespace std
{
// specialize std::iterator_traits for info_iterator_
template <class InfoType, class ProxyType>
struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
value_type;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
difference_type;
typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
reference;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
iterator_category;
};
}
<commit_msg>Comment. modified: include/reflection_manager.hpp<commit_after>#pragma once
#include <utility>
#include "reflection_info.hpp"
namespace shadow
{
////////////////////////////////////////////////////////////////////////////////
// user facing API types carrying information and functionality for the
// reflection system
class reflection_manager;
// holds one value with type/reflection information
class variable
{
private:
// holds type erased value
any value_;
// these identify the type erased value
const reflection_manager* manager_;
std::size_t type_index_;
};
// represents a type with reflection information and functionality
class type
{
public:
type(const type_info* info) : info_(info)
{
}
type* operator->()
{
return this;
}
// for const iterators
const type* operator->() const
{
return this;
}
public:
std::string
name() const
{
return info_->name;
}
std::size_t
size() const
{
return info_->size;
}
private:
const type_info* info_;
};
template <class InfoType, class ProxyType>
class info_iterator_
{
public:
typedef ProxyType value_type;
typedef typename std::iterator_traits<const InfoType*>::difference_type
difference_type;
typedef ProxyType reference;
typedef ProxyType pointer;
typedef typename std::iterator_traits<const InfoType*>::iterator_category
iterator_category;
public:
info_iterator_() = default;
info_iterator_(const InfoType* current) : current_(current)
{
}
public:
ProxyType operator*() const
{
return ProxyType(current_);
}
ProxyType operator->() const
{
return ProxyType(current_);
}
info_iterator_& operator++()
{
++current_;
return *this;
}
info_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
bool
operator==(const info_iterator_& other) const
{
return current_ == other.current_;
}
bool
operator!=(const info_iterator_& other) const
{
return current_ != other.current_;
}
private:
const InfoType* current_;
};
// represents a free function with reflection information
class free_function
{
private:
const free_function_info* info_;
};
}
namespace shadow
{
class reflection_manager
{
public:
typedef info_iterator_<type_info, type> type_iterator;
public:
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(
initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder()))
{
}
private:
// generic initialization helper function
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType)
{
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
#pragma clang diagnostic pop
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
};
}
namespace std
{
// specialize std::iterator_traits for info_iterator_
template <class InfoType, class ProxyType>
struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
value_type;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
difference_type;
typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
reference;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
iterator_category;
};
}
<|endoftext|> |
<commit_before>#pragma once
#include <utility>
#include <vector>
#include <algorithm>
#include "reflection_info.hpp"
namespace shadow
{
////////////////////////////////////////////////////////////////////////////////
// user facing API types carrying information and functionality for the
// reflection system
class reflection_manager;
// holds one value with type/reflection information
class variable
{
private:
// holds type erased value
any value_;
// these identify the type erased value
const reflection_manager* manager_;
std::size_t type_index_;
};
template <class InfoType, template <class> class... Policies>
class api_type_aggregator
: public Policies<api_type_aggregator<InfoType, Policies...>>...
{
public:
api_type_aggregator() : info_(nullptr), manager_(nullptr)
{
}
api_type_aggregator(const InfoType* info, const reflection_manager* manager)
: info_(info), manager_(manager)
{
}
api_type_aggregator* operator->()
{
return this;
}
const api_type_aggregator* operator->() const
{
return this;
}
public:
const InfoType* info_;
const reflection_manager* manager_;
};
template <class Derived>
class get_name_policy
{
public:
std::string
name() const
{
return (static_cast<const Derived*>(this))->info_->name;
}
};
template <class Derived>
class get_size_policy
{
public:
std::size_t
size() const
{
return static_cast<const Derived*>(this)->info_->size;
}
};
typedef api_type_aggregator<type_info, get_name_policy, get_size_policy> type_;
template <class Derived>
class get_type_policy
{
public:
type_
get_type() const
{
// retrieve type index
const auto type_index =
static_cast<const Derived*>(this)->info_->type_index;
return static_cast<const Derived*>(this)->manager_->type_by_index(
type_index);
}
};
typedef api_type_aggregator<constructor_info, get_type_policy> constructor_;
template <class InfoType, class ProxyType>
class info_iterator_
{
public:
typedef ProxyType value_type;
typedef typename std::iterator_traits<const InfoType*>::difference_type
difference_type;
typedef ProxyType reference;
typedef ProxyType pointer;
typedef typename std::iterator_traits<const InfoType*>::iterator_category
iterator_category;
public:
info_iterator_() = default;
info_iterator_(const InfoType* current, const reflection_manager* manager)
: current_(current), manager_(manager)
{
}
public:
ProxyType operator*() const
{
return ProxyType(current_, manager_);
}
ProxyType operator->() const
{
return ProxyType(current_, manager_);
}
ProxyType operator[](difference_type n) const
{
return ProxyType(current_ + n, manager_);
}
info_iterator_& operator++()
{
++current_;
return *this;
}
info_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
info_iterator_& operator--()
{
--current_;
return *this;
}
info_iterator_ operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
info_iterator_&
operator+=(difference_type n)
{
current_ += n;
return *this;
}
info_iterator_&
operator-=(difference_type n)
{
current_ -= n;
return *this;
}
info_iterator_
operator+(difference_type n) const
{
return info_iterator_(current_ + n, manager_);
}
info_iterator_
operator-(difference_type n) const
{
return info_iterator_(current_ - n, manager_);
}
difference_type
operator-(const info_iterator_& other)
{
return current_ - other.current_;
}
friend info_iterator_
operator+(difference_type lhs, const info_iterator_& rhs)
{
return rhs + lhs;
}
bool
operator==(const info_iterator_& other) const
{
return current_ == other.current_;
}
bool
operator!=(const info_iterator_& other) const
{
return current_ != other.current_;
}
bool
operator<(const info_iterator_& other) const
{
return current_ < other.current_;
}
bool
operator>(const info_iterator_& other) const
{
return current_ > other.current_;
}
bool
operator<=(const info_iterator_& other) const
{
return current_ <= other.current_;
}
bool
operator>=(const info_iterator_& other) const
{
return current_ >= other.current_;
}
private:
InfoType* current_;
const reflection_manager* manager_;
};
class reflection_manager
{
public:
template <class Derived>
friend class get_type_policy;
typedef type_ type;
typedef info_iterator_<const type_info, const type> const_type_iterator;
typedef constructor_ constructor;
typedef info_iterator_<const constructor_info, const constructor>
const_constructor_iterator;
public:
reflection_manager() = default;
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(
initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder())),
constructor_info_by_index_(
buckets_by_index(constructor_info_range_, TypeInfoArrayHolder()))
{
}
private:
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType)
{
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
template <class ArrayHolderType>
std::size_t array_size(ArrayHolderType)
{
if(ArrayHolderType::value == nullptr)
{
return 0;
}
else
{
return std::extent<decltype(ArrayHolderType::value)>::value;
}
}
template <class ValueType, class TypeInfoArrayHolder>
std::vector<std::vector<ValueType>>
buckets_by_index(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<ValueType>> out(
array_size(TypeInfoArrayHolder()));
std::for_each(range.first, range.second, [&out](const auto& info) {
out[info.type_index].push_back(info);
});
return out;
}
else
{
return std::vector<std::vector<ValueType>>();
}
}
#pragma clang diagnostic pop
type
type_by_index(std::size_t index) const
{
return type(type_info_range_.first + index, this);
}
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
std::pair<const_type_iterator, const_type_iterator>
types() const
{
return std::make_pair(
const_type_iterator(type_info_range_.first, this),
const_type_iterator(type_info_range_.second, this));
}
std::pair<const_constructor_iterator, const_constructor_iterator>
constructors() const
{
return std::make_pair(
const_constructor_iterator(constructor_info_range_.first, this),
const_constructor_iterator(constructor_info_range_.second, this));
}
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
std::vector<std::vector<constructor_info>> constructor_info_by_index_;
};
}
namespace std
{
// specialize std::iterator_traits for info_iterator_
template <class InfoType, class ProxyType>
struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
value_type;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
difference_type;
typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
reference;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
iterator_category;
};
}
<commit_msg>Make buckets_by_index generic in way to get index from information type. modified: include/reflection_manager.hpp<commit_after>#pragma once
#include <utility>
#include <vector>
#include <algorithm>
#include "reflection_info.hpp"
namespace shadow
{
////////////////////////////////////////////////////////////////////////////////
// user facing API types carrying information and functionality for the
// reflection system
class reflection_manager;
// holds one value with type/reflection information
class variable
{
private:
// holds type erased value
any value_;
// these identify the type erased value
const reflection_manager* manager_;
std::size_t type_index_;
};
template <class InfoType, template <class> class... Policies>
class api_type_aggregator
: public Policies<api_type_aggregator<InfoType, Policies...>>...
{
public:
api_type_aggregator() : info_(nullptr), manager_(nullptr)
{
}
api_type_aggregator(const InfoType* info, const reflection_manager* manager)
: info_(info), manager_(manager)
{
}
api_type_aggregator* operator->()
{
return this;
}
const api_type_aggregator* operator->() const
{
return this;
}
public:
const InfoType* info_;
const reflection_manager* manager_;
};
template <class Derived>
class get_name_policy
{
public:
std::string
name() const
{
return (static_cast<const Derived*>(this))->info_->name;
}
};
template <class Derived>
class get_size_policy
{
public:
std::size_t
size() const
{
return static_cast<const Derived*>(this)->info_->size;
}
};
typedef api_type_aggregator<type_info, get_name_policy, get_size_policy> type_;
template <class Derived>
class get_type_policy
{
public:
type_
get_type() const
{
// retrieve type index
const auto type_index =
static_cast<const Derived*>(this)->info_->type_index;
return static_cast<const Derived*>(this)->manager_->type_by_index(
type_index);
}
};
typedef api_type_aggregator<constructor_info, get_type_policy> constructor_;
template <class InfoType, class ProxyType>
class info_iterator_
{
public:
typedef ProxyType value_type;
typedef typename std::iterator_traits<const InfoType*>::difference_type
difference_type;
typedef ProxyType reference;
typedef ProxyType pointer;
typedef typename std::iterator_traits<const InfoType*>::iterator_category
iterator_category;
public:
info_iterator_() = default;
info_iterator_(const InfoType* current, const reflection_manager* manager)
: current_(current), manager_(manager)
{
}
public:
ProxyType operator*() const
{
return ProxyType(current_, manager_);
}
ProxyType operator->() const
{
return ProxyType(current_, manager_);
}
ProxyType operator[](difference_type n) const
{
return ProxyType(current_ + n, manager_);
}
info_iterator_& operator++()
{
++current_;
return *this;
}
info_iterator_ operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
info_iterator_& operator--()
{
--current_;
return *this;
}
info_iterator_ operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
info_iterator_&
operator+=(difference_type n)
{
current_ += n;
return *this;
}
info_iterator_&
operator-=(difference_type n)
{
current_ -= n;
return *this;
}
info_iterator_
operator+(difference_type n) const
{
return info_iterator_(current_ + n, manager_);
}
info_iterator_
operator-(difference_type n) const
{
return info_iterator_(current_ - n, manager_);
}
difference_type
operator-(const info_iterator_& other)
{
return current_ - other.current_;
}
friend info_iterator_
operator+(difference_type lhs, const info_iterator_& rhs)
{
return rhs + lhs;
}
bool
operator==(const info_iterator_& other) const
{
return current_ == other.current_;
}
bool
operator!=(const info_iterator_& other) const
{
return current_ != other.current_;
}
bool
operator<(const info_iterator_& other) const
{
return current_ < other.current_;
}
bool
operator>(const info_iterator_& other) const
{
return current_ > other.current_;
}
bool
operator<=(const info_iterator_& other) const
{
return current_ <= other.current_;
}
bool
operator>=(const info_iterator_& other) const
{
return current_ >= other.current_;
}
private:
InfoType* current_;
const reflection_manager* manager_;
};
class reflection_manager
{
public:
template <class Derived>
friend class get_type_policy;
typedef type_ type;
typedef info_iterator_<const type_info, const type> const_type_iterator;
typedef constructor_ constructor;
typedef info_iterator_<const constructor_info, const constructor>
const_constructor_iterator;
public:
reflection_manager() = default;
template <class TypeInfoArrayHolder,
class ConstructorInfoArrayHolder,
class ConversionInfoArrayHolder,
class StringSerializationInfoArrayHolder,
class FreeFunctionInfoArrayHolder,
class MemberFunctionInfoArrayHolder,
class MemberVariableInfoArrayHolder>
reflection_manager(TypeInfoArrayHolder,
ConstructorInfoArrayHolder,
ConversionInfoArrayHolder,
StringSerializationInfoArrayHolder,
FreeFunctionInfoArrayHolder,
MemberFunctionInfoArrayHolder,
MemberVariableInfoArrayHolder)
: type_info_range_(initialize_range(TypeInfoArrayHolder())),
constructor_info_range_(
initialize_range(ConstructorInfoArrayHolder())),
conversion_info_range_(initialize_range(ConversionInfoArrayHolder())),
string_serialization_info_range_(
initialize_range(StringSerializationInfoArrayHolder())),
free_function_info_range_(
initialize_range(FreeFunctionInfoArrayHolder())),
member_function_info_range_(
initialize_range(MemberFunctionInfoArrayHolder())),
member_variable_info_range_(
initialize_range(MemberVariableInfoArrayHolder())),
constructor_info_by_index_(buckets_by_index(
constructor_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.type_index; })),
conversion_info_by_index_(buckets_by_index(
conversion_info_range_,
TypeInfoArrayHolder(),
[](const auto& info) { return info.from_type_index; }))
{
}
private:
// clang complains here due to the comparison of decayed array and
// nullptr, since in the case ArrayHolderType::value was an array, this
// would always evaluate to true. The fact is that
// ArrayHolderType::value may be a pointer to nullptr for some cases of
// ArrayHolderType.
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wtautological-pointer-compare"
template <class ArrayHolderType>
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
initialize_range(ArrayHolderType)
{
if(ArrayHolderType::value != nullptr)
{
return std::make_pair(std::begin(ArrayHolderType::value),
std::end(ArrayHolderType::value));
}
else
{
std::pair<const typename ArrayHolderType::type*,
const typename ArrayHolderType::type*>
out(nullptr, nullptr);
return out;
}
}
template <class ArrayHolderType>
std::size_t array_size(ArrayHolderType)
{
if(ArrayHolderType::value == nullptr)
{
return 0;
}
else
{
return std::extent<decltype(ArrayHolderType::value)>::value;
}
}
template <class ValueType, class TypeInfoArrayHolder, class Fun>
std::vector<std::vector<ValueType>>
buckets_by_index(const std::pair<const ValueType*, const ValueType*>& range,
TypeInfoArrayHolder,
Fun index_extractor)
{
if(range.first != nullptr && range.second != nullptr)
{
std::vector<std::vector<ValueType>> out(
array_size(TypeInfoArrayHolder()));
std::for_each(range.first,
range.second,
[&out, index_extractor](const auto& info) {
out[index_extractor(info)].push_back(info);
});
return out;
}
else
{
return std::vector<std::vector<ValueType>>();
}
}
#pragma clang diagnostic pop
type
type_by_index(std::size_t index) const
{
return type(type_info_range_.first + index, this);
}
public:
////////////////////////////////////////////////////////////////////////////
// main api interface for interacting with the reflection system
std::pair<const_type_iterator, const_type_iterator>
types() const
{
return std::make_pair(
const_type_iterator(type_info_range_.first, this),
const_type_iterator(type_info_range_.second, this));
}
std::pair<const_constructor_iterator, const_constructor_iterator>
constructors() const
{
return std::make_pair(
const_constructor_iterator(constructor_info_range_.first, this),
const_constructor_iterator(constructor_info_range_.second, this));
}
private:
// pairs hold iterators to beginning and end of arrays of information
// generated at compile time
std::pair<const type_info*, const type_info*> type_info_range_;
std::pair<const constructor_info*, const constructor_info*>
constructor_info_range_;
std::pair<const conversion_info*, const conversion_info*>
conversion_info_range_;
std::pair<const string_serialization_info*,
const string_serialization_info*>
string_serialization_info_range_;
std::pair<const free_function_info*, const free_function_info*>
free_function_info_range_;
std::pair<const member_function_info*, const member_function_info*>
member_function_info_range_;
std::pair<const member_variable_info*, const member_variable_info*>
member_variable_info_range_;
// sorted information
std::vector<std::vector<constructor_info>> constructor_info_by_index_;
std::vector<std::vector<conversion_info>> conversion_info_by_index_;
};
}
namespace std
{
// specialize std::iterator_traits for info_iterator_
template <class InfoType, class ProxyType>
struct std::iterator_traits<shadow::info_iterator_<InfoType, ProxyType>>
{
typedef typename shadow::info_iterator_<InfoType, ProxyType>::value_type
value_type;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::difference_type
difference_type;
typedef typename shadow::info_iterator_<InfoType, ProxyType>::reference
reference;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::pointer pointer;
typedef
typename shadow::info_iterator_<InfoType, ProxyType>::iterator_category
iterator_category;
};
}
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/thread_impl.hh>
#include <seastar/core/future.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/timer.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/scheduling.hh>
#include <memory>
#include <setjmp.h>
#include <type_traits>
#include <chrono>
#include <seastar/util/std-compat.hh>
#include <ucontext.h>
#include <boost/intrusive/list.hpp>
/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
/// - seastar threads are cooperative; they are never preempted except
/// at blocking points (see below)
/// - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future<>.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
/// seastar::thread th([] {
/// sleep(5s).get(); // blocking point
/// });
/// \endcode
///
/// An easy way to launch a thread and carry out some computation, and return a
/// result from this execution is by using the \ref seastar::async() function.
/// The result is returned as a future, so that non-threaded code can wait for
/// the thread to terminate and yield a result.
/// Seastar API namespace
namespace seastar {
/// \addtogroup thread-module
/// @{
class thread;
class thread_attributes;
class thread_scheduling_group;
/// Class that holds attributes controling the behavior of a thread.
class thread_attributes {
public:
thread_scheduling_group* scheduling_group = nullptr; // FIXME: remove
compat::optional<seastar::scheduling_group> sched_group;
};
/// \cond internal
extern thread_local jmp_buf_link g_unthreaded_context;
// Internal class holding thread state. We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context {
struct stack_deleter {
void operator()(char *ptr) const noexcept;
};
using stack_holder = std::unique_ptr<char[], stack_deleter>;
static constexpr size_t base_stack_size = 128*1024;
thread_attributes _attr;
#ifdef SEASTAR_THREAD_STACK_GUARDS
const size_t _stack_size;
#else
static constexpr size_t _stack_size = base_stack_size;
#endif
stack_holder _stack{make_stack()};
std::function<void ()> _func;
jmp_buf_link _context;
scheduling_group _scheduling_group;
promise<> _done;
bool _joined = false;
timer<> _sched_timer{[this] { reschedule(); }};
compat::optional<promise<>> _sched_promise;
boost::intrusive::list_member_hook<> _preempted_link;
using preempted_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_preempted_link>,
boost::intrusive::constant_time_size<false>>;
boost::intrusive::list_member_hook<> _all_link;
using all_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_all_link>,
boost::intrusive::constant_time_size<false>>;
static thread_local preempted_thread_list _preempted_threads;
static thread_local all_thread_list _all_threads;
private:
static void s_main(int lo, int hi); // all parameters MUST be 'int' for makecontext
void setup();
void main();
stack_holder make_stack();
public:
thread_context(thread_attributes attr, std::function<void ()> func);
~thread_context();
void switch_in();
void switch_out();
bool should_yield() const;
void reschedule();
void yield();
friend class thread;
friend void thread_impl::switch_in(thread_context*);
friend void thread_impl::switch_out(thread_context*);
friend scheduling_group thread_impl::sched_group(const thread_context*);
};
/// \endcond
/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future. When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
std::unique_ptr<thread_context> _context;
static thread_local thread* _current;
public:
/// \brief Constructs a \c thread object that does not represent a thread
/// of execution.
thread() = default;
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(Func func);
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param attr Attributes describing the new thread.
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(thread_attributes attr, Func func);
/// \brief Moves a thread object.
thread(thread&& x) noexcept = default;
/// \brief Move-assigns a thread object.
thread& operator=(thread&& x) noexcept = default;
/// \brief Destroys a \c thread object.
///
/// The thread must not represent a running thread of execution (see join()).
~thread() { assert(!_context || _context->_joined); }
/// \brief Waits for thread execution to terminate.
///
/// Waits for thread execution to terminate, and marks the thread object as not
/// representing a running thread of execution.
future<> join();
/// \brief Voluntarily defer execution of current thread.
///
/// Gives other threads/fibers a chance to run on current CPU.
/// The current thread will resume execution promptly.
static void yield();
/// \brief Checks whether this thread ought to call yield() now.
///
/// Useful where we cannot call yield() immediately because we
/// Need to take some cleanup action first.
static bool should_yield();
static bool running_in_thread() {
return thread_impl::get() != nullptr;
}
private:
friend class reactor;
// To be used by seastar reactor only.
static bool try_run_one_yielded_thread();
};
/// An instance of this class can be used to assign a thread to a particular scheduling group.
/// Threads can share the same scheduling group if they hold a pointer to the same instance
/// of this class.
///
/// All threads that belongs to a scheduling group will have a time granularity defined by \c period,
/// and can specify a fraction \c usage of that period that indicates the maximum amount of time they
/// expect to run. \c usage, is expected to be a number between 0 and 1 for this to have any effect.
/// Numbers greater than 1 are allowed for simplicity, but they just have the same meaning of 1, alas,
/// "the whole period".
///
/// Note that this is not a preemptive runtime, and a thread will not exit the CPU unless it is scheduled out.
/// In that case, \c usage will not be enforced and the thread will simply run until it loses the CPU.
/// This can happen when a thread waits on a future that is not ready, or when it voluntarily call yield.
///
/// Unlike what happens for a thread that is not part of a scheduling group - which puts itself at the back
/// of the runqueue everytime it yields, a thread that is part of a scheduling group will only yield if
/// it has exhausted its \c usage at the call to yield. Therefore, threads in a schedule group can and
/// should yield often.
///
/// After those events, if the thread has already run for more than its fraction, it will be scheduled to
/// run again only after \c period completes, unless there are no other tasks to run (the system is
/// idle)
class thread_scheduling_group {
std::chrono::nanoseconds _period;
std::chrono::nanoseconds _quota;
std::chrono::time_point<thread_clock> _this_period_ends = {};
std::chrono::time_point<thread_clock> _this_run_start = {};
std::chrono::nanoseconds _this_period_remain = {};
public:
/// \brief Constructs a \c thread_scheduling_group object
///
/// \param period a duration representing the period
/// \param usage which fraction of the \c period to assign for the scheduling group. Expected between 0 and 1.
thread_scheduling_group(std::chrono::nanoseconds period, float usage);
/// \brief changes the current maximum usage per period
///
/// \param new_usage The new fraction of the \c period (Expected between 0 and 1) during which to run
void update_usage(float new_usage) {
_quota = std::chrono::duration_cast<std::chrono::nanoseconds>(new_usage * _period);
}
private:
void account_start();
void account_stop();
compat::optional<thread_clock::time_point> next_scheduling_point() const;
friend class thread_context;
};
template <typename Func>
inline
thread::thread(thread_attributes attr, Func func)
: _context(std::make_unique<thread_context>(std::move(attr), func)) {
}
template <typename Func>
inline
thread::thread(Func func)
: thread(thread_attributes(), std::move(func)) {
}
inline
future<>
thread::join() {
_context->_joined = true;
return _context->_done.get_future();
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param attr a \ref thread_attributes instance
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
///
/// Example:
/// \code
/// future<int> compute_sum(int a, int b) {
/// thread_attributes attr = {};
/// attr.scheduling_group = some_scheduling_group_ptr;
/// return seastar::async(attr, [a, b] {
/// // some blocking code:
/// sleep(1s).get();
/// return a + b;
/// });
/// }
/// \endcode
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(thread_attributes attr, Func&& func, Args&&... args) {
using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
struct work {
thread_attributes attr;
Func func;
std::tuple<Args...> args;
promise<return_type> pr;
thread th;
};
return do_with(work{std::move(attr), std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) mutable {
auto ret = w.pr.get_future();
w.th = thread(std::move(w.attr), [&w] {
futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
});
return w.th.join().then([ret = std::move(ret)] () mutable {
return std::move(ret);
});
});
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) {
return async(thread_attributes{}, std::forward<Func>(func), std::forward<Args>(args)...);
}
/// @}
}
<commit_msg>Deprecate thread_scheduling_group in favor of scheduling_group<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. You may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
#pragma once
#include <seastar/core/thread_impl.hh>
#include <seastar/core/future.hh>
#include <seastar/core/do_with.hh>
#include <seastar/core/future-util.hh>
#include <seastar/core/timer.hh>
#include <seastar/core/reactor.hh>
#include <seastar/core/scheduling.hh>
#include <memory>
#include <setjmp.h>
#include <type_traits>
#include <chrono>
#include <seastar/util/std-compat.hh>
#include <ucontext.h>
#include <boost/intrusive/list.hpp>
/// \defgroup thread-module Seastar threads
///
/// Seastar threads provide an execution environment where blocking
/// is tolerated; you can issue I/O, and wait for it in the same function,
/// rather then establishing a callback to be called with \ref future<>::then().
///
/// Seastar threads are not the same as operating system threads:
/// - seastar threads are cooperative; they are never preempted except
/// at blocking points (see below)
/// - seastar threads always run on the same core they were launched on
///
/// Like other seastar code, seastar threads may not issue blocking system calls.
///
/// A seastar thread blocking point is any function that returns a \ref future<>.
/// you block by calling \ref future<>::get(); this waits for the future to become
/// available, and in the meanwhile, other seastar threads and seastar non-threaded
/// code may execute.
///
/// Example:
/// \code
/// seastar::thread th([] {
/// sleep(5s).get(); // blocking point
/// });
/// \endcode
///
/// An easy way to launch a thread and carry out some computation, and return a
/// result from this execution is by using the \ref seastar::async() function.
/// The result is returned as a future, so that non-threaded code can wait for
/// the thread to terminate and yield a result.
/// Seastar API namespace
namespace seastar {
/// \addtogroup thread-module
/// @{
class thread;
class thread_attributes;
class thread_scheduling_group;
/// Class that holds attributes controling the behavior of a thread.
class thread_attributes {
public:
thread_scheduling_group* scheduling_group = nullptr; // FIXME: remove
compat::optional<seastar::scheduling_group> sched_group;
};
/// \cond internal
extern thread_local jmp_buf_link g_unthreaded_context;
// Internal class holding thread state. We can't hold this in
// \c thread itself because \c thread is movable, and we want pointers
// to this state to be captured.
class thread_context {
struct stack_deleter {
void operator()(char *ptr) const noexcept;
};
using stack_holder = std::unique_ptr<char[], stack_deleter>;
static constexpr size_t base_stack_size = 128*1024;
thread_attributes _attr;
#ifdef SEASTAR_THREAD_STACK_GUARDS
const size_t _stack_size;
#else
static constexpr size_t _stack_size = base_stack_size;
#endif
stack_holder _stack{make_stack()};
std::function<void ()> _func;
jmp_buf_link _context;
scheduling_group _scheduling_group;
promise<> _done;
bool _joined = false;
timer<> _sched_timer{[this] { reschedule(); }};
compat::optional<promise<>> _sched_promise;
boost::intrusive::list_member_hook<> _preempted_link;
using preempted_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_preempted_link>,
boost::intrusive::constant_time_size<false>>;
boost::intrusive::list_member_hook<> _all_link;
using all_thread_list = boost::intrusive::list<thread_context,
boost::intrusive::member_hook<thread_context, boost::intrusive::list_member_hook<>,
&thread_context::_all_link>,
boost::intrusive::constant_time_size<false>>;
static thread_local preempted_thread_list _preempted_threads;
static thread_local all_thread_list _all_threads;
private:
static void s_main(int lo, int hi); // all parameters MUST be 'int' for makecontext
void setup();
void main();
stack_holder make_stack();
public:
thread_context(thread_attributes attr, std::function<void ()> func);
~thread_context();
void switch_in();
void switch_out();
bool should_yield() const;
void reschedule();
void yield();
friend class thread;
friend void thread_impl::switch_in(thread_context*);
friend void thread_impl::switch_out(thread_context*);
friend scheduling_group thread_impl::sched_group(const thread_context*);
};
/// \endcond
/// \brief thread - stateful thread of execution
///
/// Threads allow using seastar APIs in a blocking manner,
/// by calling future::get() on a non-ready future. When
/// this happens, the thread is put to sleep until the future
/// becomes ready.
class thread {
std::unique_ptr<thread_context> _context;
static thread_local thread* _current;
public:
/// \brief Constructs a \c thread object that does not represent a thread
/// of execution.
thread() = default;
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(Func func);
/// \brief Constructs a \c thread object that represents a thread of execution
///
/// \param attr Attributes describing the new thread.
/// \param func Callable object to execute in thread. The callable is
/// called immediately.
template <typename Func>
thread(thread_attributes attr, Func func);
/// \brief Moves a thread object.
thread(thread&& x) noexcept = default;
/// \brief Move-assigns a thread object.
thread& operator=(thread&& x) noexcept = default;
/// \brief Destroys a \c thread object.
///
/// The thread must not represent a running thread of execution (see join()).
~thread() { assert(!_context || _context->_joined); }
/// \brief Waits for thread execution to terminate.
///
/// Waits for thread execution to terminate, and marks the thread object as not
/// representing a running thread of execution.
future<> join();
/// \brief Voluntarily defer execution of current thread.
///
/// Gives other threads/fibers a chance to run on current CPU.
/// The current thread will resume execution promptly.
static void yield();
/// \brief Checks whether this thread ought to call yield() now.
///
/// Useful where we cannot call yield() immediately because we
/// Need to take some cleanup action first.
static bool should_yield();
static bool running_in_thread() {
return thread_impl::get() != nullptr;
}
private:
friend class reactor;
// To be used by seastar reactor only.
static bool try_run_one_yielded_thread();
};
/// An instance of this class can be used to assign a thread to a particular scheduling group.
/// Threads can share the same scheduling group if they hold a pointer to the same instance
/// of this class.
///
/// All threads that belongs to a scheduling group will have a time granularity defined by \c period,
/// and can specify a fraction \c usage of that period that indicates the maximum amount of time they
/// expect to run. \c usage, is expected to be a number between 0 and 1 for this to have any effect.
/// Numbers greater than 1 are allowed for simplicity, but they just have the same meaning of 1, alas,
/// "the whole period".
///
/// Note that this is not a preemptive runtime, and a thread will not exit the CPU unless it is scheduled out.
/// In that case, \c usage will not be enforced and the thread will simply run until it loses the CPU.
/// This can happen when a thread waits on a future that is not ready, or when it voluntarily call yield.
///
/// Unlike what happens for a thread that is not part of a scheduling group - which puts itself at the back
/// of the runqueue everytime it yields, a thread that is part of a scheduling group will only yield if
/// it has exhausted its \c usage at the call to yield. Therefore, threads in a schedule group can and
/// should yield often.
///
/// After those events, if the thread has already run for more than its fraction, it will be scheduled to
/// run again only after \c period completes, unless there are no other tasks to run (the system is
/// idle)
///
/// \deprecated This class has been replaced by \ref scheduling_group, which can be used to schedule
/// both threads and continuations.
class [[deprecated("Use seastar::scheduling_group instead")]] thread_scheduling_group {
std::chrono::nanoseconds _period;
std::chrono::nanoseconds _quota;
std::chrono::time_point<thread_clock> _this_period_ends = {};
std::chrono::time_point<thread_clock> _this_run_start = {};
std::chrono::nanoseconds _this_period_remain = {};
public:
/// \brief Constructs a \c thread_scheduling_group object
///
/// \param period a duration representing the period
/// \param usage which fraction of the \c period to assign for the scheduling group. Expected between 0 and 1.
thread_scheduling_group(std::chrono::nanoseconds period, float usage);
/// \brief changes the current maximum usage per period
///
/// \param new_usage The new fraction of the \c period (Expected between 0 and 1) during which to run
void update_usage(float new_usage) {
_quota = std::chrono::duration_cast<std::chrono::nanoseconds>(new_usage * _period);
}
private:
void account_start();
void account_stop();
compat::optional<thread_clock::time_point> next_scheduling_point() const;
friend class thread_context;
};
template <typename Func>
inline
thread::thread(thread_attributes attr, Func func)
: _context(std::make_unique<thread_context>(std::move(attr), func)) {
}
template <typename Func>
inline
thread::thread(Func func)
: thread(thread_attributes(), std::move(func)) {
}
inline
future<>
thread::join() {
_context->_joined = true;
return _context->_done.get_future();
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param attr a \ref thread_attributes instance
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
///
/// Example:
/// \code
/// future<int> compute_sum(int a, int b) {
/// thread_attributes attr = {};
/// attr.scheduling_group = some_scheduling_group_ptr;
/// return seastar::async(attr, [a, b] {
/// // some blocking code:
/// sleep(1s).get();
/// return a + b;
/// });
/// }
/// \endcode
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(thread_attributes attr, Func&& func, Args&&... args) {
using return_type = std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>;
struct work {
thread_attributes attr;
Func func;
std::tuple<Args...> args;
promise<return_type> pr;
thread th;
};
return do_with(work{std::move(attr), std::forward<Func>(func), std::forward_as_tuple(std::forward<Args>(args)...)}, [] (work& w) mutable {
auto ret = w.pr.get_future();
w.th = thread(std::move(w.attr), [&w] {
futurize<return_type>::apply(std::move(w.func), std::move(w.args)).forward_to(std::move(w.pr));
});
return w.th.join().then([ret = std::move(ret)] () mutable {
return std::move(ret);
});
});
}
/// Executes a callable in a seastar thread.
///
/// Runs a block of code in a threaded context,
/// which allows it to block (using \ref future::get()). The
/// result of the callable is returned as a future.
///
/// \param func a callable to be executed in a thread
/// \param args a parameter pack to be forwarded to \c func.
/// \return whatever \c func returns, as a future.
template <typename Func, typename... Args>
inline
futurize_t<std::result_of_t<std::decay_t<Func>(std::decay_t<Args>...)>>
async(Func&& func, Args&&... args) {
return async(thread_attributes{}, std::forward<Func>(func), std::forward<Args>(args)...);
}
/// @}
}
<|endoftext|> |
<commit_before><commit_msg>Typo: deprected->deprecated<commit_after><|endoftext|> |
<commit_before>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <vector>
#include <cmath>
#include <cstddef>
#include <Eigen/Dense>
#include <Random123/aes.h>
#include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/conventional/Engine.hpp>
#include <vSMC/internal/config.hpp>
#include <vSMC/internal/random.hpp>
/// The Parallel RNG (based on Rand123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED
/// The Parallel RNG (based on Rand123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE
namespace vSMC {
template <typename T> class Sampler;
/// Resample scheme
enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC,
RESIDUAL_STRATIFIED, RESIDUAL_SYSTEMATIC};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
typedef r123::Engine< V_SMC_CRNG_TYPE > rng_type;
typedef rng_type::result_type seed_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
explicit Particle (std::size_t N,
rng_type::result_type seed = V_SMC_CRNG_SEED) :
size_(N), value_(N), sampler_(NULL),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(N), resampled_(false), zconst_(0), prng_(N)
{
reset_prng(seed);
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
std::size_t size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (T &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
T &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const T &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weights
///
/// \note The Particle class guarantee that during the life type of the
/// object, the pointer returned by this always valid and point to the
/// same address
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weights
const double *log_weight_ptr () const
{
return log_weight_.data();
}
const Eigen::VectorXd &weight () const
{
return weight_;
}
const Eigen::VectorXd &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Read only access to the sampler containing this particle set
///
/// \return A const reference to the sampler containing this particle set
const Sampler<T> &sampler () const
{
return *sampler_;
}
/// \brief Set which sampler this particle belongs to
///
/// \param samp A const pointer to the sampler
void sampler (const Sampler<T> *samp)
{
sampler_ = samp;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
}
rng_type &prng (std::size_t id)
{
return prng_[id];
}
void reset_prng (rng_type::result_type seed)
{
for (std::size_t i = 0; i != size_; ++i)
prng_[i] = rng_type(seed + i);
}
private :
std::size_t size_;
T value_;
const Sampler<T> *sampler_;
Eigen::VectorXd weight_;
Eigen::VectorXd log_weight_;
Eigen::VectorXd inc_weight_;
Eigen::VectorXi replication_;
double ess_;
bool resampled_;
double zconst_;
std::vector<rng_type> prng_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
std::size_t size = weight_.sum();
weight_ /= size;
std::size_t j = 0;
std::size_t k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (std::size_t i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (std::size_t size)
{
double tp = weight_.sum();
double sum_p = 0;
std::size_t sum_n = 0;
replication_.setConstant(0);
for (std::size_t i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
internal::binomial_distribution<>
binom(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(prng_[i]);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
std::size_t sum = replication_.sum();
if (sum != size_) {
Eigen::VectorXd::Index id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
std::size_t from = 0;
std::size_t time = 0;
for (std::size_t to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<commit_msg>add a few typedefs for particle, ensure index is never too large for Eigen::VectorXd<commit_after>#ifndef V_SMC_CORE_PARTICLE_HPP
#define V_SMC_CORE_PARTICLE_HPP
#include <cmath>
#include <cstddef>
#include <Eigen/Dense>
#include <Random123/aes.h>
#include <Random123/ars.h>
#include <Random123/philox.h>
#include <Random123/threefry.h>
#include <Random123/conventional/Engine.hpp>
#include <vSMC/internal/config.hpp>
#include <vSMC/internal/random.hpp>
/// The Parallel RNG (based on Rand123) seed, unsigned
#ifndef V_SMC_CRNG_SEED
#define V_SMC_CRNG_SEED 0xdeadbeefU
#endif // V_SMC_CRNG_SEED
/// The Parallel RNG (based on Rand123) type, philox or threefry
#ifndef V_SMC_CRNG_TYPE
#define V_SMC_CRNG_TYPE r123::Threefry4x64
#endif // V_SMC_CRNG_TYPE
namespace vSMC {
template <typename T> class Sampler;
/// Resample scheme
enum ResampleScheme {MULTINOMIAL, RESIDUAL, STRATIFIED, SYSTEMATIC,
RESIDUAL_STRATIFIED, RESIDUAL_SYSTEMATIC};
/// \brief Particle class
///
/// Particle class store the particle set and arrays of weights and log
/// weights. It provides access to particle values as well as weights. It
/// computes and manages resources for ESS, resampling, etc, tasks unique to
/// each iteration.
template <typename T>
class Particle
{
public :
/// The type of the particle values
typedef T value_type;
/// The type of the size of the particles
typedef EIGEN_DEFAULT_DENSE_INDEX_TYPE size_type;
/// The type of the Counter-based random number generator
typedef r123::Engine< V_SMC_CRNG_TYPE > rng_type;
/// The integer type of the seed
typedef rng_type::result_type seed_type;
/// The type of the weight and log weight vectors
typedef Eigen::VectorXd weight_type;
/// \brief Construct a Particle object with given number of particles
///
/// \param N The number of particles
/// \param seed The seed to the parallel RNG system
explicit Particle (size_type N, seed_type seed = V_SMC_CRNG_SEED) :
size_(N), value_(N), sampler_(NULL),
weight_(N), log_weight_(N), inc_weight_(N), replication_(N),
ess_(N), resampled_(false), zconst_(0), prng_(N)
{
reset_prng(seed);
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
/// \brief Size of the particle set
///
/// \return The number of particles
size_type size () const
{
return size_;
}
/// \brief Read and write access to particle values
///
/// \return A reference to the particle values, type (value_type &)
///
/// \note The Particle class guarantee that during the life type of the
/// object, the reference returned by this member will no be a dangle
/// handler.
value_type &value ()
{
return value_;
}
/// \brief Read only access to particle values
///
/// \return A const reference to the particle values
const value_type &value () const
{
return value_;
}
/// \brief Read only access to the weights
///
/// \return A const pointer to the weight array
///
/// \note When the system changes, this pointer may be invalidated
const double *weight_ptr () const
{
return weight_.data();
}
/// \brief Read only access to the log weights
///
/// \return A const pointer to the log weight array
///
/// \note When the system changes, this pointer may be invalidated
const double *log_weight_ptr () const
{
return log_weight_.data();
}
/// \brief Read only access to the weights
///
/// \return A const reference to the weight vector
///
/// \note When the system changes, this reference may be invalidated
const weight_type &weight () const
{
return weight_;
}
/// \brief Read only access to the log weights
///
/// \return A const reference to the log weight vector
///
/// \note When the system changes, this reference may be invalidated
const weight_type &log_weight () const
{
return log_weight_;
}
/// \brief Set the log weights
///
/// \param new_weight New log weights
/// \param delta A multiplier appiled to new_weight
void set_log_weight (const double *new_weight, double delta = 1)
{
Eigen::Map<const Eigen::VectorXd> w(new_weight, size_);
log_weight_ = delta * w;
set_weight();
}
/// \brief Add to the log weights
///
/// \param inc_weight Incremental log weights
/// \param delta A multiplier applied to inc_weight
/// \param add_zconst Whether this incremental weights should contribute
/// the esitmates of normalizing constants
void add_log_weight (const double *inc_weight, double delta = 1,
bool add_zconst = true)
{
Eigen::Map<const Eigen::VectorXd> w(inc_weight, size_);
if (add_zconst) {
inc_weight_ = (delta * w).array().exp();
zconst_ += std::log(weight_.dot(inc_weight_));
}
log_weight_ += delta * w;
set_weight();
}
/// \brief The ESS (Effective Sample Size)
///
/// \return The value of ESS for current particle set
double ess () const
{
return ess_;
}
/// \brief Get indicator of resampling
///
/// \return A bool value, \b true if the current iteration was resampled
bool resampled () const
{
return resampled_;
}
/// \brief Set indicator of resampling
///
/// \param resampled \b true if the current iteration was resampled
void resampled (bool resampled)
{
resampled_ = resampled;
}
/// \brief Read only access to the sampler containing this particle set
///
/// \return A const reference to the sampler containing this particle set
const Sampler<value_type> &sampler () const
{
return *sampler_;
}
/// \brief Set which sampler this particle belongs to
///
/// \param samp A const pointer to the sampler
void sampler (const Sampler<value_type> *samp)
{
sampler_ = samp;
}
/// \brief Get the value of SMC normalizing constant
///
/// \return SMC normalizng constant estimate
double zconst () const
{
return zconst_;
}
/// \brief Reset the value of SMC normalizing constant
void reset_zconst ()
{
zconst_ = 0;
}
/// \brief Perform resampling
///
/// \param scheme The resampling scheme, see ResamplingScheme
void resample (ResampleScheme scheme)
{
switch (scheme) {
case MULTINOMIAL :
resample_multinomial();
break;
case RESIDUAL :
resample_residual();
break;
case STRATIFIED :
resample_stratified();
break;
case SYSTEMATIC :
resample_systematic();
break;
case RESIDUAL_STRATIFIED :
resample_residual_stratified ();
break;
default :
resample_stratified();
break;
}
resample_do();
}
rng_type &prng (size_type id)
{
return prng_[id];
}
void reset_prng (rng_type::result_type seed)
{
for (size_type i = 0; i != size_; ++i)
prng_[i] = rng_type(seed + i);
}
private :
typedef Eigen::Matrix<size_type, Eigen::Dynamic, 1> replication_type;
typedef Eigen::Matrix<rng_type, Eigen::Dynamic, 1> prng_type;
size_type size_;
value_type value_;
const Sampler<value_type> *sampler_;
weight_type weight_;
weight_type log_weight_;
weight_type inc_weight_;
replication_type replication_;
double ess_;
bool resampled_;
double zconst_;
prng_type prng_;
void set_weight ()
{
double max_weight = log_weight_.maxCoeff();
log_weight_ = log_weight_.array() - max_weight;
weight_ = log_weight_.array().exp();
double sum = weight_.sum();
weight_ *= 1 / sum;
ess_ = 1 / weight_.squaredNorm();
}
void resample_multinomial ()
{
weight2replication(size_);
}
void resample_residual ()
{
// Reuse weight and log_weight. weight: act as the fractional part of
// N * weight. log_weight: act as the integral part of N * weight.
// They all will be reset to equal weights after resampling. So it is
// safe to modify them here.
for (size_type i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
weight2replication(weight_.sum());
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_stratified ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_systematic ()
{
replication_.setConstant(0);
size_type j = 0;
size_type k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size_) {
while (j < cw * size_ - u && j != size_) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
}
void resample_residual_stratified ()
{
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
u = unif(prng_[j++]);
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void resample_residual_systematic ()
{
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i)
weight_[i] = std::modf(size_ * weight_[i], log_weight_.data() + i);
size_type size = weight_.sum();
weight_ /= size;
size_type j = 0;
size_type k = 0;
internal::uniform_real_distribution<> unif(0,1);
double u = unif(prng_[0]);
double cw = weight_[0];
while (j != size) {
while (j < cw * size - u && j != size) {
++replication_[k];
++j;
}
if (k == size_ - 1)
break;
cw += weight_[++k];
}
for (size_type i = 0; i != size_; ++i)
replication_[i] += log_weight_[i];
}
void weight2replication (size_type size)
{
double tp = weight_.sum();
double sum_p = 0;
size_type sum_n = 0;
replication_.setConstant(0);
for (size_type i = 0; i != size_; ++i) {
if (sum_n < size && weight_[i] > 0) {
internal::binomial_distribution<>
binom(size - sum_n, weight_[i] / (tp - sum_p));
replication_[i] = binom(prng_[i]);
}
sum_p += weight_[i];
sum_n += replication_[i];
}
}
void resample_do ()
{
// Some times the nuemrical round error can cause the total childs
// differ from number of particles
size_type sum = replication_.sum();
if (sum != size_) {
size_type id_max;
replication_.maxCoeff(&id_max);
replication_[id_max] += size_ - sum;
}
size_type from = 0;
size_type time = 0;
for (size_type to = 0; to != size_; ++to) {
if (!replication_[to]) {
// replication_[to] has zero child, copy from elsewhere
if (replication_[from] - time <= 1) {
// only 1 child left on replication_[from]
time = 0;
do // move from to some position with at least 2 children
++from;
while (replication_[from] < 2);
}
value_.copy(from, to);
++time;
}
}
ess_ = size_;
weight_.setConstant(1.0 / size_);
log_weight_.setConstant(0);
}
}; // class Particle
} // namespace vSMC
#endif // V_SMC_CORE_PARTICLE_HPP
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in Section and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <ctime>
#include <nix/util/util.hpp>
#include "TestSection.hpp"
using namespace std;
using namespace nix;
void TestSection::setUp() {
startup_time = time(NULL);
file = File::open("test_section.h5", FileMode::Overwrite);
section = file.createSection("section", "metadata");
section_other = file.createSection("other_section", "metadata");
section_null = nullptr;
}
void TestSection::tearDown() {
file.close();
}
void TestSection::testValidate() {
std::cout << std::endl << section.validate();
}
void TestSection::testId() {
CPPUNIT_ASSERT(section.id().size() == 24);
}
void TestSection::testName() {
CPPUNIT_ASSERT(section.name() == "section");
string name = util::createId("", 32);
section.name(name);
CPPUNIT_ASSERT(section.name() == name);
}
void TestSection::testType() {
CPPUNIT_ASSERT(section.type() == "metadata");
string typ = util::createId("", 32);
section.type(typ);
CPPUNIT_ASSERT(section.type() == typ);
}
void TestSection::testDefinition() {
string def = util::createId("", 128);
section.definition(def);
CPPUNIT_ASSERT(*section.definition() == def);
section.definition(nix::none);
CPPUNIT_ASSERT(section.definition() == nix::none);
}
void TestSection::testParent() {
CPPUNIT_ASSERT(section.parent() == nullptr);
Section child = section.createSection("child", "section");
CPPUNIT_ASSERT(child.parent() != nullptr);
CPPUNIT_ASSERT(child.parent().id() == section.id());
CPPUNIT_ASSERT(child.parent().parent() == nullptr);
}
void TestSection::testRepository() {
CPPUNIT_ASSERT(!section.repository());
string rep = "http://foo.bar/" + util::createId("", 32);
section.repository(rep);
CPPUNIT_ASSERT(section.repository() == rep);
section.repository(boost::none);
CPPUNIT_ASSERT(!section.repository());
}
void TestSection::testLink() {
CPPUNIT_ASSERT(!section.link());
section.link(section_other);
CPPUNIT_ASSERT(section.link());
CPPUNIT_ASSERT(section.link().id() == section_other.id());
section.link(boost::none);
CPPUNIT_ASSERT(!section.link());
}
void TestSection::testMapping() {
CPPUNIT_ASSERT(!section.mapping());
string map = "http://foo.bar/" + util::createId("", 32);
section.mapping(map);
CPPUNIT_ASSERT(section.mapping() == map);
section.mapping(boost::none);
CPPUNIT_ASSERT(!section.mapping());
}
void TestSection::testSectionAccess() {
vector<string> names = { "section_a", "section_b", "section_c", "section_d", "section_e" };
CPPUNIT_ASSERT(section.sectionCount() == 0);
CPPUNIT_ASSERT(section.sections().size() == 0);
CPPUNIT_ASSERT(section.getSection("invalid_id") == false);
vector<string> ids;
for (auto name : names) {
Section child_section = section.createSection(name, "metadata");
CPPUNIT_ASSERT(child_section.name() == name);
ids.push_back(child_section.id());
}
CPPUNIT_ASSERT(section.sectionCount() == names.size());
CPPUNIT_ASSERT(section.sections().size() == names.size());
for (auto id : ids) {
Section child_section = section.getSection(id);
CPPUNIT_ASSERT(section.hasSection(id) == true);
CPPUNIT_ASSERT(child_section.id() == id);
section.deleteSection(id);
}
CPPUNIT_ASSERT(section.sectionCount() == 0);
CPPUNIT_ASSERT(section.sections().size() == 0);
CPPUNIT_ASSERT(section.getSection("invalid_id") == false);
}
void TestSection::testFindSection() {
// prepare
Section l1n1 = section.createSection("l1n1", "typ1");
Section l1n2 = section.createSection("l1n2", "typ2");
Section l1n3 = section.createSection("l1n3", "typ3");
Section l2n1 = l1n1.createSection("l2n1", "typ1");
Section l2n2 = l1n1.createSection("l2n2", "typ2");
Section l2n3 = l1n1.createSection("l2n3", "typ2");
Section l2n4 = l1n3.createSection("l2n4", "typ2");
Section l2n5 = l1n3.createSection("l2n5", "typ2");
Section l2n6 = l1n3.createSection("l2n6", "typ3");
Section l3n1 = l2n1.createSection("l2n3", "typ1");
Section l3n2 = l2n3.createSection("l2n3", "typ2");
Section l3n3 = l2n3.createSection("l2n3", "typ2");
Section l3n4 = l2n5.createSection("l2n3", "typ2");
// test depth limit
CPPUNIT_ASSERT(section.findSections().size() == 14);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 2).size() == 10);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 1).size() == 4);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 0).size() == 1);
// test filter
auto filter_typ1 = util::TypeFilter<Section>("typ1");
auto filter_typ2 = util::TypeFilter<Section>("typ2");
CPPUNIT_ASSERT(section.findSections(filter_typ1).size() == 3);
CPPUNIT_ASSERT(section.findSections(filter_typ2).size() == 8);
}
void TestSection::testFindRelated(){
Section l1n1 = section.createSection("l1n1", "typ1");
Section l2n1 = l1n1.createSection("l2n1", "t1");
Section l2n2 = l1n1.createSection("l2n2", "t2");
Section l3n1 = l2n1.createSection("l3n1", "t3");
Section l3n2 = l2n2.createSection("l3n2", "t3");
Section l3n3 = l2n2.createSection("l3n3", "t4");
Section l4n1 = l3n2.createSection("l4n1", "typ2");
Section l4n2 = l3n3.createSection("l4n2", "typ2");
Section l5n1 = l4n1.createSection("l5n1", "typ2");
string t1 = "t1";
string t3 = "t3";
string t4 = "t4";
string typ2 = "typ2";
string typ1 = "typ1";
vector<Section> related = l1n1.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l1n1.findRelated(util::TypeFilter<Section>(t3));
CPPUNIT_ASSERT(related.size() == 2);
related = l1n1.findRelated(util::TypeFilter<Section>(t4));
CPPUNIT_ASSERT(related.size() == 1);
related = l1n1.findRelated(util::TypeFilter<Section>(typ2));
CPPUNIT_ASSERT(related.size() == 2);
related = l4n1.findRelated(util::TypeFilter<Section>(typ1));
CPPUNIT_ASSERT(related.size() == 1);
related = l4n1.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l3n2.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l3n2.findRelated(util::TypeFilter<Section>(t3));
CPPUNIT_ASSERT(related.size() == 0);
section.deleteSection(l1n1.id());
}
void TestSection::testPropertyAccess() {
vector<string> names = { "property_a", "property_b", "property_c", "property_d", "property_e" };
CPPUNIT_ASSERT(section.propertyCount() == 0);
CPPUNIT_ASSERT(section.properties().size() == 0);
CPPUNIT_ASSERT(section.getProperty("invalid_id") == false);
Property p = section.createProperty("empty_prop", DataType::Double);
CPPUNIT_ASSERT(section.propertyCount() == 1);
Property prop = section.getPropertyByName("empty_prop");
CPPUNIT_ASSERT(prop.dataType() == nix::DataType::Double);
section.deleteProperty(p.id());
CPPUNIT_ASSERT(section.propertyCount() == 0);
Value dummy(10);
prop = section.createProperty("single value", dummy);
CPPUNIT_ASSERT(section.hasPropertyWithName("single value"));
CPPUNIT_ASSERT(section.propertyCount() == 1);
section.deleteProperty(prop.id());
CPPUNIT_ASSERT(section.propertyCount() == 0);
vector<string> ids;
for (auto name : names) {
prop = section.createProperty(name, dummy);
CPPUNIT_ASSERT(prop.name() == name);
CPPUNIT_ASSERT(section.hasPropertyWithName(name));
Property prop_copy = section.getPropertyByName(name);
CPPUNIT_ASSERT(prop_copy.id() == prop.id());
ids.push_back(prop.id());
}
CPPUNIT_ASSERT(section.propertyCount() == names.size());
CPPUNIT_ASSERT(section.properties().size() == names.size());
section_other.createProperty("some_prop", dummy);
section_other.link(section);
CPPUNIT_ASSERT(section_other.propertyCount() == 1);
CPPUNIT_ASSERT(section_other.inheritedProperties().size() == names.size() + 1);
for (auto id : ids) {
Property prop = section.getProperty(id);
CPPUNIT_ASSERT(section.hasProperty(id));
CPPUNIT_ASSERT(prop.id() == id);
section.deleteProperty(id);
}
CPPUNIT_ASSERT(section.propertyCount() == 0);
CPPUNIT_ASSERT(section.properties().size() == 0);
CPPUNIT_ASSERT(section.getProperty("invalid_id") == false);
vector<Value> values;
values.push_back(Value(10));
values.push_back(Value(100));
section.createProperty("another test", values);
CPPUNIT_ASSERT(section.propertyCount() == 1);
prop = section.getPropertyByName("another test");
CPPUNIT_ASSERT(prop.valueCount() == 2);
}
void TestSection::testOperators() {
CPPUNIT_ASSERT(section_null == false);
CPPUNIT_ASSERT(section_null == none);
CPPUNIT_ASSERT(section != false);
CPPUNIT_ASSERT(section != none);
CPPUNIT_ASSERT(section == section);
CPPUNIT_ASSERT(section != section_other);
section_other = section;
CPPUNIT_ASSERT(section == section_other);
section_other = none;
CPPUNIT_ASSERT(section_null == false);
CPPUNIT_ASSERT(section_null == none);
}
void TestSection::testCreatedAt() {
CPPUNIT_ASSERT(section.createdAt() >= startup_time);
time_t past_time = time(NULL) - 10000000;
section.forceCreatedAt(past_time);
CPPUNIT_ASSERT(section.createdAt() == past_time);
}
void TestSection::testUpdatedAt() {
CPPUNIT_ASSERT(section.updatedAt() >= startup_time);
}
<commit_msg>added test that empty values indeed returns zero value count<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in Section and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <ctime>
#include <nix/util/util.hpp>
#include "TestSection.hpp"
using namespace std;
using namespace nix;
void TestSection::setUp() {
startup_time = time(NULL);
file = File::open("test_section.h5", FileMode::Overwrite);
section = file.createSection("section", "metadata");
section_other = file.createSection("other_section", "metadata");
section_null = nullptr;
}
void TestSection::tearDown() {
file.close();
}
void TestSection::testValidate() {
std::cout << std::endl << section.validate();
}
void TestSection::testId() {
CPPUNIT_ASSERT(section.id().size() == 24);
}
void TestSection::testName() {
CPPUNIT_ASSERT(section.name() == "section");
string name = util::createId("", 32);
section.name(name);
CPPUNIT_ASSERT(section.name() == name);
}
void TestSection::testType() {
CPPUNIT_ASSERT(section.type() == "metadata");
string typ = util::createId("", 32);
section.type(typ);
CPPUNIT_ASSERT(section.type() == typ);
}
void TestSection::testDefinition() {
string def = util::createId("", 128);
section.definition(def);
CPPUNIT_ASSERT(*section.definition() == def);
section.definition(nix::none);
CPPUNIT_ASSERT(section.definition() == nix::none);
}
void TestSection::testParent() {
CPPUNIT_ASSERT(section.parent() == nullptr);
Section child = section.createSection("child", "section");
CPPUNIT_ASSERT(child.parent() != nullptr);
CPPUNIT_ASSERT(child.parent().id() == section.id());
CPPUNIT_ASSERT(child.parent().parent() == nullptr);
}
void TestSection::testRepository() {
CPPUNIT_ASSERT(!section.repository());
string rep = "http://foo.bar/" + util::createId("", 32);
section.repository(rep);
CPPUNIT_ASSERT(section.repository() == rep);
section.repository(boost::none);
CPPUNIT_ASSERT(!section.repository());
}
void TestSection::testLink() {
CPPUNIT_ASSERT(!section.link());
section.link(section_other);
CPPUNIT_ASSERT(section.link());
CPPUNIT_ASSERT(section.link().id() == section_other.id());
section.link(boost::none);
CPPUNIT_ASSERT(!section.link());
}
void TestSection::testMapping() {
CPPUNIT_ASSERT(!section.mapping());
string map = "http://foo.bar/" + util::createId("", 32);
section.mapping(map);
CPPUNIT_ASSERT(section.mapping() == map);
section.mapping(boost::none);
CPPUNIT_ASSERT(!section.mapping());
}
void TestSection::testSectionAccess() {
vector<string> names = { "section_a", "section_b", "section_c", "section_d", "section_e" };
CPPUNIT_ASSERT(section.sectionCount() == 0);
CPPUNIT_ASSERT(section.sections().size() == 0);
CPPUNIT_ASSERT(section.getSection("invalid_id") == false);
vector<string> ids;
for (auto name : names) {
Section child_section = section.createSection(name, "metadata");
CPPUNIT_ASSERT(child_section.name() == name);
ids.push_back(child_section.id());
}
CPPUNIT_ASSERT(section.sectionCount() == names.size());
CPPUNIT_ASSERT(section.sections().size() == names.size());
for (auto id : ids) {
Section child_section = section.getSection(id);
CPPUNIT_ASSERT(section.hasSection(id) == true);
CPPUNIT_ASSERT(child_section.id() == id);
section.deleteSection(id);
}
CPPUNIT_ASSERT(section.sectionCount() == 0);
CPPUNIT_ASSERT(section.sections().size() == 0);
CPPUNIT_ASSERT(section.getSection("invalid_id") == false);
}
void TestSection::testFindSection() {
// prepare
Section l1n1 = section.createSection("l1n1", "typ1");
Section l1n2 = section.createSection("l1n2", "typ2");
Section l1n3 = section.createSection("l1n3", "typ3");
Section l2n1 = l1n1.createSection("l2n1", "typ1");
Section l2n2 = l1n1.createSection("l2n2", "typ2");
Section l2n3 = l1n1.createSection("l2n3", "typ2");
Section l2n4 = l1n3.createSection("l2n4", "typ2");
Section l2n5 = l1n3.createSection("l2n5", "typ2");
Section l2n6 = l1n3.createSection("l2n6", "typ3");
Section l3n1 = l2n1.createSection("l2n3", "typ1");
Section l3n2 = l2n3.createSection("l2n3", "typ2");
Section l3n3 = l2n3.createSection("l2n3", "typ2");
Section l3n4 = l2n5.createSection("l2n3", "typ2");
// test depth limit
CPPUNIT_ASSERT(section.findSections().size() == 14);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 2).size() == 10);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 1).size() == 4);
CPPUNIT_ASSERT(section.findSections(util::AcceptAll<Section>(), 0).size() == 1);
// test filter
auto filter_typ1 = util::TypeFilter<Section>("typ1");
auto filter_typ2 = util::TypeFilter<Section>("typ2");
CPPUNIT_ASSERT(section.findSections(filter_typ1).size() == 3);
CPPUNIT_ASSERT(section.findSections(filter_typ2).size() == 8);
}
void TestSection::testFindRelated(){
Section l1n1 = section.createSection("l1n1", "typ1");
Section l2n1 = l1n1.createSection("l2n1", "t1");
Section l2n2 = l1n1.createSection("l2n2", "t2");
Section l3n1 = l2n1.createSection("l3n1", "t3");
Section l3n2 = l2n2.createSection("l3n2", "t3");
Section l3n3 = l2n2.createSection("l3n3", "t4");
Section l4n1 = l3n2.createSection("l4n1", "typ2");
Section l4n2 = l3n3.createSection("l4n2", "typ2");
Section l5n1 = l4n1.createSection("l5n1", "typ2");
string t1 = "t1";
string t3 = "t3";
string t4 = "t4";
string typ2 = "typ2";
string typ1 = "typ1";
vector<Section> related = l1n1.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l1n1.findRelated(util::TypeFilter<Section>(t3));
CPPUNIT_ASSERT(related.size() == 2);
related = l1n1.findRelated(util::TypeFilter<Section>(t4));
CPPUNIT_ASSERT(related.size() == 1);
related = l1n1.findRelated(util::TypeFilter<Section>(typ2));
CPPUNIT_ASSERT(related.size() == 2);
related = l4n1.findRelated(util::TypeFilter<Section>(typ1));
CPPUNIT_ASSERT(related.size() == 1);
related = l4n1.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l3n2.findRelated(util::TypeFilter<Section>(t1));
CPPUNIT_ASSERT(related.size() == 1);
related = l3n2.findRelated(util::TypeFilter<Section>(t3));
CPPUNIT_ASSERT(related.size() == 0);
section.deleteSection(l1n1.id());
}
void TestSection::testPropertyAccess() {
vector<string> names = { "property_a", "property_b", "property_c", "property_d", "property_e" };
CPPUNIT_ASSERT(section.propertyCount() == 0);
CPPUNIT_ASSERT(section.properties().size() == 0);
CPPUNIT_ASSERT(section.getProperty("invalid_id") == false);
Property p = section.createProperty("empty_prop", DataType::Double);
CPPUNIT_ASSERT(section.propertyCount() == 1);
Property prop = section.getPropertyByName("empty_prop");
CPPUNIT_ASSERT(prop.valueCount() == 0);
CPPUNIT_ASSERT(prop.dataType() == nix::DataType::Double);
section.deleteProperty(p.id());
CPPUNIT_ASSERT(section.propertyCount() == 0);
Value dummy(10);
prop = section.createProperty("single value", dummy);
CPPUNIT_ASSERT(section.hasPropertyWithName("single value"));
CPPUNIT_ASSERT(section.propertyCount() == 1);
section.deleteProperty(prop.id());
CPPUNIT_ASSERT(section.propertyCount() == 0);
vector<string> ids;
for (auto name : names) {
prop = section.createProperty(name, dummy);
CPPUNIT_ASSERT(prop.name() == name);
CPPUNIT_ASSERT(section.hasPropertyWithName(name));
Property prop_copy = section.getPropertyByName(name);
CPPUNIT_ASSERT(prop_copy.id() == prop.id());
ids.push_back(prop.id());
}
CPPUNIT_ASSERT(section.propertyCount() == names.size());
CPPUNIT_ASSERT(section.properties().size() == names.size());
section_other.createProperty("some_prop", dummy);
section_other.link(section);
CPPUNIT_ASSERT(section_other.propertyCount() == 1);
CPPUNIT_ASSERT(section_other.inheritedProperties().size() == names.size() + 1);
for (auto id : ids) {
Property prop = section.getProperty(id);
CPPUNIT_ASSERT(section.hasProperty(id));
CPPUNIT_ASSERT(prop.id() == id);
section.deleteProperty(id);
}
CPPUNIT_ASSERT(section.propertyCount() == 0);
CPPUNIT_ASSERT(section.properties().size() == 0);
CPPUNIT_ASSERT(section.getProperty("invalid_id") == false);
vector<Value> values;
values.push_back(Value(10));
values.push_back(Value(100));
section.createProperty("another test", values);
CPPUNIT_ASSERT(section.propertyCount() == 1);
prop = section.getPropertyByName("another test");
CPPUNIT_ASSERT(prop.valueCount() == 2);
}
void TestSection::testOperators() {
CPPUNIT_ASSERT(section_null == false);
CPPUNIT_ASSERT(section_null == none);
CPPUNIT_ASSERT(section != false);
CPPUNIT_ASSERT(section != none);
CPPUNIT_ASSERT(section == section);
CPPUNIT_ASSERT(section != section_other);
section_other = section;
CPPUNIT_ASSERT(section == section_other);
section_other = none;
CPPUNIT_ASSERT(section_null == false);
CPPUNIT_ASSERT(section_null == none);
}
void TestSection::testCreatedAt() {
CPPUNIT_ASSERT(section.createdAt() >= startup_time);
time_t past_time = time(NULL) - 10000000;
section.forceCreatedAt(past_time);
CPPUNIT_ASSERT(section.createdAt() == past_time);
}
void TestSection::testUpdatedAt() {
CPPUNIT_ASSERT(section.updatedAt() >= startup_time);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include "Env.hpp"
#include "deployment.hpp"
#include "Machine.hpp"
#include "User.hpp"
#include "associations.hpp"
#include "runtime/Action.hpp"
#include "EventStructures.hpp"
int main()
{
Env::initEnvironment();
UsedRuntimePtr rt = UsedRuntimeType::getRuntimeInstance();
Model::Machine m;
Model::User u1;
Model::User u2;
Action::link<typename Model::Usage::usedMachine, typename Model::Usage::userOfMachine>(&m, &u1);
Action::link<typename Model::Usage::usedMachine, typename Model::Usage::userOfMachine>(&m, &u2);
Action::log("Machine and users are starting.");
Action::start(&m);
Action::start(&u1);
Action::start(&u2);
Action::send(&u1, ES::SharedPtr<Model::DoYourWork_EC>(new Model::DoYourWork_EC()));
rt->startRT(); // in case of single runtime, process all current messages
m.printSwitchOnLog();
return 0;
}
<commit_msg>Fix machine1 example main according new associations<commit_after>#include <iostream>
#include "Env.hpp"
#include "deployment.hpp"
#include "Machine.hpp"
#include "User.hpp"
#include "AssociationInstances.hpp"
#include "runtime/Action.hpp"
#include "EventStructures.hpp"
int main()
{
Env::initEnvironment();
UsedRuntimePtr rt = UsedRuntimeType::getRuntimeInstance();
Model::Machine m;
Model::User u1;
Model::User u2;
Action::link(Model::Usage.usedMachine, &m, Model::Usage.userOfMachine,&u1);
Action::link(Model::Usage.usedMachine, &m, Model::Usage.userOfMachine, &u2);
Action::log("Machine and users are starting.");
Action::start(&m);
Action::start(&u1);
Action::start(&u2);
Action::send(&u1, ES::SharedPtr<Model::DoYourWork_EC>(new Model::DoYourWork_EC()));
rt->startRT(); // in case of single runtime, process all current messages
m.printSwitchOnLog();
return 0;
}
<|endoftext|> |
<commit_before>/*!
\copyright (c) RDO-Team, 2011
\file calc_base.cpp
\authors
\authors ([email protected])
\authors ([email protected])
\date 16.05.2007
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/calc/calc_base.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOCalc
// --------------------------------------------------------------------------------
RDOCalc::RDOCalc()
{}
RDOCalc::~RDOCalc()
{}
REF(RDOValue) RDOCalc::calcValue(CREF(LPRDORuntime) pRuntime)
{
try
{
#ifdef _DEBUG
/*
if (src_text().empty())
{
TRACE(_T("%d\n"), sizeof(tstring));
}
else if (src_text().length() < 500)
{
TRACE(_T("calc: %s\n"), src_text().c_str());
if (src_text() == _T(""))
{
TRACE(_T("calc: %s\n"), src_text().c_str());
}
}
else
{
tstring str = src_text();
str.resize(500);
TRACE(_T("calc: %s\n"), str.c_str());
}
*/
#endif
return doCalc(pRuntime);
}
catch (REF(RDORuntimeException) ex)
{
tstring message = rdo::format(_T("< : %f>, '%s'"), pRuntime->getTimeNow(), m_srcInfo.src_text().c_str());
if (!ex.message().empty())
{
message = rdo::format(_T("%s: %s"), message.c_str(), ex.message().c_str());
}
rdoSimulator::RDOSyntaxError error(
rdoSimulator::RDOSyntaxError::UNKNOWN,
message,
m_srcInfo.src_pos().m_last_line,
m_srcInfo.src_pos().m_last_pos,
m_srcInfo.src_filetype()
);
pRuntime->error().push(error);
}
return m_value;
}
CREF(RDOSrcInfo) RDOCalc::srcInfo() const
{
return m_srcInfo;
}
void RDOCalc::setSrcInfo(CREF(RDOSrcInfo) srcInfo)
{
m_srcInfo = srcInfo;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<commit_msg> - а зачем тут REF, если мы не меняем RDORuntimeException<commit_after>/*!
\copyright (c) RDO-Team, 2011
\file calc_base.cpp
\authors
\authors ([email protected])
\authors ([email protected])
\date 16.05.2007
\brief
\indent 4T
*/
// ---------------------------------------------------------------------------- PCH
#include "simulator/runtime/pch.h"
// ----------------------------------------------------------------------- INCLUDES
// ----------------------------------------------------------------------- SYNOPSIS
#include "simulator/runtime/calc/calc_base.h"
#include "simulator/runtime/rdo_runtime.h"
// --------------------------------------------------------------------------------
OPEN_RDO_RUNTIME_NAMESPACE
// --------------------------------------------------------------------------------
// -------------------- RDOCalc
// --------------------------------------------------------------------------------
RDOCalc::RDOCalc()
{}
RDOCalc::~RDOCalc()
{}
REF(RDOValue) RDOCalc::calcValue(CREF(LPRDORuntime) pRuntime)
{
try
{
#ifdef _DEBUG
/*
if (src_text().empty())
{
TRACE(_T("%d\n"), sizeof(tstring));
}
else if (src_text().length() < 500)
{
TRACE(_T("calc: %s\n"), src_text().c_str());
if (src_text() == _T(""))
{
TRACE(_T("calc: %s\n"), src_text().c_str());
}
}
else
{
tstring str = src_text();
str.resize(500);
TRACE(_T("calc: %s\n"), str.c_str());
}
*/
#endif
return doCalc(pRuntime);
}
catch (CREF(RDORuntimeException) ex)
{
tstring message = rdo::format(_T("< : %f>, '%s'"), pRuntime->getTimeNow(), m_srcInfo.src_text().c_str());
if (!ex.message().empty())
{
message = rdo::format(_T("%s: %s"), message.c_str(), ex.message().c_str());
}
rdoSimulator::RDOSyntaxError error(
rdoSimulator::RDOSyntaxError::UNKNOWN,
message,
m_srcInfo.src_pos().m_last_line,
m_srcInfo.src_pos().m_last_pos,
m_srcInfo.src_filetype()
);
pRuntime->error().push(error);
}
return m_value;
}
CREF(RDOSrcInfo) RDOCalc::srcInfo() const
{
return m_srcInfo;
}
void RDOCalc::setSrcInfo(CREF(RDOSrcInfo) srcInfo)
{
m_srcInfo = srcInfo;
}
CLOSE_RDO_RUNTIME_NAMESPACE
<|endoftext|> |
<commit_before>#include "render/shaderattribute2d.h"
#include "core/assert.h"
#include "render/shader.h"
namespace attributes2d {
const ShaderAttribute& Texture() {
static ShaderAttribute attribute{"texture", 0, ShaderAttributeSize::VEC1};
return attribute;
}
const ShaderAttribute& Rgba() {
static ShaderAttribute attribute{"rgba", 0, ShaderAttributeSize::VEC4};
return attribute;
}
const ShaderAttribute& Color() {
static ShaderAttribute attribute{"color", 0, ShaderAttributeSize::VEC4};
return attribute;
}
const ShaderAttribute& Model() {
static ShaderAttribute attribute{"model", 0, ShaderAttributeSize::MAT44};
return attribute;
}
const ShaderAttribute& Projection() {
static ShaderAttribute attribute{"projection", 0, ShaderAttributeSize::MAT44};
return attribute;
}
const ShaderAttribute& Image() {
static ShaderAttribute attribute{"image", 0, ShaderAttributeSize::VEC1};
return attribute;
}
void PrebindShader(Shader* shader) {
Assert(shader);
shader->PreBind(Texture());
shader->PreBind(Rgba());
shader->PreBind(Color());
shader->PreBind(Model());
shader->PreBind(Image());
shader->PreBind(Projection());
}
}<commit_msg>fixed not binding shaders<commit_after>#include "render/shaderattribute2d.h"
#include "core/assert.h"
#include "render/shader.h"
namespace attributes2d {
const ShaderAttribute& Texture() {
static ShaderAttribute attribute{"texture", 0, ShaderAttributeSize::VEC1};
return attribute;
}
const ShaderAttribute& Rgba() {
static ShaderAttribute attribute{"rgba", 0, ShaderAttributeSize::VEC4};
return attribute;
}
const ShaderAttribute& Color() {
static ShaderAttribute attribute{"color", 0, ShaderAttributeSize::VEC4};
return attribute;
}
const ShaderAttribute& Model() {
static ShaderAttribute attribute{"model", 0, ShaderAttributeSize::MAT44};
return attribute;
}
const ShaderAttribute& Projection() {
static ShaderAttribute attribute{"projection", 0, ShaderAttributeSize::MAT44};
return attribute;
}
const ShaderAttribute& Image() {
static ShaderAttribute attribute{"image", 0, ShaderAttributeSize::VEC1};
return attribute;
}
void PrebindShader(Shader* shader) {
Assert(shader);
Use(shader);
shader->PreBind(Texture());
shader->PreBind(Rgba());
shader->PreBind(Color());
shader->PreBind(Model());
shader->PreBind(Image());
shader->PreBind(Projection());
Use(nullptr);
}
}<|endoftext|> |
<commit_before>//===-- LanaiSetflagAluCombiner.cpp - Pass to combine set flag & ALU ops --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Lanai.h"
#include "LanaiTargetMachine.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
#define DEBUG_TYPE "lanai-setflag-alu-combiner"
STATISTIC(NumSetflagAluCombined,
"Number of SET_FLAG and ALU instructions combined");
static llvm::cl::opt<bool> DisableSetflagAluCombiner(
"disable-lanai-setflag-alu-combiner", llvm::cl::init(false),
llvm::cl::desc("Do not combine SET_FLAG and ALU operators"),
llvm::cl::Hidden);
namespace llvm {
void initializeLanaiSetflagAluCombinerPass(PassRegistry &);
} // namespace llvm
namespace {
typedef MachineBasicBlock::iterator MbbIterator;
typedef MachineFunction::iterator MfIterator;
class LanaiSetflagAluCombiner : public MachineFunctionPass {
public:
static char ID;
LanaiSetflagAluCombiner() : MachineFunctionPass(ID) {
initializeLanaiSetflagAluCombinerPass(*PassRegistry::getPassRegistry());
}
const char *getPassName() const override {
return "Lanai SET_FLAG ALU combiner pass";
}
bool runOnMachineFunction(MachineFunction &F) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::AllVRegsAllocated);
}
private:
bool CombineSetflagAluInBasicBlock(MachineFunction *MF,
MachineBasicBlock *BB);
};
} // namespace
char LanaiSetflagAluCombiner::ID = 0;
INITIALIZE_PASS(LanaiSetflagAluCombiner, DEBUG_TYPE,
"Lanai SET_FLAG ALU combiner pass", false, false)
namespace {
const unsigned kInvalid = -1;
static unsigned flagSettingOpcodeVariant(unsigned OldOpcode) {
switch (OldOpcode) {
case Lanai::ADD_I_HI:
return Lanai::ADD_F_I_HI;
case Lanai::ADD_I_LO:
return Lanai::ADD_F_I_LO;
case Lanai::ADD_R:
return Lanai::ADD_F_R;
case Lanai::ADD_R_CC:
return Lanai::ADD_F_R_CC;
case Lanai::ADDC_I_HI:
return Lanai::ADDC_F_I_HI;
case Lanai::ADDC_I_LO:
return Lanai::ADDC_F_I_LO;
case Lanai::ADDC_R:
return Lanai::ADDC_F_R;
case Lanai::ADDC_R_CC:
return Lanai::ADDC_F_R_CC;
case Lanai::AND_I_HI:
return Lanai::AND_F_I_HI;
case Lanai::AND_I_LO:
return Lanai::AND_F_I_LO;
case Lanai::AND_R:
return Lanai::AND_F_R;
case Lanai::AND_R_CC:
return Lanai::AND_F_R_CC;
case Lanai::OR_I_HI:
return Lanai::OR_F_I_HI;
case Lanai::OR_I_LO:
return Lanai::OR_F_I_LO;
case Lanai::OR_R:
return Lanai::OR_F_R;
case Lanai::OR_R_CC:
return Lanai::OR_F_R_CC;
case Lanai::SL_I:
return Lanai::SL_F_I;
case Lanai::SRL_R:
return Lanai::SRL_F_R;
case Lanai::SA_I:
return Lanai::SA_F_I;
case Lanai::SRA_R:
return Lanai::SRA_F_R;
case Lanai::SUB_I_HI:
return Lanai::SUB_F_I_HI;
case Lanai::SUB_I_LO:
return Lanai::SUB_F_I_LO;
case Lanai::SUB_R:
return Lanai::SUB_F_R;
case Lanai::SUB_R_CC:
return Lanai::SUB_F_R_CC;
case Lanai::SUBB_I_HI:
return Lanai::SUBB_F_I_HI;
case Lanai::SUBB_I_LO:
return Lanai::SUBB_F_I_LO;
case Lanai::SUBB_R:
return Lanai::SUBB_F_R;
case Lanai::SUBB_R_CC:
return Lanai::SUBB_F_R_CC;
case Lanai::XOR_I_HI:
return Lanai::XOR_F_I_HI;
case Lanai::XOR_I_LO:
return Lanai::XOR_F_I_LO;
case Lanai::XOR_R:
return Lanai::XOR_F_R;
case Lanai::XOR_R_CC:
return Lanai::XOR_F_R_CC;
default:
return kInvalid;
}
}
// Returns whether opcode corresponds to instruction that sets flags.
static bool isFlagSettingInstruction(unsigned Opcode) {
switch (Opcode) {
case Lanai::ADDC_F_I_HI:
case Lanai::ADDC_F_I_LO:
case Lanai::ADDC_F_R:
case Lanai::ADDC_F_R_CC:
case Lanai::ADD_F_I_HI:
case Lanai::ADD_F_I_LO:
case Lanai::ADD_F_R:
case Lanai::ADD_F_R_CC:
case Lanai::AND_F_I_HI:
case Lanai::AND_F_I_LO:
case Lanai::AND_F_R:
case Lanai::AND_F_R_CC:
case Lanai::OR_F_I_HI:
case Lanai::OR_F_I_LO:
case Lanai::OR_F_R:
case Lanai::OR_F_R_CC:
case Lanai::SFSUB_F_RI:
case Lanai::SFSUB_F_RR:
case Lanai::SA_F_I:
case Lanai::SL_F_I:
case Lanai::SHL_F_R:
case Lanai::SRA_F_R:
case Lanai::SRL_F_R:
case Lanai::SUBB_F_I_HI:
case Lanai::SUBB_F_I_LO:
case Lanai::SUBB_F_R:
case Lanai::SUBB_F_R_CC:
case Lanai::SUB_F_I_HI:
case Lanai::SUB_F_I_LO:
case Lanai::SUB_F_R:
case Lanai::SUB_F_R_CC:
case Lanai::XOR_F_I_HI:
case Lanai::XOR_F_I_LO:
case Lanai::XOR_F_R:
case Lanai::XOR_F_R_CC:
return true;
default:
return false;
}
}
// Return the Conditional Code operand for a given instruction kind. For
// example, operand at index 1 of a BRIND_CC instruction is the conditional code
// (eq, ne, etc.). Returns -1 if the instruction does not have a conditional
// code.
static int getCCOperandPosition(unsigned Opcode) {
switch (Opcode) {
case Lanai::BRIND_CC:
case Lanai::BRIND_CCA:
case Lanai::BRR:
case Lanai::BRCC:
case Lanai::SCC:
return 1;
case Lanai::SELECT:
case Lanai::ADDC_F_R_CC:
case Lanai::ADDC_R_CC:
case Lanai::ADD_F_R_CC:
case Lanai::ADD_R_CC:
case Lanai::AND_F_R_CC:
case Lanai::AND_R_CC:
case Lanai::OR_F_R_CC:
case Lanai::OR_R_CC:
case Lanai::SUBB_F_R_CC:
case Lanai::SUBB_R_CC:
case Lanai::SUB_F_R_CC:
case Lanai::SUB_R_CC:
case Lanai::XOR_F_R_CC:
case Lanai::XOR_R_CC:
return 3;
default:
return -1;
}
}
// Returns true if instruction is a lowered SET_FLAG instruction with 0/R0 as
// the first operand and whose conditional code is such that it can be merged
// (i.e., EQ, NE, PL and MI).
static bool isSuitableSetflag(MbbIterator Instruction, MbbIterator End) {
unsigned Opcode = Instruction->getOpcode();
if (Opcode == Lanai::SFSUB_F_RI || Opcode == Lanai::SFSUB_F_RR) {
const MachineOperand &Operand = Instruction->getOperand(1);
if (Operand.isReg() && Operand.getReg() != Lanai::R0)
return false;
if (Operand.isImm() && Operand.getImm() != 0)
return false;
MbbIterator SCCUserIter = Instruction;
while (SCCUserIter != End) {
++SCCUserIter;
// Early exit when encountering flag setting or return instruction.
if (isFlagSettingInstruction(SCCUserIter->getOpcode()) ||
SCCUserIter->isReturn())
// Only return true if flags are set post the flag setting instruction
// tested or a return is executed.
return true;
int CCIndex = getCCOperandPosition(SCCUserIter->getOpcode());
if (CCIndex != -1) {
LPCC::CondCode CC = static_cast<LPCC::CondCode>(
SCCUserIter->getOperand(CCIndex).getImm());
// Return false if the flag is used outside of a EQ, NE, PL and MI.
if (CC != LPCC::ICC_EQ && CC != LPCC::ICC_NE && CC != LPCC::ICC_PL &&
CC != LPCC::ICC_MI)
return false;
}
}
}
return false;
}
// Combines a SET_FLAG instruction comparing a register with 0 and an ALU
// operation that sets the same register used in the comparison into a single
// flag setting ALU instruction (both instructions combined are removed and new
// flag setting ALU operation inserted where ALU instruction was).
bool LanaiSetflagAluCombiner::CombineSetflagAluInBasicBlock(
MachineFunction *MF, MachineBasicBlock *BB) {
bool Modified = false;
const TargetInstrInfo *TII =
MF->getSubtarget<LanaiSubtarget>().getInstrInfo();
MbbIterator SetflagIter = BB->begin();
MbbIterator End = BB->end();
MbbIterator Begin = BB->begin();
while (SetflagIter != End) {
bool Replaced = false;
if (isSuitableSetflag(SetflagIter, End)) {
MbbIterator AluIter = SetflagIter;
while (AluIter != Begin) {
--AluIter;
// Skip debug instructions. Debug instructions don't affect codegen.
if (AluIter->isDebugValue()) {
continue;
}
// Early exit when encountering flag setting instruction.
if (isFlagSettingInstruction(AluIter->getOpcode())) {
break;
}
// Check that output of AluIter is equal to input of SetflagIter.
if (AluIter->getNumOperands() > 1 && AluIter->getOperand(0).isReg() &&
(AluIter->getOperand(0).getReg() ==
SetflagIter->getOperand(0).getReg())) {
unsigned NewOpc = flagSettingOpcodeVariant(AluIter->getOpcode());
if (NewOpc == kInvalid)
break;
// Change the ALU instruction to the flag setting variant.
AluIter->setDesc(TII->get(NewOpc));
AluIter->addImplicitDefUseOperands(*MF);
Replaced = true;
++NumSetflagAluCombined;
break;
}
}
// Erase the setflag instruction if merged.
if (Replaced) {
BB->erase(SetflagIter++);
}
}
Modified |= Replaced;
if (SetflagIter == End)
break;
if (!Replaced)
++SetflagIter;
}
return Modified;
}
// Driver function that iterates over the machine basic building blocks of a
// machine function
bool LanaiSetflagAluCombiner::runOnMachineFunction(MachineFunction &MF) {
if (DisableSetflagAluCombiner)
return false;
bool Modified = false;
MfIterator End = MF.end();
for (MfIterator MFI = MF.begin(); MFI != End; ++MFI) {
Modified |= CombineSetflagAluInBasicBlock(&MF, &*MFI);
}
return Modified;
}
} // namespace
FunctionPass *llvm::createLanaiSetflagAluCombinerPass() {
return new LanaiSetflagAluCombiner();
}
<commit_msg>[lanai] Change the way flag setting instructions are checked.<commit_after>//===-- LanaiSetflagAluCombiner.cpp - Pass to combine set flag & ALU ops --===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Lanai.h"
#include "LanaiTargetMachine.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/RegisterScavenging.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Target/TargetInstrInfo.h"
using namespace llvm;
#define DEBUG_TYPE "lanai-setflag-alu-combiner"
STATISTIC(NumSetflagAluCombined,
"Number of SET_FLAG and ALU instructions combined");
static llvm::cl::opt<bool> DisableSetflagAluCombiner(
"disable-lanai-setflag-alu-combiner", llvm::cl::init(false),
llvm::cl::desc("Do not combine SET_FLAG and ALU operators"),
llvm::cl::Hidden);
namespace llvm {
void initializeLanaiSetflagAluCombinerPass(PassRegistry &);
} // namespace llvm
namespace {
typedef MachineBasicBlock::iterator MbbIterator;
typedef MachineFunction::iterator MfIterator;
class LanaiSetflagAluCombiner : public MachineFunctionPass {
public:
static char ID;
LanaiSetflagAluCombiner() : MachineFunctionPass(ID) {
initializeLanaiSetflagAluCombinerPass(*PassRegistry::getPassRegistry());
}
const char *getPassName() const override {
return "Lanai SET_FLAG ALU combiner pass";
}
bool runOnMachineFunction(MachineFunction &F) override;
MachineFunctionProperties getRequiredProperties() const override {
return MachineFunctionProperties().set(
MachineFunctionProperties::Property::AllVRegsAllocated);
}
private:
bool CombineSetflagAluInBasicBlock(MachineFunction *MF,
MachineBasicBlock *BB);
};
} // namespace
char LanaiSetflagAluCombiner::ID = 0;
INITIALIZE_PASS(LanaiSetflagAluCombiner, DEBUG_TYPE,
"Lanai SET_FLAG ALU combiner pass", false, false)
namespace {
const unsigned kInvalid = -1;
static unsigned flagSettingOpcodeVariant(unsigned OldOpcode) {
switch (OldOpcode) {
case Lanai::ADD_I_HI:
return Lanai::ADD_F_I_HI;
case Lanai::ADD_I_LO:
return Lanai::ADD_F_I_LO;
case Lanai::ADD_R:
return Lanai::ADD_F_R;
case Lanai::ADD_R_CC:
return Lanai::ADD_F_R_CC;
case Lanai::ADDC_I_HI:
return Lanai::ADDC_F_I_HI;
case Lanai::ADDC_I_LO:
return Lanai::ADDC_F_I_LO;
case Lanai::ADDC_R:
return Lanai::ADDC_F_R;
case Lanai::ADDC_R_CC:
return Lanai::ADDC_F_R_CC;
case Lanai::AND_I_HI:
return Lanai::AND_F_I_HI;
case Lanai::AND_I_LO:
return Lanai::AND_F_I_LO;
case Lanai::AND_R:
return Lanai::AND_F_R;
case Lanai::AND_R_CC:
return Lanai::AND_F_R_CC;
case Lanai::OR_I_HI:
return Lanai::OR_F_I_HI;
case Lanai::OR_I_LO:
return Lanai::OR_F_I_LO;
case Lanai::OR_R:
return Lanai::OR_F_R;
case Lanai::OR_R_CC:
return Lanai::OR_F_R_CC;
case Lanai::SL_I:
return Lanai::SL_F_I;
case Lanai::SRL_R:
return Lanai::SRL_F_R;
case Lanai::SA_I:
return Lanai::SA_F_I;
case Lanai::SRA_R:
return Lanai::SRA_F_R;
case Lanai::SUB_I_HI:
return Lanai::SUB_F_I_HI;
case Lanai::SUB_I_LO:
return Lanai::SUB_F_I_LO;
case Lanai::SUB_R:
return Lanai::SUB_F_R;
case Lanai::SUB_R_CC:
return Lanai::SUB_F_R_CC;
case Lanai::SUBB_I_HI:
return Lanai::SUBB_F_I_HI;
case Lanai::SUBB_I_LO:
return Lanai::SUBB_F_I_LO;
case Lanai::SUBB_R:
return Lanai::SUBB_F_R;
case Lanai::SUBB_R_CC:
return Lanai::SUBB_F_R_CC;
case Lanai::XOR_I_HI:
return Lanai::XOR_F_I_HI;
case Lanai::XOR_I_LO:
return Lanai::XOR_F_I_LO;
case Lanai::XOR_R:
return Lanai::XOR_F_R;
case Lanai::XOR_R_CC:
return Lanai::XOR_F_R_CC;
default:
return kInvalid;
}
}
// Returns whether opcode corresponds to instruction that sets flags.
static bool isFlagSettingInstruction(MbbIterator Instruction) {
return Instruction->killsRegister(Lanai::SR);
}
// Return the Conditional Code operand for a given instruction kind. For
// example, operand at index 1 of a BRIND_CC instruction is the conditional code
// (eq, ne, etc.). Returns -1 if the instruction does not have a conditional
// code.
static int getCCOperandPosition(unsigned Opcode) {
switch (Opcode) {
case Lanai::BRIND_CC:
case Lanai::BRIND_CCA:
case Lanai::BRR:
case Lanai::BRCC:
case Lanai::SCC:
return 1;
case Lanai::SELECT:
case Lanai::ADDC_F_R_CC:
case Lanai::ADDC_R_CC:
case Lanai::ADD_F_R_CC:
case Lanai::ADD_R_CC:
case Lanai::AND_F_R_CC:
case Lanai::AND_R_CC:
case Lanai::OR_F_R_CC:
case Lanai::OR_R_CC:
case Lanai::SUBB_F_R_CC:
case Lanai::SUBB_R_CC:
case Lanai::SUB_F_R_CC:
case Lanai::SUB_R_CC:
case Lanai::XOR_F_R_CC:
case Lanai::XOR_R_CC:
return 3;
default:
return -1;
}
}
// Returns true if instruction is a lowered SET_FLAG instruction with 0/R0 as
// the first operand and whose conditional code is such that it can be merged
// (i.e., EQ, NE, PL and MI).
static bool isSuitableSetflag(MbbIterator Instruction, MbbIterator End) {
unsigned Opcode = Instruction->getOpcode();
if (Opcode == Lanai::SFSUB_F_RI || Opcode == Lanai::SFSUB_F_RR) {
const MachineOperand &Operand = Instruction->getOperand(1);
if (Operand.isReg() && Operand.getReg() != Lanai::R0)
return false;
if (Operand.isImm() && Operand.getImm() != 0)
return false;
MbbIterator SCCUserIter = Instruction;
while (SCCUserIter != End) {
++SCCUserIter;
if (SCCUserIter == End)
break;
// Skip debug instructions. Debug instructions don't affect codegen.
if (SCCUserIter->isDebugValue())
continue;
// Early exit when encountering flag setting or return instruction.
if (isFlagSettingInstruction(SCCUserIter))
// Only return true if flags are set post the flag setting instruction
// tested or a return is executed.
return true;
int CCIndex = getCCOperandPosition(SCCUserIter->getOpcode());
if (CCIndex != -1) {
LPCC::CondCode CC = static_cast<LPCC::CondCode>(
SCCUserIter->getOperand(CCIndex).getImm());
// Return false if the flag is used outside of a EQ, NE, PL and MI.
if (CC != LPCC::ICC_EQ && CC != LPCC::ICC_NE && CC != LPCC::ICC_PL &&
CC != LPCC::ICC_MI)
return false;
}
}
}
return false;
}
// Combines a SET_FLAG instruction comparing a register with 0 and an ALU
// operation that sets the same register used in the comparison into a single
// flag setting ALU instruction (both instructions combined are removed and new
// flag setting ALU operation inserted where ALU instruction was).
bool LanaiSetflagAluCombiner::CombineSetflagAluInBasicBlock(
MachineFunction *MF, MachineBasicBlock *BB) {
bool Modified = false;
const TargetInstrInfo *TII =
MF->getSubtarget<LanaiSubtarget>().getInstrInfo();
MbbIterator SetflagIter = BB->begin();
MbbIterator End = BB->end();
MbbIterator Begin = BB->begin();
while (SetflagIter != End) {
bool Replaced = false;
if (isSuitableSetflag(SetflagIter, End)) {
MbbIterator AluIter = SetflagIter;
while (AluIter != Begin) {
--AluIter;
// Skip debug instructions. Debug instructions don't affect codegen.
if (AluIter->isDebugValue())
continue;
// Early exit when encountering flag setting instruction.
if (isFlagSettingInstruction(AluIter))
break;
// Check that output of AluIter is equal to input of SetflagIter.
if (AluIter->getNumOperands() > 1 && AluIter->getOperand(0).isReg() &&
(AluIter->getOperand(0).getReg() ==
SetflagIter->getOperand(0).getReg())) {
unsigned NewOpc = flagSettingOpcodeVariant(AluIter->getOpcode());
if (NewOpc == kInvalid)
break;
// Change the ALU instruction to the flag setting variant.
AluIter->setDesc(TII->get(NewOpc));
AluIter->addImplicitDefUseOperands(*MF);
Replaced = true;
++NumSetflagAluCombined;
break;
}
}
// Erase the setflag instruction if merged.
if (Replaced)
BB->erase(SetflagIter++);
}
Modified |= Replaced;
if (!Replaced)
++SetflagIter;
}
return Modified;
}
// Driver function that iterates over the machine basic building blocks of a
// machine function
bool LanaiSetflagAluCombiner::runOnMachineFunction(MachineFunction &MF) {
if (DisableSetflagAluCombiner)
return false;
bool Modified = false;
MfIterator End = MF.end();
for (MfIterator MFI = MF.begin(); MFI != End; ++MFI) {
Modified |= CombineSetflagAluInBasicBlock(&MF, &*MFI);
}
return Modified;
}
} // namespace
FunctionPass *llvm::createLanaiSetflagAluCombinerPass() {
return new LanaiSetflagAluCombiner();
}
<|endoftext|> |
<commit_before>//===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower X86 MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "X86ATTAsmPrinter.h"
#include "X86MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
MCSymbol *X86ATTAsmPrinter::GetPICBaseSymbol() {
// FIXME: the actual label generated doesn't matter here! Just mangle in
// something unique (the function number) with Private prefix.
SmallString<60> Name;
if (Subtarget->isTargetDarwin()) {
raw_svector_ostream(Name) << 'L' << getFunctionNumber() << "$pb";
} else {
assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
raw_svector_ostream(Name) << ".Lllvm$" << getFunctionNumber()<<".$piclabel";
}
return OutContext.GetOrCreateSymbol(Name.str());
}
static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
// Convert registers in the addr mode according to subreg64.
for (unsigned i = 0; i != 4; ++i) {
if (!MI->getOperand(i).isReg()) continue;
unsigned Reg = MI->getOperand(i).getReg();
if (Reg == 0) continue;
MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
}
}
/// LowerGlobalAddressOperand - Lower an MO_GlobalAddress operand to an
/// MCOperand.
MCSymbol *X86ATTAsmPrinter::GetGlobalAddressSymbol(const MachineOperand &MO) {
const GlobalValue *GV = MO.getGlobal();
const char *Suffix = "";
if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
Suffix = "$stub";
else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
Suffix = "$non_lazy_ptr";
std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
if (Subtarget->isTargetCygMing())
DecorateCygMingName(Name, GV);
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_GOT_ABSOLUTE_ADDRESS: // Doesn't modify symbol name.
case X86II::MO_PIC_BASE_OFFSET: // Doesn't modify symbol name.
break;
case X86II::MO_DLLIMPORT:
// Handle dllimport linkage.
Name = "__imp_" + Name;
break;
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
GVStubs[Name] = Mang->getMangledName(GV);
break;
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
HiddenGVStubs[Name] = Mang->getMangledName(GV);
break;
case X86II::MO_DARWIN_STUB:
FnStubs[Name] = Mang->getMangledName(GV);
break;
// FIXME: These probably should be a modifier on the symbol or something??
case X86II::MO_TLSGD: Name += "@TLSGD"; break;
case X86II::MO_GOTTPOFF: Name += "@GOTTPOFF"; break;
case X86II::MO_INDNTPOFF: Name += "@INDNTPOFF"; break;
case X86II::MO_TPOFF: Name += "@TPOFF"; break;
case X86II::MO_NTPOFF: Name += "@NTPOFF"; break;
case X86II::MO_GOTPCREL: Name += "@GOTPCREL"; break;
case X86II::MO_GOT: Name += "@GOT"; break;
case X86II::MO_GOTOFF: Name += "@GOTOFF"; break;
case X86II::MO_PLT: Name += "@PLT"; break;
}
return OutContext.GetOrCreateSymbol(Name);
}
MCSymbol *X86ATTAsmPrinter::GetExternalSymbolSymbol(const MachineOperand &MO) {
std::string Name = Mang->makeNameProper(MO.getSymbolName());
if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
FnStubs[Name+"$stub"] = Name;
Name += "$stub";
}
return OutContext.GetOrCreateSymbol(Name);
}
MCSymbol *X86ATTAsmPrinter::GetJumpTableSymbol(const MachineOperand &MO) {
SmallString<256> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "JTI"
<< getFunctionNumber() << '_' << MO.getIndex();
switch (MO.getTargetFlags()) {
default:
llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
break;
// Subtract the pic base.
GetPICBaseSymbol();
break;
}
// Create a symbol for the name.
return OutContext.GetOrCreateSymbol(Name.str());
}
MCSymbol *X86ATTAsmPrinter::
GetConstantPoolIndexSymbol(const MachineOperand &MO) {
SmallString<256> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
<< getFunctionNumber() << '_' << MO.getIndex();
switch (MO.getTargetFlags()) {
default:
llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
break;
}
// Create a symbol for the name.
return OutContext.GetOrCreateSymbol(Name.str());
}
MCOperand X86ATTAsmPrinter::LowerSymbolOperand(const MachineOperand &MO,
MCSymbol *Sym) {
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, OutContext);
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
// These affect the name of the symbol, not any suffix.
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DLLIMPORT:
case X86II::MO_DARWIN_STUB:
case X86II::MO_TLSGD:
case X86II::MO_GOTTPOFF:
case X86II::MO_INDNTPOFF:
case X86II::MO_TPOFF:
case X86II::MO_NTPOFF:
case X86II::MO_GOTPCREL:
case X86II::MO_GOT:
case X86II::MO_GOTOFF:
case X86II::MO_PLT:
break;
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
// Subtract the pic base.
Expr = MCBinaryExpr::CreateSub(Expr,
MCSymbolRefExpr::Create(GetPICBaseSymbol(),
OutContext),
OutContext);
break;
case X86II::MO_GOT_ABSOLUTE_ADDRESS: {
// For this, we want to print something like:
// MYSYMBOL + (. - PICBASE)
// However, we can't generate a ".", so just emit a new label here and refer
// to it. We know that this operand flag occurs at most once per function.
SmallString<64> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "picbaseref"
<< getFunctionNumber();
MCSymbol *DotSym = OutContext.GetOrCreateSymbol(Name.str());
OutStreamer.EmitLabel(DotSym);
const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
const MCExpr *PICBase = MCSymbolRefExpr::Create(GetPICBaseSymbol(),
OutContext);
DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
Expr = MCBinaryExpr::CreateAdd(Expr, DotExpr, OutContext);
break;
}
}
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(),
OutContext),
OutContext);
return MCOperand::CreateExpr(Expr);
}
void X86ATTAsmPrinter::
printInstructionThroughMCStreamer(const MachineInstr *MI) {
MCInst TmpInst;
switch (MI->getOpcode()) {
case TargetInstrInfo::DBG_LABEL:
case TargetInstrInfo::EH_LABEL:
case TargetInstrInfo::GC_LABEL:
printLabel(MI);
return;
case TargetInstrInfo::INLINEASM:
O << '\t';
printInlineAsm(MI);
return;
case TargetInstrInfo::IMPLICIT_DEF:
printImplicitDef(MI);
return;
case X86::MOVPC32r: {
// This is a pseudo op for a two instruction sequence with a label, which
// looks like:
// call "L1$pb"
// "L1$pb":
// popl %esi
// Emit the call.
MCSymbol *PICBase = GetPICBaseSymbol();
TmpInst.setOpcode(X86::CALLpcrel32);
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
TmpInst.addOperand(MCOperand::CreateExpr(MCSymbolRefExpr::Create(PICBase,
OutContext)));
printInstruction(&TmpInst);
// Emit the label.
OutStreamer.EmitLabel(PICBase);
// popl $reg
TmpInst.setOpcode(X86::POP32r);
TmpInst.getOperand(0) = MCOperand::CreateReg(MI->getOperand(0).getReg());
printInstruction(&TmpInst);
return;
}
}
TmpInst.setOpcode(MI->getOpcode());
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
MCOperand MCOp;
switch (MO.getType()) {
default:
O.flush();
errs() << "Cannot lower operand #" << i << " of :" << *MI;
llvm_unreachable("Unimp");
case MachineOperand::MO_Register:
MCOp = MCOperand::CreateReg(MO.getReg());
break;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::CreateImm(MO.getImm());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(),
MO.getMBB()->getNumber());
break;
case MachineOperand::MO_GlobalAddress:
MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
break;
case MachineOperand::MO_ExternalSymbol:
MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO));
break;
}
TmpInst.addOperand(MCOp);
}
switch (TmpInst.getOpcode()) {
case X86::LEA64_32r:
// Handle the 'subreg rewriting' for the lea64_32mem operand.
lower_lea64_32mem(&TmpInst, 1);
break;
}
printInstruction(&TmpInst);
}
<commit_msg>Remove unreachable code.<commit_after>//===-- X86MCInstLower.cpp - Convert X86 MachineInstr to an MCInst --------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains code to lower X86 MachineInstrs to their corresponding
// MCInst records.
//
//===----------------------------------------------------------------------===//
#include "X86ATTAsmPrinter.h"
#include "X86MCAsmInfo.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/Mangler.h"
#include "llvm/ADT/SmallString.h"
using namespace llvm;
MCSymbol *X86ATTAsmPrinter::GetPICBaseSymbol() {
// FIXME: the actual label generated doesn't matter here! Just mangle in
// something unique (the function number) with Private prefix.
SmallString<60> Name;
if (Subtarget->isTargetDarwin()) {
raw_svector_ostream(Name) << 'L' << getFunctionNumber() << "$pb";
} else {
assert(Subtarget->isTargetELF() && "Don't know how to print PIC label!");
raw_svector_ostream(Name) << ".Lllvm$" << getFunctionNumber()<<".$piclabel";
}
return OutContext.GetOrCreateSymbol(Name.str());
}
static void lower_lea64_32mem(MCInst *MI, unsigned OpNo) {
// Convert registers in the addr mode according to subreg64.
for (unsigned i = 0; i != 4; ++i) {
if (!MI->getOperand(i).isReg()) continue;
unsigned Reg = MI->getOperand(i).getReg();
if (Reg == 0) continue;
MI->getOperand(i).setReg(getX86SubSuperRegister(Reg, MVT::i64));
}
}
/// LowerGlobalAddressOperand - Lower an MO_GlobalAddress operand to an
/// MCOperand.
MCSymbol *X86ATTAsmPrinter::GetGlobalAddressSymbol(const MachineOperand &MO) {
const GlobalValue *GV = MO.getGlobal();
const char *Suffix = "";
if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB)
Suffix = "$stub";
else if (MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY ||
MO.getTargetFlags() == X86II::MO_DARWIN_NONLAZY_PIC_BASE ||
MO.getTargetFlags() == X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE)
Suffix = "$non_lazy_ptr";
std::string Name = Mang->getMangledName(GV, Suffix, Suffix[0] != '\0');
if (Subtarget->isTargetCygMing())
DecorateCygMingName(Name, GV);
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_GOT_ABSOLUTE_ADDRESS: // Doesn't modify symbol name.
case X86II::MO_PIC_BASE_OFFSET: // Doesn't modify symbol name.
break;
case X86II::MO_DLLIMPORT:
// Handle dllimport linkage.
Name = "__imp_" + Name;
break;
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
GVStubs[Name] = Mang->getMangledName(GV);
break;
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
HiddenGVStubs[Name] = Mang->getMangledName(GV);
break;
case X86II::MO_DARWIN_STUB:
FnStubs[Name] = Mang->getMangledName(GV);
break;
// FIXME: These probably should be a modifier on the symbol or something??
case X86II::MO_TLSGD: Name += "@TLSGD"; break;
case X86II::MO_GOTTPOFF: Name += "@GOTTPOFF"; break;
case X86II::MO_INDNTPOFF: Name += "@INDNTPOFF"; break;
case X86II::MO_TPOFF: Name += "@TPOFF"; break;
case X86II::MO_NTPOFF: Name += "@NTPOFF"; break;
case X86II::MO_GOTPCREL: Name += "@GOTPCREL"; break;
case X86II::MO_GOT: Name += "@GOT"; break;
case X86II::MO_GOTOFF: Name += "@GOTOFF"; break;
case X86II::MO_PLT: Name += "@PLT"; break;
}
return OutContext.GetOrCreateSymbol(Name);
}
MCSymbol *X86ATTAsmPrinter::GetExternalSymbolSymbol(const MachineOperand &MO) {
std::string Name = Mang->makeNameProper(MO.getSymbolName());
if (MO.getTargetFlags() == X86II::MO_DARWIN_STUB) {
FnStubs[Name+"$stub"] = Name;
Name += "$stub";
}
return OutContext.GetOrCreateSymbol(Name);
}
MCSymbol *X86ATTAsmPrinter::GetJumpTableSymbol(const MachineOperand &MO) {
SmallString<256> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "JTI"
<< getFunctionNumber() << '_' << MO.getIndex();
switch (MO.getTargetFlags()) {
default:
llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
break;
}
// Create a symbol for the name.
return OutContext.GetOrCreateSymbol(Name.str());
}
MCSymbol *X86ATTAsmPrinter::
GetConstantPoolIndexSymbol(const MachineOperand &MO) {
SmallString<256> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "CPI"
<< getFunctionNumber() << '_' << MO.getIndex();
switch (MO.getTargetFlags()) {
default:
llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
break;
}
// Create a symbol for the name.
return OutContext.GetOrCreateSymbol(Name.str());
}
MCOperand X86ATTAsmPrinter::LowerSymbolOperand(const MachineOperand &MO,
MCSymbol *Sym) {
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
const MCExpr *Expr = MCSymbolRefExpr::Create(Sym, OutContext);
switch (MO.getTargetFlags()) {
default: llvm_unreachable("Unknown target flag on GV operand");
case X86II::MO_NO_FLAG: // No flag.
// These affect the name of the symbol, not any suffix.
case X86II::MO_DARWIN_NONLAZY:
case X86II::MO_DLLIMPORT:
case X86II::MO_DARWIN_STUB:
case X86II::MO_TLSGD:
case X86II::MO_GOTTPOFF:
case X86II::MO_INDNTPOFF:
case X86II::MO_TPOFF:
case X86II::MO_NTPOFF:
case X86II::MO_GOTPCREL:
case X86II::MO_GOT:
case X86II::MO_GOTOFF:
case X86II::MO_PLT:
break;
case X86II::MO_PIC_BASE_OFFSET:
case X86II::MO_DARWIN_NONLAZY_PIC_BASE:
case X86II::MO_DARWIN_HIDDEN_NONLAZY_PIC_BASE:
// Subtract the pic base.
Expr = MCBinaryExpr::CreateSub(Expr,
MCSymbolRefExpr::Create(GetPICBaseSymbol(),
OutContext),
OutContext);
break;
case X86II::MO_GOT_ABSOLUTE_ADDRESS: {
// For this, we want to print something like:
// MYSYMBOL + (. - PICBASE)
// However, we can't generate a ".", so just emit a new label here and refer
// to it. We know that this operand flag occurs at most once per function.
SmallString<64> Name;
raw_svector_ostream(Name) << MAI->getPrivateGlobalPrefix() << "picbaseref"
<< getFunctionNumber();
MCSymbol *DotSym = OutContext.GetOrCreateSymbol(Name.str());
OutStreamer.EmitLabel(DotSym);
const MCExpr *DotExpr = MCSymbolRefExpr::Create(DotSym, OutContext);
const MCExpr *PICBase = MCSymbolRefExpr::Create(GetPICBaseSymbol(),
OutContext);
DotExpr = MCBinaryExpr::CreateSub(DotExpr, PICBase, OutContext);
Expr = MCBinaryExpr::CreateAdd(Expr, DotExpr, OutContext);
break;
}
}
if (!MO.isJTI() && MO.getOffset())
Expr = MCBinaryExpr::CreateAdd(Expr, MCConstantExpr::Create(MO.getOffset(),
OutContext),
OutContext);
return MCOperand::CreateExpr(Expr);
}
void X86ATTAsmPrinter::
printInstructionThroughMCStreamer(const MachineInstr *MI) {
MCInst TmpInst;
switch (MI->getOpcode()) {
case TargetInstrInfo::DBG_LABEL:
case TargetInstrInfo::EH_LABEL:
case TargetInstrInfo::GC_LABEL:
printLabel(MI);
return;
case TargetInstrInfo::INLINEASM:
O << '\t';
printInlineAsm(MI);
return;
case TargetInstrInfo::IMPLICIT_DEF:
printImplicitDef(MI);
return;
case X86::MOVPC32r: {
// This is a pseudo op for a two instruction sequence with a label, which
// looks like:
// call "L1$pb"
// "L1$pb":
// popl %esi
// Emit the call.
MCSymbol *PICBase = GetPICBaseSymbol();
TmpInst.setOpcode(X86::CALLpcrel32);
// FIXME: We would like an efficient form for this, so we don't have to do a
// lot of extra uniquing.
TmpInst.addOperand(MCOperand::CreateExpr(MCSymbolRefExpr::Create(PICBase,
OutContext)));
printInstruction(&TmpInst);
// Emit the label.
OutStreamer.EmitLabel(PICBase);
// popl $reg
TmpInst.setOpcode(X86::POP32r);
TmpInst.getOperand(0) = MCOperand::CreateReg(MI->getOperand(0).getReg());
printInstruction(&TmpInst);
return;
}
}
TmpInst.setOpcode(MI->getOpcode());
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
const MachineOperand &MO = MI->getOperand(i);
MCOperand MCOp;
switch (MO.getType()) {
default:
O.flush();
errs() << "Cannot lower operand #" << i << " of :" << *MI;
llvm_unreachable("Unimp");
case MachineOperand::MO_Register:
MCOp = MCOperand::CreateReg(MO.getReg());
break;
case MachineOperand::MO_Immediate:
MCOp = MCOperand::CreateImm(MO.getImm());
break;
case MachineOperand::MO_MachineBasicBlock:
MCOp = MCOperand::CreateMBBLabel(getFunctionNumber(),
MO.getMBB()->getNumber());
break;
case MachineOperand::MO_GlobalAddress:
MCOp = LowerSymbolOperand(MO, GetGlobalAddressSymbol(MO));
break;
case MachineOperand::MO_ExternalSymbol:
MCOp = LowerSymbolOperand(MO, GetExternalSymbolSymbol(MO));
break;
case MachineOperand::MO_JumpTableIndex:
MCOp = LowerSymbolOperand(MO, GetJumpTableSymbol(MO));
break;
case MachineOperand::MO_ConstantPoolIndex:
MCOp = LowerSymbolOperand(MO, GetConstantPoolIndexSymbol(MO));
break;
}
TmpInst.addOperand(MCOp);
}
switch (TmpInst.getOpcode()) {
case X86::LEA64_32r:
// Handle the 'subreg rewriting' for the lea64_32mem operand.
lower_lea64_32mem(&TmpInst, 1);
break;
}
printInstruction(&TmpInst);
}
<|endoftext|> |
<commit_before>/**
* @file VectorMath.hpp
* @brief The VectorMath class.
* @author Dominique LaSalle <[email protected]>
* Copyright 2017-2018, Solid Lake LLC
* @version 1
* @date 2017-10-11
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef SOLIDUTILS_INCLUDE_VECTORMATH_HPP
#define SOLIDUTILS_INCLUDE_VECTORMATH_HPP
#include "Array.hpp"
namespace sl
{
/**
* @brief The VectorMath class contains static functions for manipulating
* numerical data in vectors. This includes operations for summation, scaling,
* dot products, cross products, prefix sums, etc..
*/
class VectorMath
{
public:
/**
* @brief Sum the elements of an array.
*
* @tparam T The type element.
* @param data The starting memory location.
* @param size The number of elements.
*
* @return The sum.
*/
template <typename T>
static T sum(
T * const data,
size_t const size) noexcept
{
T sum = 0;
for (size_t i = 0; i < size; ++i) {
sum += data[i];
}
return sum;
}
/**
* @brief Set all entries int the array to the given sequence.
*
* @tparam The type of elements in the array.
* @param data The starting location of memory.
* @param size The number of lements.
* @param start The starting value of the sequence.
* @param inc The increment of the sequence.
*/
template <typename T>
static void increment(
T * const data,
size_t const size,
T const start = 0,
T const inc = 1) noexcept
{
T val = start;
for (size_t i = 0; i < size; ++i) {
data[i] = val;
val += inc;
}
}
/**
* @brief Perform a prefix sum on an array.
*
* @tparam T The type of elements in the array.
* @param data The starting location of memory.
* @param size The number of elements in the array.
*/
template <typename T>
static void prefixSumExclusive(
T * const data,
size_t const size) noexcept
{
T sum = 0;
for (size_t i = 0; i < size; ++i) {
T const val = data[i];
data[i] = sum;
sum += val;
}
}
};
}
#endif
<commit_msg>Add prefixsum exclusive for iterators<commit_after>/**
* @file VectorMath.hpp
* @brief The VectorMath class.
* @author Dominique LaSalle <[email protected]>
* Copyright 2017-2018, Solid Lake LLC
* @version 1
* @date 2017-10-11
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef SOLIDUTILS_INCLUDE_VECTORMATH_HPP
#define SOLIDUTILS_INCLUDE_VECTORMATH_HPP
#include "Array.hpp"
#include <type_traits>
namespace sl
{
/**
* @brief The VectorMath class contains static functions for manipulating
* numerical data in vectors. This includes operations for summation, scaling,
* dot products, cross products, prefix sums, etc..
*/
class VectorMath
{
public:
/**
* @brief Sum the elements of an array.
*
* @tparam T The type element.
* @param data The starting memory location.
* @param size The number of elements.
*
* @return The sum.
*/
template <typename T>
static T sum(
T * const data,
size_t const size) noexcept
{
T sum = 0;
for (size_t i = 0; i < size; ++i) {
sum += data[i];
}
return sum;
}
/**
* @brief Set all entries int the array to the given sequence.
*
* @tparam The type of elements in the array.
* @param data The starting location of memory.
* @param size The number of lements.
* @param start The starting value of the sequence.
* @param inc The increment of the sequence.
*/
template <typename T>
static void increment(
T * const data,
size_t const size,
T const start = 0,
T const inc = 1) noexcept
{
T val = start;
for (size_t i = 0; i < size; ++i) {
data[i] = val;
val += inc;
}
}
/**
* @brief Perform a prefix sum on an array.
*
* @tparam T The type of elements in the array.
* @param data The starting location of memory.
* @param size The number of elements in the array.
*/
template <typename T>
static void prefixSumExclusive(
T * const data,
size_t const size) noexcept
{
prefixSumExclusive(data, data+size);
}
/**
* @brief Perform a prefix sum on an array.
*
* @tparam T The type of elements in the array.
* @param data The starting location of memory.
* @param size The number of elements in the array.
*/
template <typename T>
static void prefixSumExclusive(
T const begin,
T const end) noexcept
{
using V = typename std::remove_reference<decltype(*begin)>::type;
V sum = 0;
for (T iter = begin; iter != end; ++iter) {
V const val = *iter;
*iter = sum;
sum += val;
}
}
};
}
#endif
<|endoftext|> |
<commit_before>#include <map>
#include <gtest/gtest.h>
#include "uint256_t.h"
static const std::map <uint32_t, std::string> tests = {
std::make_pair(2, "10000100000101011000010101101100"),
std::make_pair(3, "12201102210121112101"),
std::make_pair(4, "2010011120111230"),
std::make_pair(5, "14014244043144"),
std::make_pair(6, "1003520344444"),
std::make_pair(7, "105625466632"),
std::make_pair(8, "20405302554"),
std::make_pair(9, "5642717471"),
std::make_pair(10, "2216002924"),
std::make_pair(11, "a3796a883"),
std::make_pair(12, "51a175124"),
std::make_pair(13, "294145645"),
std::make_pair(14, "170445352"),
std::make_pair(15, "ce82d6d4"),
std::make_pair(16, "8415856c"),
std::make_pair(17, "56dc4e33"),
std::make_pair(18, "3b2db13a"),
std::make_pair(19, "291i3b4g"),
std::make_pair(20, "1eca0764"),
std::make_pair(21, "14hc96jg"),
std::make_pair(22, "jblga9e"),
std::make_pair(23, "em6i5a5"),
std::make_pair(24, "be75374"),
std::make_pair(25, "91mo4go"),
std::make_pair(26, "74d74li"),
std::make_pair(27, "5jblgea"),
std::make_pair(28, "4gl7i9g"),
std::make_pair(29, "3l13lor"),
std::make_pair(30, "315o5e4"),
std::make_pair(31, "2fcfub9"),
std::make_pair(32, "221b1bc"),
std::make_pair(33, "1nkji2p"),
std::make_pair(34, "1eq93ik"),
std::make_pair(35, "176p6y9"),
std::make_pair(36, "10ncmss")
// std::make_pair(256, "uint256_t"),
};
TEST(Function, str){
// number of leading 0s
const std::string::size_type leading = 5;
// make sure all of the test strings create the ASCII version of the string
const uint256_t original(2216002924);
for(std::pair <uint32_t const, std::string> t : tests){
EXPECT_EQ(original.str(t.first), t.second);
}
// add leading zeros
for(uint32_t base = 2; base <= 36; base++){
EXPECT_EQ(original.str(base, tests.at(base).size() + leading), std::string(leading, '0') + tests.at(base));
}
}
TEST(External, ostream){
const uint256_t value(0xfedcba9876543210ULL);
// write out octal uint256_t
std::stringstream oct; oct << std::oct << value;
EXPECT_EQ(oct.str(), "1773345651416625031020");
// write out decimal uint256_t
std::stringstream dec; dec << std::dec << value;
EXPECT_EQ(dec.str(), "18364758544493064720");
// write out hexadecimal uint256_t
std::stringstream hex; hex << std::hex << value;
EXPECT_EQ(hex.str(), "fedcba9876543210");
// zero
std::stringstream zero; zero << uint256_t();
EXPECT_EQ(zero.str(), "0");
}
<commit_msg>added test for export_bits and export_bits_truncate<commit_after>#include <map>
#include <gtest/gtest.h>
#include "uint256_t.h"
static const std::map <uint32_t, std::string> tests = {
std::make_pair(2, "10000100000101011000010101101100"),
std::make_pair(3, "12201102210121112101"),
std::make_pair(4, "2010011120111230"),
std::make_pair(5, "14014244043144"),
std::make_pair(6, "1003520344444"),
std::make_pair(7, "105625466632"),
std::make_pair(8, "20405302554"),
std::make_pair(9, "5642717471"),
std::make_pair(10, "2216002924"),
std::make_pair(11, "a3796a883"),
std::make_pair(12, "51a175124"),
std::make_pair(13, "294145645"),
std::make_pair(14, "170445352"),
std::make_pair(15, "ce82d6d4"),
std::make_pair(16, "8415856c"),
std::make_pair(17, "56dc4e33"),
std::make_pair(18, "3b2db13a"),
std::make_pair(19, "291i3b4g"),
std::make_pair(20, "1eca0764"),
std::make_pair(21, "14hc96jg"),
std::make_pair(22, "jblga9e"),
std::make_pair(23, "em6i5a5"),
std::make_pair(24, "be75374"),
std::make_pair(25, "91mo4go"),
std::make_pair(26, "74d74li"),
std::make_pair(27, "5jblgea"),
std::make_pair(28, "4gl7i9g"),
std::make_pair(29, "3l13lor"),
std::make_pair(30, "315o5e4"),
std::make_pair(31, "2fcfub9"),
std::make_pair(32, "221b1bc"),
std::make_pair(33, "1nkji2p"),
std::make_pair(34, "1eq93ik"),
std::make_pair(35, "176p6y9"),
std::make_pair(36, "10ncmss")
// std::make_pair(256, "uint256_t"),
};
TEST(Function, str){
// number of leading 0s
const std::string::size_type leading = 5;
// make sure all of the test strings create the ASCII version of the string
const uint256_t original(2216002924);
for(std::pair <uint32_t const, std::string> t : tests){
EXPECT_EQ(original.str(t.first), t.second);
}
// add leading zeros
for(uint32_t base = 2; base <= 36; base++){
EXPECT_EQ(original.str(base, tests.at(base).size() + leading), std::string(leading, '0') + tests.at(base));
}
}
TEST(Function, export_bits){
const uint64_t u64 = 0x0123456789abcdefULL;
const uint256_t value = u64;
EXPECT_EQ(value, u64);
const std::vector<uint8_t> full = {
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
};
EXPECT_EQ(value.export_bits(), full);
}
TEST(Function, export_bits_truncated){
const uint64_t u64 = 0x0123456789abcdefULL;
const uint256_t value = u64;
EXPECT_EQ(value, u64);
const std::vector<uint8_t> truncated = {
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef
};
EXPECT_EQ(value.export_bits_truncate(), truncated);
}
TEST(External, ostream){
const uint256_t value(0xfedcba9876543210ULL);
// write out octal uint256_t
std::stringstream oct; oct << std::oct << value;
EXPECT_EQ(oct.str(), "1773345651416625031020");
// write out decimal uint256_t
std::stringstream dec; dec << std::dec << value;
EXPECT_EQ(dec.str(), "18364758544493064720");
// write out hexadecimal uint256_t
std::stringstream hex; hex << std::hex << value;
EXPECT_EQ(hex.str(), "fedcba9876543210");
// zero
std::stringstream zero; zero << uint256_t();
EXPECT_EQ(zero.str(), "0");
}
<|endoftext|> |
<commit_before>// @(#)root/io:$Id$
// Author: Jakob Blomer
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RConfig.hxx"
#include "ROOT/RRawFileUnix.hxx"
#include "ROOT/RLogger.hxx" // for R__DEBUG_HERE
#include "ROOT/RMakeUnique.hxx"
#ifdef R__HAS_URING
#include "ROOT/RIoUring.hxx"
#endif
#include "TError.h"
#include <cerrno>
#include <cstring>
#include <stdexcept>
#include <string>
#include <utility>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace {
constexpr int kDefaultBlockSize = 4096; // If fstat() does not provide a block size hint, use this value instead
} // anonymous namespace
ROOT::Internal::RRawFileUnix::RRawFileUnix(std::string_view url, ROptions options)
: RRawFile(url, options), fFileDes(-1)
{
}
ROOT::Internal::RRawFileUnix::~RRawFileUnix()
{
if (fFileDes >= 0)
close(fFileDes);
}
std::unique_ptr<ROOT::Internal::RRawFile> ROOT::Internal::RRawFileUnix::Clone() const
{
return std::make_unique<RRawFileUnix>(fUrl, fOptions);
}
int ROOT::Internal::RRawFileUnix::GetFeatures() const {
return kFeatureHasSize | kFeatureHasMmap;
}
std::uint64_t ROOT::Internal::RRawFileUnix::GetSizeImpl()
{
#ifdef R__SEEK64
struct stat64 info;
int res = fstat64(fFileDes, &info);
#else
struct stat info;
int res = fstat(fFileDes, &info);
#endif
if (res != 0)
throw std::runtime_error("Cannot call fstat on '" + fUrl + "', error: " + std::string(strerror(errno)));
return info.st_size;
}
void *ROOT::Internal::RRawFileUnix::MapImpl(size_t nbytes, std::uint64_t offset, std::uint64_t &mapdOffset)
{
static std::uint64_t szPageBitmap = sysconf(_SC_PAGESIZE) - 1;
mapdOffset = offset & ~szPageBitmap;
nbytes += offset & szPageBitmap;
void *result = mmap(nullptr, nbytes, PROT_READ, MAP_PRIVATE, fFileDes, mapdOffset);
if (result == MAP_FAILED)
throw std::runtime_error(std::string("Cannot perform memory mapping: ") + strerror(errno));
return result;
}
void ROOT::Internal::RRawFileUnix::OpenImpl()
{
#ifdef R__SEEK64
fFileDes = open64(GetLocation(fUrl).c_str(), O_RDONLY);
#else
fFileDes = open(GetLocation(fUrl).c_str(), O_RDONLY);
#endif
if (fFileDes < 0) {
throw std::runtime_error("Cannot open '" + fUrl + "', error: " + std::string(strerror(errno)));
}
if (fOptions.fBlockSize >= 0)
return;
#ifdef R__SEEK64
struct stat64 info;
int res = fstat64(fFileDes, &info);
#else
struct stat info;
int res = fstat(fFileDes, &info);
#endif
if (res != 0) {
throw std::runtime_error("Cannot call fstat on '" + fUrl + "', error: " + std::string(strerror(errno)));
}
if (info.st_blksize > 0) {
fOptions.fBlockSize = info.st_blksize;
} else {
fOptions.fBlockSize = kDefaultBlockSize;
}
}
void ROOT::Internal::RRawFileUnix::ReadVImpl(RIOVec *ioVec, unsigned int nReq)
{
#ifdef R__HAS_URING
if (!RIoUring::IsAvailable()) {
R__DEBUG_HERE("RRawFileUnix") <<
"io_uring setup failed, falling back to default ReadV implementation";
RRawFile::ReadVImpl(ioVec, nReq);
return;
}
// check we can construct the ring
RIoUring ring(8);
throw std::runtime_error("io_uring ReadV unimplemented!");
#else
RRawFile::ReadVImpl(ioVec, nReq);
#endif
}
size_t ROOT::Internal::RRawFileUnix::ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset)
{
size_t total_bytes = 0;
while (nbytes) {
#ifdef R__SEEK64
ssize_t res = pread64(fFileDes, buffer, nbytes, offset);
#else
ssize_t res = pread(fFileDes, buffer, nbytes, offset);
#endif
if (res < 0) {
if (errno == EINTR)
continue;
throw std::runtime_error("Cannot read from '" + fUrl + "', error: " + std::string(strerror(errno)));
} else if (res == 0) {
return total_bytes;
}
R__ASSERT(static_cast<size_t>(res) <= nbytes);
buffer = reinterpret_cast<unsigned char *>(buffer) + res;
nbytes -= res;
total_bytes += res;
offset += res;
}
return total_bytes;
}
void ROOT::Internal::RRawFileUnix::UnmapImpl(void *region, size_t nbytes)
{
int rv = munmap(region, nbytes);
if (rv != 0)
throw std::runtime_error(std::string("Cannot remove memory mapping: ") + strerror(errno));
}
<commit_msg>[io] try and fix RLogger.hxx include<commit_after>// @(#)root/io:$Id$
// Author: Jakob Blomer
/*************************************************************************
* Copyright (C) 1995-2018, Rene Brun and Fons Rademakers. *
* All rights reserved. *
* *
* For the licensing terms see $ROOTSYS/LICENSE. *
* For the list of contributors see $ROOTSYS/README/CREDITS. *
*************************************************************************/
#include "ROOT/RConfig.hxx"
#include <ROOT/RLogger.hxx> // for R__DEBUG_HERE
#include "ROOT/RRawFileUnix.hxx"
#include "ROOT/RMakeUnique.hxx"
#ifdef R__HAS_URING
#include "ROOT/RIoUring.hxx"
#endif
#include "TError.h"
#include <cerrno>
#include <cstring>
#include <stdexcept>
#include <string>
#include <utility>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
namespace {
constexpr int kDefaultBlockSize = 4096; // If fstat() does not provide a block size hint, use this value instead
} // anonymous namespace
ROOT::Internal::RRawFileUnix::RRawFileUnix(std::string_view url, ROptions options)
: RRawFile(url, options), fFileDes(-1)
{
}
ROOT::Internal::RRawFileUnix::~RRawFileUnix()
{
if (fFileDes >= 0)
close(fFileDes);
}
std::unique_ptr<ROOT::Internal::RRawFile> ROOT::Internal::RRawFileUnix::Clone() const
{
return std::make_unique<RRawFileUnix>(fUrl, fOptions);
}
int ROOT::Internal::RRawFileUnix::GetFeatures() const {
return kFeatureHasSize | kFeatureHasMmap;
}
std::uint64_t ROOT::Internal::RRawFileUnix::GetSizeImpl()
{
#ifdef R__SEEK64
struct stat64 info;
int res = fstat64(fFileDes, &info);
#else
struct stat info;
int res = fstat(fFileDes, &info);
#endif
if (res != 0)
throw std::runtime_error("Cannot call fstat on '" + fUrl + "', error: " + std::string(strerror(errno)));
return info.st_size;
}
void *ROOT::Internal::RRawFileUnix::MapImpl(size_t nbytes, std::uint64_t offset, std::uint64_t &mapdOffset)
{
static std::uint64_t szPageBitmap = sysconf(_SC_PAGESIZE) - 1;
mapdOffset = offset & ~szPageBitmap;
nbytes += offset & szPageBitmap;
void *result = mmap(nullptr, nbytes, PROT_READ, MAP_PRIVATE, fFileDes, mapdOffset);
if (result == MAP_FAILED)
throw std::runtime_error(std::string("Cannot perform memory mapping: ") + strerror(errno));
return result;
}
void ROOT::Internal::RRawFileUnix::OpenImpl()
{
#ifdef R__SEEK64
fFileDes = open64(GetLocation(fUrl).c_str(), O_RDONLY);
#else
fFileDes = open(GetLocation(fUrl).c_str(), O_RDONLY);
#endif
if (fFileDes < 0) {
throw std::runtime_error("Cannot open '" + fUrl + "', error: " + std::string(strerror(errno)));
}
if (fOptions.fBlockSize >= 0)
return;
#ifdef R__SEEK64
struct stat64 info;
int res = fstat64(fFileDes, &info);
#else
struct stat info;
int res = fstat(fFileDes, &info);
#endif
if (res != 0) {
throw std::runtime_error("Cannot call fstat on '" + fUrl + "', error: " + std::string(strerror(errno)));
}
if (info.st_blksize > 0) {
fOptions.fBlockSize = info.st_blksize;
} else {
fOptions.fBlockSize = kDefaultBlockSize;
}
}
void ROOT::Internal::RRawFileUnix::ReadVImpl(RIOVec *ioVec, unsigned int nReq)
{
#ifdef R__HAS_URING
if (!RIoUring::IsAvailable()) {
R__DEBUG_HERE("RRawFileUnix") <<
"io_uring setup failed, falling back to default ReadV implementation";
RRawFile::ReadVImpl(ioVec, nReq);
return;
}
// check we can construct the ring
RIoUring ring(8);
throw std::runtime_error("io_uring ReadV unimplemented!");
#else
RRawFile::ReadVImpl(ioVec, nReq);
#endif
}
size_t ROOT::Internal::RRawFileUnix::ReadAtImpl(void *buffer, size_t nbytes, std::uint64_t offset)
{
size_t total_bytes = 0;
while (nbytes) {
#ifdef R__SEEK64
ssize_t res = pread64(fFileDes, buffer, nbytes, offset);
#else
ssize_t res = pread(fFileDes, buffer, nbytes, offset);
#endif
if (res < 0) {
if (errno == EINTR)
continue;
throw std::runtime_error("Cannot read from '" + fUrl + "', error: " + std::string(strerror(errno)));
} else if (res == 0) {
return total_bytes;
}
R__ASSERT(static_cast<size_t>(res) <= nbytes);
buffer = reinterpret_cast<unsigned char *>(buffer) + res;
nbytes -= res;
total_bytes += res;
offset += res;
}
return total_bytes;
}
void ROOT::Internal::RRawFileUnix::UnmapImpl(void *region, size_t nbytes)
{
int rv = munmap(region, nbytes);
if (rv != 0)
throw std::runtime_error(std::string("Cannot remove memory mapping: ") + strerror(errno));
}
<|endoftext|> |
<commit_before>#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
// If you find this code useful, please add a reference to the following paper in your work:
// Gil Levi and Tal Hassner, "LATCH: Learned Arrangements of Three Patch Codes", arXiv preprint arXiv:1501.03719, 15 Jan. 2015
using namespace std;
using namespace cv;
const float inlier_threshold = 2.5f; // Distance threshold to identify inliers
const float nn_match_ratio = 0.8f; // Nearest neighbor matching ratio
int main(void)
{
Mat img1 = imread("../data/graf1.png", IMREAD_GRAYSCALE);
Mat img2 = imread("../data/graf3.png", IMREAD_GRAYSCALE);
Mat homography;
FileStorage fs("../data/H1to3p.xml", FileStorage::READ);
fs.getFirstTopLevelNode() >> homography;
vector<KeyPoint> kpts1, kpts2;
Mat desc1, desc2;
Ptr<cv::ORB> orb_detector = cv::ORB::create(10000);
Ptr<xfeatures2d::LATCHDescriptorExtractor> latch = xfeatures2d::LATCHDescriptorExtractor::create();
orb_detector->detect(img1, kpts1);
latch->compute(img1, kpts1, desc1);
orb_detector->detect(img2, kpts2);
latch->compute(img2, kpts2, desc2);
BFMatcher matcher(NORM_HAMMING);
vector< vector<DMatch> > nn_matches;
matcher.knnMatch(desc1, desc2, nn_matches, 2);
vector<KeyPoint> matched1, matched2, inliers1, inliers2;
vector<DMatch> good_matches;
for (size_t i = 0; i < nn_matches.size(); i++) {
DMatch first = nn_matches[i][0];
float dist1 = nn_matches[i][0].distance;
float dist2 = nn_matches[i][1].distance;
if (dist1 < nn_match_ratio * dist2) {
matched1.push_back(kpts1[first.queryIdx]);
matched2.push_back(kpts2[first.trainIdx]);
}
}
for (unsigned i = 0; i < matched1.size(); i++) {
Mat col = Mat::ones(3, 1, CV_64F);
col.at<double>(0) = matched1[i].pt.x;
col.at<double>(1) = matched1[i].pt.y;
col = homography * col;
col /= col.at<double>(2);
double dist = sqrt(pow(col.at<double>(0) - matched2[i].pt.x, 2) +
pow(col.at<double>(1) - matched2[i].pt.y, 2));
if (dist < inlier_threshold) {
int new_i = static_cast<int>(inliers1.size());
inliers1.push_back(matched1[i]);
inliers2.push_back(matched2[i]);
good_matches.push_back(DMatch(new_i, new_i, 0));
}
}
Mat res;
drawMatches(img1, inliers1, img2, inliers2, good_matches, res);
imwrite("../../samples/data/latch_res.png", res);
double inlier_ratio = inliers1.size() * 1.0 / matched1.size();
cout << "LATCH Matching Results" << endl;
cout << "*******************************" << endl;
cout << "# Keypoints 1: \t" << kpts1.size() << endl;
cout << "# Keypoints 2: \t" << kpts2.size() << endl;
cout << "# Matches: \t" << matched1.size() << endl;
cout << "# Inliers: \t" << inliers1.size() << endl;
cout << "# Inliers Ratio: \t" << inlier_ratio << endl;
cout << endl;
return 0;
}
<commit_msg>renamed LATCH<commit_after>#include <opencv2/features2d.hpp>
#include <opencv2/xfeatures2d.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
// If you find this code useful, please add a reference to the following paper in your work:
// Gil Levi and Tal Hassner, "LATCH: Learned Arrangements of Three Patch Codes", arXiv preprint arXiv:1501.03719, 15 Jan. 2015
using namespace std;
using namespace cv;
const float inlier_threshold = 2.5f; // Distance threshold to identify inliers
const float nn_match_ratio = 0.8f; // Nearest neighbor matching ratio
int main(void)
{
Mat img1 = imread("../data/graf1.png", IMREAD_GRAYSCALE);
Mat img2 = imread("../data/graf3.png", IMREAD_GRAYSCALE);
Mat homography;
FileStorage fs("../data/H1to3p.xml", FileStorage::READ);
fs.getFirstTopLevelNode() >> homography;
vector<KeyPoint> kpts1, kpts2;
Mat desc1, desc2;
Ptr<cv::ORB> orb_detector = cv::ORB::create(10000);
Ptr<xfeatures2d::LATCH> latch = xfeatures2d::LATCH::create();
orb_detector->detect(img1, kpts1);
latch->compute(img1, kpts1, desc1);
orb_detector->detect(img2, kpts2);
latch->compute(img2, kpts2, desc2);
BFMatcher matcher(NORM_HAMMING);
vector< vector<DMatch> > nn_matches;
matcher.knnMatch(desc1, desc2, nn_matches, 2);
vector<KeyPoint> matched1, matched2, inliers1, inliers2;
vector<DMatch> good_matches;
for (size_t i = 0; i < nn_matches.size(); i++) {
DMatch first = nn_matches[i][0];
float dist1 = nn_matches[i][0].distance;
float dist2 = nn_matches[i][1].distance;
if (dist1 < nn_match_ratio * dist2) {
matched1.push_back(kpts1[first.queryIdx]);
matched2.push_back(kpts2[first.trainIdx]);
}
}
for (unsigned i = 0; i < matched1.size(); i++) {
Mat col = Mat::ones(3, 1, CV_64F);
col.at<double>(0) = matched1[i].pt.x;
col.at<double>(1) = matched1[i].pt.y;
col = homography * col;
col /= col.at<double>(2);
double dist = sqrt(pow(col.at<double>(0) - matched2[i].pt.x, 2) +
pow(col.at<double>(1) - matched2[i].pt.y, 2));
if (dist < inlier_threshold) {
int new_i = static_cast<int>(inliers1.size());
inliers1.push_back(matched1[i]);
inliers2.push_back(matched2[i]);
good_matches.push_back(DMatch(new_i, new_i, 0));
}
}
Mat res;
drawMatches(img1, inliers1, img2, inliers2, good_matches, res);
imwrite("../../samples/data/latch_res.png", res);
double inlier_ratio = inliers1.size() * 1.0 / matched1.size();
cout << "LATCH Matching Results" << endl;
cout << "*******************************" << endl;
cout << "# Keypoints 1: \t" << kpts1.size() << endl;
cout << "# Keypoints 2: \t" << kpts2.size() << endl;
cout << "# Matches: \t" << matched1.size() << endl;
cout << "# Inliers: \t" << inliers1.size() << endl;
cout << "# Inliers Ratio: \t" << inlier_ratio << endl;
cout << endl;
return 0;
}
<|endoftext|> |
<commit_before>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
if (node1 == node2
and node2->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
return true;
}
if (lsoln->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
const IncomingSet &incoming_set = h->getIncomingSet();
IncomingSet filtered_set;
for (IncomingSet::const_iterator i = incoming_set.begin();
i != incoming_set.end(); ++i) {
Handle candidate_handle(*i);
if (candidate_handle->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
filtered_set.push_back(LinkCast(candidate_handle));
}
}
// if none is in AF
if (filtered_set.empty()) {
//xxx what shall we do here?, return the default or return empty ?
filtered_set = incoming_set;
}
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
return filtered_set;
}
<commit_msg>changed get_incoming_set defn and removed redundant header inclusions<commit_after>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
bool AttentionalFocusCB::node_match(Handle& node1, Handle& node2) {
if (node1 == node2
and node2->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
bool AttentionalFocusCB::link_match(LinkPtr& lpat, LinkPtr& lsoln) {
if (DefaultPatternMatchCB::link_match(lpat, lsoln)) {
return true;
}
if (lsoln->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
return false;
} else {
return true;
}
}
IncomingSet AttentionalFocusCB::get_incoming_set(Handle h) {
const IncomingSet &incoming_set = h->getIncomingSet();
IncomingSet filtered_set;
for (IncomingSet::const_iterator i = incoming_set.begin();
i != incoming_set.end(); ++i) {
Handle candidate_handle(*i);
if (candidate_handle->getAttentionValue()->getSTI()
> _atom_space->getAttentionalFocusBoundary()) {
filtered_set.push_back(LinkCast(candidate_handle));
}
}
// if none is in AF
if (filtered_set.empty()) {
//xxx what shall we do here?, return the default or return empty ?
filtered_set = incoming_set;
}
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti); //sort by STI for better performance
return filtered_set;
}
<|endoftext|> |
<commit_before>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
// Uncomment below to enable debug print
// #define DEBUG
#ifdef DEBUG
#define dbgprt(f, varargs...) printf(f, ##varargs)
#else
#define dbgprt(f, varargs...)
#endif
bool AttentionalFocusCB::node_match(const Handle& node1, const Handle& node2)
{
return node1 == node2 and
node2->getSTI() > _as->getAttentionalFocusBoundary();
}
bool AttentionalFocusCB::link_match(const LinkPtr& lpat, const LinkPtr& lsoln)
{
return DefaultPatternMatchCB::link_match(lpat, lsoln)
and lsoln->getSTI() > _as->getAttentionalFocusBoundary();
}
IncomingSet AttentionalFocusCB::get_incoming_set(const Handle& h)
{
const IncomingSet &incoming_set = h->getIncomingSet();
// Discard the part of the incoming set that is below the
// AF boundary. The PM will look only at those links that
// this callback returns; thus we avoid searching the low-AF
// parts of the hypergraph.
IncomingSet filtered_set;
for (const auto& l : incoming_set)
if (l->getSTI() > _as->getAttentionalFocusBoundary())
filtered_set.push_back(l);
// If nothing is in AF
if (filtered_set.empty())
{
// XXX What shall we do here? Return the default or return empty ?
// Returning empty completely halts the search up to this point
// ... and maybe that is a good thing, right? But it might also
// mean that there is an AF bug somewhere ... I think that
// returning the empty set is really probably the right thing ...
// XXX TODO test with PLN and FIXME ...
filtered_set = incoming_set;
}
// The exploration of the set of patterns proceeds by going through
// the incoming set, one by one. So sorting the incoming set will
// cause the exploration to look at the highest STI atoms first.
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti);
return filtered_set;
}
void AttentionalFocusCB::perform_search(PatternMatchEngine *pme,
const std::set<Handle> &vars,
const std::vector<Handle> &clauses,
const std::vector<Handle> &negations)
{
// In principle, we could start our search at some node, any node,
// that is not a variable. In practice, the search begins by
// iterating over the incoming set of the node, and so, if it is
// large, a huge amount of effort might be wasted exploring
// dead-ends. Thus, it pays off to start the search on the
// node with the smallest ("narrowest" or "thinnest") incoming set
// possible. Thus, we look at all the clauses, to find the
// "thinnest" one.
//
// Note also: the user is allowed to specify patterns that have
// no constants in them at all. In this case, the search is
// performed by looping over all links of the given types.
size_t bestclause;
Handle best_start = find_thinnest(clauses, _starter_pred, bestclause);
if ((Handle::UNDEFINED != best_start) and
// (Handle::UNDEFINED != _starter_pred) and
(!vars.empty()))
{
_root = clauses[bestclause];
dbgprt("Search start node: %s\n", best_start->toShortString().c_str());
dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str());
// This should be calling the over-loaded virtual method
// get_incoming_set(), so that, e.g. it gets sorted by attentional
// focus in the AttentionalFocusCB class...
IncomingSet iset = get_incoming_set(best_start);
size_t sz = iset.size();
for (size_t i = 0; i < sz; i++) {
Handle h(iset[i]);
dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
dbgprt("Loop candidate (%lu/%lu): %s\n", i, sz,
h->toShortString().c_str());
bool rc = pme->do_candidate(_root, _starter_pred, h);
if (rc) break;
}
// If we are here, we are done.
return;
}
// If we are here, then we could not find a clause at which to start,
// as, apparently, the clauses consist entirely of variables!! So,
// basically, we must search the entire!! atomspace, in this case.
// Yes, this hurts.
_root = clauses[0];
_starter_pred = _root;
dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str());
// Get the set of types of the potential candidates
std::set<Type> ptypes;
if (_root->getType() == VARIABLE_NODE)
ptypes = _type_restrictions->at(_root);
// XXX TODO -- as a performance optimization, we should try all
// the different clauses, and find the one with the smallest number
// of atoms of that type, or otherwise try to find a small ("thin")
// incoming set to search over.
// Plunge into the deep end - start looking at all viable
// candidates in the AtomSpace.
std::list<Handle> handle_set;
_as->getHandleSetInAttentionalFocus(back_inserter(handle_set));
// WARNING: if there's nothing in the attentional focus then get
// the whole atomspace
if (handle_set.empty())
_as->getHandlesByType(back_inserter(handle_set), ATOM, true);
// Filter by variable types
if (not ptypes.empty()) {
auto it = remove_if(handle_set.begin(), handle_set.end(),
[&ptypes](const Handle& h) {
return ptypes.find(h->getType()) == ptypes.end();
});
handle_set.erase(it, handle_set.end());
}
size_t handle_set_size = handle_set.size(), i = 0;
for (const Handle& h : handle_set)
{
dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
dbgprt("Loop candidate (%lu/%lu): %s\n", i++, handle_set_size,
h->toShortString().c_str());
bool rc = pme->do_candidate(_root, _starter_pred, h);
if (rc) break;
}
}
<commit_msg>Fix compiler warning<commit_after>/*
* AttentionalFocusCB.cc
*
* Copyright (C) 2014 Misgana Bayetta
*
* Author: Misgana Bayetta <[email protected]> July 2014
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License v3 as
* published by the Free Software Foundation and including the exceptions
* at http://opencog.org/wiki/Licenses
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to:
* Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "AttentionalFocusCB.h"
using namespace opencog;
// Uncomment below to enable debug print
// #define DEBUG
#ifdef DEBUG
#define dbgprt(f, varargs...) printf(f, ##varargs)
#else
#define dbgprt(f, varargs...)
#endif
bool AttentionalFocusCB::node_match(const Handle& node1, const Handle& node2)
{
return node1 == node2 and
node2->getSTI() > _as->getAttentionalFocusBoundary();
}
bool AttentionalFocusCB::link_match(const LinkPtr& lpat, const LinkPtr& lsoln)
{
return DefaultPatternMatchCB::link_match(lpat, lsoln)
and lsoln->getSTI() > _as->getAttentionalFocusBoundary();
}
IncomingSet AttentionalFocusCB::get_incoming_set(const Handle& h)
{
const IncomingSet &incoming_set = h->getIncomingSet();
// Discard the part of the incoming set that is below the
// AF boundary. The PM will look only at those links that
// this callback returns; thus we avoid searching the low-AF
// parts of the hypergraph.
IncomingSet filtered_set;
for (const auto& l : incoming_set)
if (l->getSTI() > _as->getAttentionalFocusBoundary())
filtered_set.push_back(l);
// If nothing is in AF
if (filtered_set.empty())
{
// XXX What shall we do here? Return the default or return empty ?
// Returning empty completely halts the search up to this point
// ... and maybe that is a good thing, right? But it might also
// mean that there is an AF bug somewhere ... I think that
// returning the empty set is really probably the right thing ...
// XXX TODO test with PLN and FIXME ...
filtered_set = incoming_set;
}
// The exploration of the set of patterns proceeds by going through
// the incoming set, one by one. So sorting the incoming set will
// cause the exploration to look at the highest STI atoms first.
std::sort(filtered_set.begin(), filtered_set.end(), compare_sti);
return filtered_set;
}
void AttentionalFocusCB::perform_search(PatternMatchEngine *pme,
const std::set<Handle> &vars,
const std::vector<Handle> &clauses,
const std::vector<Handle> &negations)
{
// In principle, we could start our search at some node, any node,
// that is not a variable. In practice, the search begins by
// iterating over the incoming set of the node, and so, if it is
// large, a huge amount of effort might be wasted exploring
// dead-ends. Thus, it pays off to start the search on the
// node with the smallest ("narrowest" or "thinnest") incoming set
// possible. Thus, we look at all the clauses, to find the
// "thinnest" one.
//
// Note also: the user is allowed to specify patterns that have
// no constants in them at all. In this case, the search is
// performed by looping over all links of the given types.
size_t bestclause;
Handle best_start = find_thinnest(clauses, _starter_pred, bestclause);
if ((Handle::UNDEFINED != best_start) and
// (Handle::UNDEFINED != _starter_pred) and
(!vars.empty()))
{
_root = clauses[bestclause];
dbgprt("Search start node: %s\n", best_start->toShortString().c_str());
dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str());
// This should be calling the over-loaded virtual method
// get_incoming_set(), so that, e.g. it gets sorted by attentional
// focus in the AttentionalFocusCB class...
IncomingSet iset = get_incoming_set(best_start);
size_t sz = iset.size();
for (size_t i = 0; i < sz; i++) {
Handle h(iset[i]);
dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
dbgprt("Loop candidate (%lu/%lu): %s\n", i, sz,
h->toShortString().c_str());
bool rc = pme->do_candidate(_root, _starter_pred, h);
if (rc) break;
}
// If we are here, we are done.
return;
}
// If we are here, then we could not find a clause at which to start,
// as, apparently, the clauses consist entirely of variables!! So,
// basically, we must search the entire!! atomspace, in this case.
// Yes, this hurts.
_root = clauses[0];
_starter_pred = _root;
dbgprt("Start pred is: %s\n", _starter_pred->toShortString().c_str());
// Get the set of types of the potential candidates
std::set<Type> ptypes;
if (_root->getType() == VARIABLE_NODE)
ptypes = _type_restrictions->at(_root);
// XXX TODO -- as a performance optimization, we should try all
// the different clauses, and find the one with the smallest number
// of atoms of that type, or otherwise try to find a small ("thin")
// incoming set to search over.
// Plunge into the deep end - start looking at all viable
// candidates in the AtomSpace.
std::list<Handle> handle_set;
_as->getHandleSetInAttentionalFocus(back_inserter(handle_set));
// WARNING: if there's nothing in the attentional focus then get
// the whole atomspace
if (handle_set.empty())
_as->getHandlesByType(back_inserter(handle_set), ATOM, true);
// Filter by variable types
if (not ptypes.empty()) {
auto it = remove_if(handle_set.begin(), handle_set.end(),
[&ptypes](const Handle& h) {
return ptypes.find(h->getType()) == ptypes.end();
});
handle_set.erase(it, handle_set.end());
}
#ifdef DEBUG
size_t i = 0;
#endif
for (const Handle& h : handle_set)
{
dbgprt("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n");
dbgprt("Loop candidate (%lu/%lu): %s\n", ++i, handle_set.size(),
h->toShortString().c_str());
bool rc = pme->do_candidate(_root, _starter_pred, h);
if (rc) break;
}
}
<|endoftext|> |
<commit_before><commit_msg>Modified method data handling and fix #57<commit_after><|endoftext|> |
<commit_before>#include <bits/stdc++.h>
using namespace std;
int findMinimum(int num, int digits){
vector<int> splitArr;
int pos = 0;
while(num>0){
splitArr.push_back(num % 10);
num /= 10;
pos++;
}
sort(splitArr.begin(), splitArr.end());
int resultLen = splitArr.size()-digits;
pos = 0; num = 0;
while(resultLen){
num = num*10 + splitArr[pos];
pos++;
resultLen--;
}
return num;
}
int main(){
int num,digits;
cout<<"Enter input Number: ";
cin>>num;
cout<<"Enter number of digits to remove: ";
cin>>digits;
cout<<findMinimum(num,digits)<<endl;
return 0;
}<commit_msg>Update deleteDigits.cpp<commit_after>#include <bits/stdc++.h>
using namespace std;
int findMinimum(int num, int digits){
vector<int> splitArr;
int pos = 0;
while(num>0){
splitArr.push_back(num % 10);
num /= 10;
pos++;
}
sort(splitArr.begin(), splitArr.end());
int resultLen = splitArr.size()-digits;
if(resultLen < 1) return 0;
pos = 0; num = 0;
while(resultLen){
num = num*10 + splitArr[pos];
pos++;
resultLen--;
}
return num;
}
int main(){
int num,digits;
cout<<"Enter input Number: ";
cin>>num;
assert(num>-1);
cout<<"Enter number of digits to remove: ";
cin>>digits;
assert(digits>-1);
cout<<findMinimum(num,digits)<<endl;
return 0;
}<|endoftext|> |
<commit_before>/***********************************************************************
filename: CEGUIOgreTextureTarget.cpp
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreRenderTexture.h>
#include <OgreRenderSystem.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OgreTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
OgreRenderTarget(owner, rs),
d_CEGUITexture(0)
{
d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture());
// setup area and cause the initial texture to be generated.
declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}
//----------------------------------------------------------------------------//
OgreTextureTarget::~OgreTextureTarget()
{
d_owner.destroyTexture(*d_CEGUITexture);
}
//----------------------------------------------------------------------------//
bool OgreTextureTarget::isImageryCache() const
{
return true;
}
//----------------------------------------------------------------------------//
void OgreTextureTarget::clear()
{
if (!d_viewportValid)
updateViewport();
Ogre::Viewport* old_vp = d_renderSystem._getViewport();
d_renderSystem._setViewport(d_viewport);
d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR,
Ogre::ColourValue(0, 0, 0, 0));
if (old_vp)
d_renderSystem._setViewport(old_vp);
}
//----------------------------------------------------------------------------//
Texture& OgreTextureTarget::getTexture() const
{
return *d_CEGUITexture;
}
//----------------------------------------------------------------------------//
void OgreTextureTarget::declareRenderSize(const Size& sz)
{
// exit if current size is enough
if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height))
return;
Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual(
OgreTexture::getUniqueName(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8,
Ogre::TU_RENDERTARGET);
d_renderTarget = rttTex->getBuffer()->getRenderTarget();
Rect init_area(
Vector2(0, 0),
Size(d_renderTarget->getWidth(), d_renderTarget->getHeight())
);
setArea(init_area);
// delete viewport and reset ptr so a new one is generated. This is
// required because we have changed d_renderTarget so need a new VP also.
delete d_viewport;
d_viewport = 0;
// because Texture takes ownership, the act of setting the new ogre texture
// also ensures any previous ogre texture is released.
d_CEGUITexture->setOgreTexture(rttTex, true);
clear();
}
//----------------------------------------------------------------------------//
bool OgreTextureTarget::isRenderingInverted() const
{
return false;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<commit_msg>FIX: Crash in Ogre based texture target, where we may inadvertently restore a deleted viewport to the render system.<commit_after>/***********************************************************************
filename: CEGUIOgreTextureTarget.cpp
created: Tue Feb 17 2009
author: Paul D Turner
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUIOgreTextureTarget.h"
#include "CEGUIOgreTexture.h"
#include <OgreTextureManager.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreRenderTexture.h>
#include <OgreRenderSystem.h>
// Start of CEGUI namespace section
namespace CEGUI
{
//----------------------------------------------------------------------------//
const float OgreTextureTarget::DEFAULT_SIZE = 128.0f;
//----------------------------------------------------------------------------//
OgreTextureTarget::OgreTextureTarget(OgreRenderer& owner,
Ogre::RenderSystem& rs) :
OgreRenderTarget(owner, rs),
d_CEGUITexture(0)
{
d_CEGUITexture = static_cast<OgreTexture*>(&d_owner.createTexture());
// setup area and cause the initial texture to be generated.
declareRenderSize(Size(DEFAULT_SIZE, DEFAULT_SIZE));
}
//----------------------------------------------------------------------------//
OgreTextureTarget::~OgreTextureTarget()
{
d_owner.destroyTexture(*d_CEGUITexture);
}
//----------------------------------------------------------------------------//
bool OgreTextureTarget::isImageryCache() const
{
return true;
}
//----------------------------------------------------------------------------//
void OgreTextureTarget::clear()
{
if (!d_viewportValid)
updateViewport();
d_renderSystem._setViewport(d_viewport);
d_renderSystem.clearFrameBuffer(Ogre::FBT_COLOUR,
Ogre::ColourValue(0, 0, 0, 0));
}
//----------------------------------------------------------------------------//
Texture& OgreTextureTarget::getTexture() const
{
return *d_CEGUITexture;
}
//----------------------------------------------------------------------------//
void OgreTextureTarget::declareRenderSize(const Size& sz)
{
// exit if current size is enough
if ((d_area.getWidth() >= sz.d_width) && (d_area.getHeight() >=sz.d_height))
return;
Ogre::TexturePtr rttTex = Ogre::TextureManager::getSingleton().createManual(
OgreTexture::getUniqueName(),
Ogre::ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
Ogre::TEX_TYPE_2D, sz.d_width, sz.d_height, 1, 0, Ogre::PF_A8R8G8B8,
Ogre::TU_RENDERTARGET);
d_renderTarget = rttTex->getBuffer()->getRenderTarget();
Rect init_area(
Vector2(0, 0),
Size(d_renderTarget->getWidth(), d_renderTarget->getHeight())
);
setArea(init_area);
// delete viewport and reset ptr so a new one is generated. This is
// required because we have changed d_renderTarget so need a new VP also.
delete d_viewport;
d_viewport = 0;
// because Texture takes ownership, the act of setting the new ogre texture
// also ensures any previous ogre texture is released.
d_CEGUITexture->setOgreTexture(rttTex, true);
clear();
}
//----------------------------------------------------------------------------//
bool OgreTextureTarget::isRenderingInverted() const
{
return false;
}
//----------------------------------------------------------------------------//
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium 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 "chrome/browser/extensions/extension_apitest.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/extensions/extension_test_api.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kNewInputMethod[] = "ru::rus";
const char kSetInputMethodMessage[] = "setInputMethod";
const char kSetInputMethodDone[] = "done";
// Class that listens for the JS message then changes input method and replies
// back.
class SetInputMethodListener : public content::NotificationObserver {
public:
// Creates listener, which should reply exactly |count_| times.
explicit SetInputMethodListener(int count) : count_(count) {
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_TEST_MESSAGE,
NotificationService::AllSources());
}
virtual ~SetInputMethodListener() {
EXPECT_EQ(0, count_);
}
// Implements the content::NotificationObserver interface.
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
const std::string& content = *Details<std::string>(details).ptr();
const std::string expected_message = StringPrintf("%s:%s",
kSetInputMethodMessage,
kNewInputMethod);
if (content == expected_message) {
chromeos::input_method::InputMethodManager::GetInstance()->
ChangeInputMethod(StringPrintf("xkb:%s", kNewInputMethod));
ExtensionTestSendMessageFunction* function =
content::Source<ExtensionTestSendMessageFunction>(source).ptr();
EXPECT_GT(count_--, 0);
function->Reply(kSetInputMethodDone);
}
}
private:
content::NotificationRegistrar registrar_;
int count_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, InputMethodApiBasic) {
// Two test, two calls. See JS code for more info.
SetInputMethodListener listener(2);
ASSERT_TRUE(RunExtensionTest("input_method")) << message_;
}
<commit_msg>Fix more cros build errors in tests.<commit_after>// Copyright (c) 2011 The Chromium 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 "chrome/browser/extensions/extension_apitest.h"
#include "base/stringprintf.h"
#include "chrome/browser/chromeos/extensions/input_method_event_router.h"
#include "chrome/browser/chromeos/input_method/input_method_manager.h"
#include "chrome/browser/extensions/extension_test_api.h"
#include "chrome/common/chrome_notification_types.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/common/notification_service.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
const char kNewInputMethod[] = "ru::rus";
const char kSetInputMethodMessage[] = "setInputMethod";
const char kSetInputMethodDone[] = "done";
// Class that listens for the JS message then changes input method and replies
// back.
class SetInputMethodListener : public content::NotificationObserver {
public:
// Creates listener, which should reply exactly |count_| times.
explicit SetInputMethodListener(int count) : count_(count) {
registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_TEST_MESSAGE,
NotificationService::AllSources());
}
virtual ~SetInputMethodListener() {
EXPECT_EQ(0, count_);
}
// Implements the content::NotificationObserver interface.
virtual void Observe(int type,
const content::NotificationSource& source,
const content::NotificationDetails& details) {
const std::string& content = *content::Details<std::string>(details).ptr();
const std::string expected_message = StringPrintf("%s:%s",
kSetInputMethodMessage,
kNewInputMethod);
if (content == expected_message) {
chromeos::input_method::InputMethodManager::GetInstance()->
ChangeInputMethod(StringPrintf("xkb:%s", kNewInputMethod));
ExtensionTestSendMessageFunction* function =
content::Source<ExtensionTestSendMessageFunction>(source).ptr();
EXPECT_GT(count_--, 0);
function->Reply(kSetInputMethodDone);
}
}
private:
content::NotificationRegistrar registrar_;
int count_;
};
} // namespace
IN_PROC_BROWSER_TEST_F(ExtensionApiTest, InputMethodApiBasic) {
// Two test, two calls. See JS code for more info.
SetInputMethodListener listener(2);
ASSERT_TRUE(RunExtensionTest("input_method")) << message_;
}
<|endoftext|> |
<commit_before>// $Id: options.C,v 1.13 2000/07/26 14:38:14 amoll Exp $
#include <BALL/DATATYPE/options.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <list>
#include <algorithm>
using namespace std;
using std::ofstream;
using std::ios;
namespace BALL
{
const Size Options::MAX_ENTRY_LENGTH = 1024;
Options::Options()
: StringHashMap<String>(),
name_("")
{
}
Options::Options(const Options& options, bool deep)
: StringHashMap<String>(options, deep),
name_(options.name_)
{
}
Options::~Options()
{
}
bool Options::isReal(const String& key) const
{
errno = 0;
char* endptr;
String value(get(key));
// an empty String is no real number
if (value =="")
{
return false;
}
// try to convert it to a number
strtod(value.c_str(), &endptr);
// return and tell whether it happend to work
return (errno == 0) && (endptr != value.c_str());
}
bool Options::isVector(const String& key) const
{
// if the key does not exist - then the nonexistent value
// cannot contain a vector
if (!has(key))
{
return false;
}
// try to interpret the string as three double values
double dummy;
if (sscanf(get(key).c_str(), "(%lf %lf %lf)", &dummy, &dummy, &dummy) == 3)
{
return true;
}
return false;
}
bool Options::isBool(const String& key) const
{
String s = get(key);
if (s == "")
return false;
s.toLower();
return (s.compare("true") == 0 || s.compare("false") == 0);
}
bool Options::isSet(const String& key) const
{
return (StringHashMap<String>::find(key) != StringHashMap<String>::end());
}
bool Options::isInteger(const String& key) const
{
double double_value;
long long_value;
// if it cannot be read as a floating point number
// it cannot be an integer
if (!isReal(key))
return false;
// check wheter it is an integer
long_value = atol(get(key).c_str());
double_value = atof(get(key).c_str());
// check if it is an integer (cutoff is 1e-7)
if (fabs(double_value - ((double)long_value)) <= 1e-7)
return true;
// it is a floating point number, but no integer
return false;
}
double Options::getReal(const String& key) const
{
double value;
errno = 0;
value = atof((*find(key)).second.c_str());
if (errno == 0){
return value;
} else {
return 0.0;
}
}
Vector3 Options::getVector(const String& key) const
{
Vector3 h(0,0,0);
if (!has(key))
{
return h;
}
// use temporary variables of double precision
// this avoids trouble if the definition of
// Vector3 is changed between TVector3<float> and TVector3<double>
double x, y, z;
// try to interpret the option as a vector
sscanf(get(key).c_str(), "(%lf %lf %lf)", &x, &y, &z);
h.x = x;
h.y = y;
h.z = z;
return h;
}
bool Options::getBool(const String& key) const
{
ConstIterator it = find(key);
if ((it != end()) && (it->second == "true"))
{
return true;
} else {
return false;
}
}
long Options::getInteger(const String& key) const
{
long value;
errno = 0;
ConstIterator it = find(key);
if (it == end())
return 0;
value = atol((*it).second.c_str());
if (errno == 0)
{
return value;
} else {
errno = 0;
return 0;
}
}
void Options::set(const String& key, const String& value)
{
(*this)[key] = value;
}
void Options::setInteger(const String& key, const long value)
{
static char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "%ld", value);
set(key, &(buffer[0]));
}
void Options::setReal(const String& key, const double value)
{
char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "%f", value);
set(key, buffer);
}
void Options::setVector(const String& key, const Vector3& value)
{
char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "(%f %f %f)", value.x, value.y, value.z);
set(key, buffer);
}
void Options::setBool(const String& key, const bool value)
{
if (value)
{
set(key, "true");
} else {
set(key, "false");
}
}
String Options::setDefault(const String& key, const String& value)
{
if (!has(key))
{
set(key, value);
return key;
} else {
return get(key);
}
}
double Options::setDefaultReal(const String& key, const double value)
{
if (!has(key) || !isReal(key))
{
setReal(key, value);
return value;
} else {
return getReal(key);
}
}
bool Options::setDefaultBool(const String& key, const bool value)
{
if (!has(key) || !isBool(key))
{
setBool(key, value);
return value;
} else {
return getBool(key);
}
}
long Options::setDefaultInteger(const String& key, const long value)
{
if (!has(key) || !isInteger(key))
{
setInteger(key, value);
return value;
} else {
return getInteger(key);
}
}
void Options::setName(const String& name)
{
name_ = name;
}
const String& Options::getName() const
{
return name_;
}
String Options::get(const String& key) const
{
ConstIterator it = find(key);
if (it == end())
{
return "";
} else {
return (*it).second;
}
}
bool Options::readOptionFile(const String& filename)
{
ifstream infile;
infile.open(filename.c_str(), ios::in);
if (!infile)
{
return false;
}
char buffer[MAX_ENTRY_LENGTH + 1];
String s, key;
while (infile.getline(buffer, MAX_ENTRY_LENGTH))
{
if ((buffer[0] != '#') && (buffer[0] != '!') && (buffer[0] != ';'))
{
s = buffer;
key = s.getField(0, " ");
s = s.after(" ");
set(key, s);
}
}
infile.close();
return true;
}
bool Options::writeOptionFile(const String& filename) const
{
std::list<String> entry_list;
String entry;
std::ofstream stream(filename.c_str());//, File::OUT);
if (!stream.is_open())
{
return false;
}
stream << "![OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;
StringHashMap<String>::ConstIterator it(begin());
for(; !(it == end()); ++it)
{
entry = (*it).first + ' ' + (*it).second;
entry_list.push_back(entry);
}
entry_list.sort();
std::list<String>::iterator list_it = entry_list.begin();
for (; list_it != entry_list.end(); ++list_it)
{
stream << *list_it << endl;
}
stream << "!-----------------------------------" << endl;
filename.close();
entry_list.clear();
return true;
}
void Options::dump (ostream& stream, Size /* depth */) const
{
std::list<String> entry_list;
String entry;
stream << "[OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;
StringHashMap<String>::ConstIterator it(begin());
for(; !(it == end()); ++it)
{
entry = (*it).first + ' ' + (*it).second;
entry_list.push_back(entry);
}
entry_list.sort();
std::list<String>::iterator list_it = entry_list.begin();
for (; list_it != entry_list.end(); ++list_it)
{
stream << *list_it << endl;
}
stream << "-----------------------------------" << endl;
entry_list.clear();
}
} // namespace BALL
<commit_msg>fixed: get***, exceptions were thrown from subfunctions, now testing in this functions if the key exists<commit_after>// $Id: options.C,v 1.14 2000/07/26 15:07:40 amoll Exp $
#include <BALL/DATATYPE/options.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <math.h>
#include <fstream>
#include <list>
#include <algorithm>
using namespace std;
using std::ofstream;
using std::ios;
namespace BALL
{
const Size Options::MAX_ENTRY_LENGTH = 1024;
Options::Options()
: StringHashMap<String>(),
name_("")
{
}
Options::Options(const Options& options, bool deep)
: StringHashMap<String>(options, deep),
name_(options.name_)
{
}
Options::~Options()
{
}
bool Options::isReal(const String& key) const
{
errno = 0;
char* endptr;
String value(get(key));
// an empty String is no real number
if (value =="")
{
return false;
}
// try to convert it to a number
strtod(value.c_str(), &endptr);
// return and tell whether it happend to work
return (errno == 0) && (endptr != value.c_str());
}
bool Options::isVector(const String& key) const
{
// if the key does not exist - then the nonexistent value
// cannot contain a vector
if (!has(key))
{
return false;
}
// try to interpret the string as three double values
double dummy;
if (sscanf(get(key).c_str(), "(%lf %lf %lf)", &dummy, &dummy, &dummy) == 3)
{
return true;
}
return false;
}
bool Options::isBool(const String& key) const
{
String s = get(key);
if (s == "")
return false;
s.toLower();
return (s.compare("true") == 0 || s.compare("false") == 0);
}
bool Options::isSet(const String& key) const
{
return (StringHashMap<String>::find(key) != StringHashMap<String>::end());
}
bool Options::isInteger(const String& key) const
{
double double_value;
long long_value;
// if it cannot be read as a floating point number
// it cannot be an integer
if (!isReal(key))
return false;
// check wheter it is an integer
long_value = atol(get(key).c_str());
double_value = atof(get(key).c_str());
// check if it is an integer (cutoff is 1e-7)
if (fabs(double_value - ((double)long_value)) <= 1e-7)
return true;
// it is a floating point number, but no integer
return false;
}
double Options::getReal(const String& key) const
{
if (!has(key))
{
return 0.0;
}
double value;
errno = 0;
value = atof((*find(key)).second.c_str());
if (errno == 0){
return value;
} else {
return 0.0;
}
}
Vector3 Options::getVector(const String& key) const
{
Vector3 h(0,0,0);
if (!has(key))
{
return h;
}
// use temporary variables of double precision
// this avoids trouble if the definition of
// Vector3 is changed between TVector3<float> and TVector3<double>
double x, y, z;
// try to interpret the option as a vector
sscanf(get(key).c_str(), "(%lf %lf %lf)", &x, &y, &z);
h.x = x;
h.y = y;
h.z = z;
return h;
}
bool Options::getBool(const String& key) const
{
if (!has(key))
{
return false;
}
ConstIterator it = find(key);
if ((it != end()) && (it->second == "true"))
{
return true;
} else {
return false;
}
}
long Options::getInteger(const String& key) const
{
if (!has(key))
{
return 0;
}
long value;
errno = 0;
ConstIterator it = find(key);
if (it == end())
{
return 0;
}
value = atol((*it).second.c_str());
if (errno == 0)
{
return value;
} else {
errno = 0;
return 0;
}
}
void Options::set(const String& key, const String& value)
{
(*this)[key] = value;
}
void Options::setInteger(const String& key, const long value)
{
static char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "%ld", value);
set(key, &(buffer[0]));
}
void Options::setReal(const String& key, const double value)
{
char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "%f", value);
set(key, buffer);
}
void Options::setVector(const String& key, const Vector3& value)
{
char buffer[MAX_ENTRY_LENGTH + 1];
sprintf(buffer, "(%f %f %f)", value.x, value.y, value.z);
set(key, buffer);
}
void Options::setBool(const String& key, const bool value)
{
if (value)
{
set(key, "true");
} else {
set(key, "false");
}
}
String Options::setDefault(const String& key, const String& value)
{
if (!has(key))
{
set(key, value);
return key;
} else {
return get(key);
}
}
double Options::setDefaultReal(const String& key, const double value)
{
if (!has(key) || !isReal(key))
{
setReal(key, value);
return value;
} else {
return getReal(key);
}
}
bool Options::setDefaultBool(const String& key, const bool value)
{
if (!has(key) || !isBool(key))
{
setBool(key, value);
return value;
} else {
return getBool(key);
}
}
long Options::setDefaultInteger(const String& key, const long value)
{
if (!has(key) || !isInteger(key))
{
setInteger(key, value);
return value;
} else {
return getInteger(key);
}
}
void Options::setName(const String& name)
{
name_ = name;
}
const String& Options::getName() const
{
return name_;
}
String Options::get(const String& key) const
{
if (!has(key))
{
return "";
}
ConstIterator it = find(key);
if (it == end())
{
return "";
} else {
return (*it).second;
}
}
bool Options::readOptionFile(const String& filename)
{
ifstream infile;
infile.open(filename.c_str(), ios::in);
if (!infile)
{
return false;
}
char buffer[MAX_ENTRY_LENGTH + 1];
String s, key;
while (infile.getline(buffer, MAX_ENTRY_LENGTH))
{
if ((buffer[0] != '#') && (buffer[0] != '!') && (buffer[0] != ';'))
{
s = buffer;
key = s.getField(0, " ");
s = s.after(" ");
set(key, s);
}
}
infile.close();
return true;
}
bool Options::writeOptionFile(const String& filename) const
{
std::list<String> entry_list;
String entry;
std::ofstream stream(filename.c_str());//, File::OUT);
if (!stream.is_open())
{
return false;
}
stream << "![OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;
StringHashMap<String>::ConstIterator it(begin());
for(; !(it == end()); ++it)
{
entry = (*it).first + ' ' + (*it).second;
entry_list.push_back(entry);
}
entry_list.sort();
std::list<String>::iterator list_it = entry_list.begin();
for (; list_it != entry_list.end(); ++list_it)
{
stream << *list_it << endl;
}
stream << "!-----------------------------------" << endl;
stream.close();
entry_list.clear();
return true;
}
void Options::dump (ostream& stream, Size /* depth */) const
{
std::list<String> entry_list;
String entry;
stream << "[OptionsTable: " << getName() << " (" << size() << " entries)]" << endl;
StringHashMap<String>::ConstIterator it(begin());
for(; !(it == end()); ++it)
{
entry = (*it).first + ' ' + (*it).second;
entry_list.push_back(entry);
}
entry_list.sort();
std::list<String>::iterator list_it = entry_list.begin();
for (; list_it != entry_list.end(); ++list_it)
{
stream << *list_it << endl;
}
stream << "-----------------------------------" << endl;
entry_list.clear();
}
} // namespace BALL
<|endoftext|> |
<commit_before>#ifndef _ENTITY_KEYBIND_HPP_
#define _ENTITY_KEYBIND_HPP_
// ------------------------------------------------------------------------------------------------
#include "Entity.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* ...
*/
class CKeybind : public Reference< CKeybind >
{
public:
// --------------------------------------------------------------------------------------------
using RefType::Reference;
/* --------------------------------------------------------------------------------------------
*
*/
SQInt32 GetPrimary() const noexcept;
/* --------------------------------------------------------------------------------------------
*
*/
SQInt32 GetSecondary() const noexcept;
/* --------------------------------------------------------------------------------------------
*
*/
SQInt32 GetAlternative() const noexcept;
/* --------------------------------------------------------------------------------------------
*
*/
bool IsRelease() const noexcept;
};
} // Namespace:: SqMod
#endif // _ENTITY_KEYBIND_HPP_<commit_msg>Documented the Keybind type.<commit_after>#ifndef _ENTITY_KEYBIND_HPP_
#define _ENTITY_KEYBIND_HPP_
// ------------------------------------------------------------------------------------------------
#include "Entity.hpp"
// ------------------------------------------------------------------------------------------------
namespace SqMod {
/* ------------------------------------------------------------------------------------------------
* Class responsible for managing the referenced keybind instance.
*/
class CKeybind : public Reference< CKeybind >
{
public:
// --------------------------------------------------------------------------------------------
using RefType::Reference;
/* --------------------------------------------------------------------------------------------
* Retrieve the primary key code of the referenced keybind instance.
*/
SQInt32 GetPrimary() const noexcept;
/* --------------------------------------------------------------------------------------------
* Retrieve the secondary key code of the referenced keybind instance.
*/
SQInt32 GetSecondary() const noexcept;
/* --------------------------------------------------------------------------------------------
* Retrieve the alternative key code of the referenced keybind instance.
*/
SQInt32 GetAlternative() const noexcept;
/* --------------------------------------------------------------------------------------------
* See whether the referenced keybind instance reacts to key press events.
*/
bool IsRelease() const noexcept;
};
} // Namespace:: SqMod
#endif // _ENTITY_KEYBIND_HPP_<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium 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 "chrome/browser/extensions/extension_file_util.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace keys = extension_manifest_keys;
TEST(ExtensionFileUtil, MoveDirSafely) {
// Create a test directory structure with some data in it.
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("src");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "foobar";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"),
data.c_str(), data.length()));
// Move it to a path that doesn't exist yet.
FilePath dest_path = temp.path().AppendASCII("dest").AppendASCII("dest");
ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));
// The path should get created.
ASSERT_TRUE(file_util::DirectoryExists(dest_path));
// The data should match.
std::string data_out;
ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"),
&data_out));
ASSERT_EQ(data, data_out);
// The src path should be gone.
ASSERT_FALSE(file_util::PathExists(src_path));
// Create some new test data.
ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path,
true)); // recursive
data = "hotdog";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"),
data.c_str(), data.length()));
// Test again, overwriting the old path.
ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));
ASSERT_TRUE(file_util::DirectoryExists(dest_path));
data_out.clear();
ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"),
&data_out));
ASSERT_EQ(data, data_out);
ASSERT_FALSE(file_util::PathExists(src_path));
}
TEST(ExtensionFileUtil, CompareToInstalledVersion) {
// Compare to an existing extension.
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions");
const std::string kId = "behllobkkfkfnphdnhnkndlbkcpglgmj";
const std::string kCurrentVersion = "1.0.0.0";
FilePath version_dir;
ASSERT_EQ(Extension::UPGRADE,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0.1", &version_dir));
ASSERT_EQ(Extension::REINSTALL,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0.0", &version_dir));
ASSERT_EQ(Extension::REINSTALL,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0", &version_dir));
ASSERT_EQ(Extension::DOWNGRADE,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "0.0.1.0", &version_dir));
// Compare to an extension that is missing its manifest file.
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion);
FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion);
ASSERT_TRUE(file_util::CreateDirectory(dest.DirName()));
ASSERT_TRUE(file_util::CopyDirectory(src, dest, true));
ASSERT_TRUE(file_util::Delete(dest.AppendASCII("manifest.json"), false));
ASSERT_EQ(Extension::NEW_INSTALL,
extension_file_util::CompareToInstalledVersion(
temp.path(), kId, kCurrentVersion, "1.0.0", &version_dir));
// Compare to a non-existent extension.
const std::string kMissingVersion = "";
const std::string kBadId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
ASSERT_EQ(Extension::NEW_INSTALL,
extension_file_util::CompareToInstalledVersion(
temp.path(), kBadId, kMissingVersion, "1.0.0", &version_dir));
}
TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension != NULL);
EXPECT_EQ("The first extension that I made.", extension->description());
}
TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_FALSE(extension == NULL);
EXPECT_TRUE(error.empty());
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
data.c_str(), data.length()));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
src_path = temp.path().AppendASCII("_some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("dddddddddddddddddddddddddddddddd")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest is not valid JSON. "
"Line: 2, column: 16, Syntax error.", error.c_str());
}
TEST(ExtensionFileUtil, MissingPrivacyBlacklist) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("privacy_blacklists")
.AppendASCII("missing_blacklist");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
EXPECT_TRUE(MatchPatternASCII(error,
"Could not load '*privacy_blacklist.pbl' for privacy blacklist: "
"file does not exist.")) << error;
}
TEST(ExtensionFileUtil, InvalidPrivacyBlacklist) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("privacy_blacklists")
.AppendASCII("invalid_blacklist");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
EXPECT_TRUE(MatchPatternASCII(error,
"Could not load '*privacy_blacklist.pbl' for privacy blacklist: "
"Incorrect header.")) << error;
}
// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionsService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
<commit_msg>add unit test for ExtensionURLToRelativeFilePath<commit_after>// Copyright (c) 2009 The Chromium 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 "chrome/browser/extensions/extension_file_util.h"
#include "base/file_util.h"
#include "base/scoped_temp_dir.h"
#include "base/string_util.h"
#include "base/path_service.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/extensions/extension_constants.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace keys = extension_manifest_keys;
TEST(ExtensionFileUtil, MoveDirSafely) {
// Create a test directory structure with some data in it.
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("src");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "foobar";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"),
data.c_str(), data.length()));
// Move it to a path that doesn't exist yet.
FilePath dest_path = temp.path().AppendASCII("dest").AppendASCII("dest");
ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));
// The path should get created.
ASSERT_TRUE(file_util::DirectoryExists(dest_path));
// The data should match.
std::string data_out;
ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"),
&data_out));
ASSERT_EQ(data, data_out);
// The src path should be gone.
ASSERT_FALSE(file_util::PathExists(src_path));
// Create some new test data.
ASSERT_TRUE(file_util::CopyDirectory(dest_path, src_path,
true)); // recursive
data = "hotdog";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("data"),
data.c_str(), data.length()));
// Test again, overwriting the old path.
ASSERT_TRUE(extension_file_util::MoveDirSafely(src_path, dest_path));
ASSERT_TRUE(file_util::DirectoryExists(dest_path));
data_out.clear();
ASSERT_TRUE(file_util::ReadFileToString(dest_path.AppendASCII("data"),
&data_out));
ASSERT_EQ(data, data_out);
ASSERT_FALSE(file_util::PathExists(src_path));
}
TEST(ExtensionFileUtil, CompareToInstalledVersion) {
// Compare to an existing extension.
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions");
const std::string kId = "behllobkkfkfnphdnhnkndlbkcpglgmj";
const std::string kCurrentVersion = "1.0.0.0";
FilePath version_dir;
ASSERT_EQ(Extension::UPGRADE,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0.1", &version_dir));
ASSERT_EQ(Extension::REINSTALL,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0.0", &version_dir));
ASSERT_EQ(Extension::REINSTALL,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "1.0.0", &version_dir));
ASSERT_EQ(Extension::DOWNGRADE,
extension_file_util::CompareToInstalledVersion(
install_dir, kId, kCurrentVersion, "0.0.1.0", &version_dir));
// Compare to an extension that is missing its manifest file.
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src = install_dir.AppendASCII(kId).AppendASCII(kCurrentVersion);
FilePath dest = temp.path().AppendASCII(kId).AppendASCII(kCurrentVersion);
ASSERT_TRUE(file_util::CreateDirectory(dest.DirName()));
ASSERT_TRUE(file_util::CopyDirectory(src, dest, true));
ASSERT_TRUE(file_util::Delete(dest.AppendASCII("manifest.json"), false));
ASSERT_EQ(Extension::NEW_INSTALL,
extension_file_util::CompareToInstalledVersion(
temp.path(), kId, kCurrentVersion, "1.0.0", &version_dir));
// Compare to a non-existent extension.
const std::string kMissingVersion = "";
const std::string kBadId = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
ASSERT_EQ(Extension::NEW_INSTALL,
extension_file_util::CompareToInstalledVersion(
temp.path(), kBadId, kMissingVersion, "1.0.0", &version_dir));
}
TEST(ExtensionFileUtil, LoadExtensionWithValidLocales) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("behllobkkfkfnphdnhnkndlbkcpglgmj")
.AppendASCII("1.0.0.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension != NULL);
EXPECT_EQ("The first extension that I made.", extension->description());
}
TEST(ExtensionFileUtil, LoadExtensionWithoutLocalesFolder) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("good")
.AppendASCII("Extensions")
.AppendASCII("bjafgdebaacbbbecmhlhpofkepfkgcpa")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_FALSE(extension == NULL);
EXPECT_TRUE(error.empty());
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesNoUnderscores) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().AppendASCII("some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string data = "{ \"name\": { \"message\": \"foobar\" } }";
ASSERT_TRUE(file_util::WriteFile(src_path.AppendASCII("some_file.txt"),
data.c_str(), data.length()));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesOnlyReserved) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_TRUE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, CheckIllegalFilenamesReservedAndIllegal) {
ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
FilePath src_path = temp.path().Append(Extension::kLocaleFolder);
ASSERT_TRUE(file_util::CreateDirectory(src_path));
src_path = temp.path().AppendASCII("_some_dir");
ASSERT_TRUE(file_util::CreateDirectory(src_path));
std::string error;
EXPECT_FALSE(extension_file_util::CheckForIllegalFilenames(temp.path(),
&error));
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnMissingManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("dddddddddddddddddddddddddddddddd")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest file is missing or unreadable.", error.c_str());
}
TEST(ExtensionFileUtil, LoadExtensionGivesHelpfullErrorOnBadManifest) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("bad")
.AppendASCII("Extensions")
.AppendASCII("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee")
.AppendASCII("1.0");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
ASSERT_STREQ("Manifest is not valid JSON. "
"Line: 2, column: 16, Syntax error.", error.c_str());
}
TEST(ExtensionFileUtil, MissingPrivacyBlacklist) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("privacy_blacklists")
.AppendASCII("missing_blacklist");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
EXPECT_TRUE(MatchPatternASCII(error,
"Could not load '*privacy_blacklist.pbl' for privacy blacklist: "
"file does not exist.")) << error;
}
TEST(ExtensionFileUtil, InvalidPrivacyBlacklist) {
FilePath install_dir;
ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &install_dir));
install_dir = install_dir.AppendASCII("extensions")
.AppendASCII("privacy_blacklists")
.AppendASCII("invalid_blacklist");
std::string error;
scoped_ptr<Extension> extension(
extension_file_util::LoadExtension(install_dir, false, &error));
ASSERT_TRUE(extension == NULL);
ASSERT_FALSE(error.empty());
EXPECT_TRUE(MatchPatternASCII(error,
"Could not load '*privacy_blacklist.pbl' for privacy blacklist: "
"Incorrect header.")) << error;
}
#define URL_PREFIX "chrome-extension://extension-id/"
TEST(ExtensionFileUtil, ExtensionURLToRelativeFilePath) {
struct TestCase {
const char* url;
const char* expected_relative_path;
} test_cases[] = {
{ URL_PREFIX "simple.html",
"simple.html" },
{ URL_PREFIX "directory/to/file.html",
"directory/to/file.html" },
{ URL_PREFIX "escape%20spaces.html",
"escape spaces.html" },
{ URL_PREFIX "%C3%9Cber.html",
"\xC3\x9C" "ber.html" },
};
for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
GURL url(test_cases[i].url);
#if defined(OS_POSIX)
FilePath expected_path(test_cases[i].expected_relative_path);
#elif defined(OS_WIN)
FilePath expected_path(UTF8ToWide(test_cases[i].expected_relative_path));
#endif
FilePath actual_path =
extension_file_util::ExtensionURLToRelativeFilePath(url);
EXPECT_FALSE(actual_path.IsAbsolute()) <<
" For the path " << actual_path.value();
EXPECT_EQ(expected_path.value(), actual_path.value());
}
}
// TODO(aa): More tests as motivation allows. Maybe steal some from
// ExtensionsService? Many of them could probably be tested here without the
// MessageLoop shenanigans.
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSphereSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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.
=========================================================================*/
#include <math.h>
#include "vtkSphereSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkGhostLevels.h"
//------------------------------------------------------------------------------
vtkSphereSource* vtkSphereSource::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSphereSource");
if(ret)
{
return (vtkSphereSource*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkSphereSource;
}
//----------------------------------------------------------------------------
// Construct sphere with radius=0.5 and default resolution 8 in both Phi
// and Theta directions. Theta ranges from (0,360) and phi (0,180) degrees.
vtkSphereSource::vtkSphereSource(int res)
{
res = res < 4 ? 4 : res;
this->Radius = 0.5;
this->Center[0] = 0.0;
this->Center[1] = 0.0;
this->Center[2] = 0.0;
this->ThetaResolution = res;
this->PhiResolution = res;
this->StartTheta = 0.0;
this->EndTheta = 360.0;
this->StartPhi = 0.0;
this->EndPhi = 180.0;
}
//----------------------------------------------------------------------------
void vtkSphereSource::Execute()
{
int i, j;
int jStart, jEnd, numOffset;
int numPts, numPolys;
vtkPoints *newPoints;
vtkNormals *newNormals;
vtkGhostLevels *newGhostPoints = NULL;
vtkCellArray *newPolys;
float x[3], n[3], deltaPhi, deltaTheta, phi, theta, radius, norm;
float startTheta, endTheta, startPhi, endPhi;
int pts[3], base, numPoles=0, thetaResolution, phiResolution;
vtkPolyData *output = this->GetOutput();
int piece = output->GetUpdatePiece();
int numPieces = output->GetUpdateNumberOfPieces();
int ghostLevel = output->GetUpdateGhostLevel();
// I want to modify the ivars resoultion start theta and end theta,
// so I will make local copies of them. THese might be able to be merged
// with the other copies of them, ...
int localThetaResolution = this->ThetaResolution;
float localStartTheta = this->StartTheta;
float localEndTheta = this->EndTheta;
while (localEndTheta < localStartTheta)
{
localEndTheta += 360.0;
}
deltaTheta = (localEndTheta - localStartTheta) / localThetaResolution;
// Change the ivars based on pieces.
int start, end;
start = piece * localThetaResolution / numPieces;
end = (piece+1) * localThetaResolution / numPieces;
localEndTheta = localStartTheta + (float)(end) * deltaTheta;
localStartTheta = localStartTheta + (float)(start) * deltaTheta;
localThetaResolution = end - start;
//
// Set things up; allocate memory
//
vtkDebugMacro("SphereSource Executing");
numPts = this->PhiResolution * localThetaResolution + 2;
// creating triangles
numPolys = this->PhiResolution * 2 * localThetaResolution;
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numPts);
if (numPieces > 1)
{
newGhostPoints = vtkGhostLevels::New();
newGhostPoints->Allocate(numPts);
}
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys, 3));
//
// Create sphere
//
// Create north pole if needed
if ( this->StartPhi <= 0.0 )
{
x[0] = this->Center[0];
x[1] = this->Center[1];
x[2] = this->Center[2] + this->Radius;
newPoints->InsertPoint(numPoles,x);
x[0] = x[1] = 0.0; x[2] = 1.0;
newNormals->InsertNormal(numPoles,x);
if (newGhostPoints)
{
if (piece == 0)
{
newGhostPoints->InsertGhostLevel(numPoles, 0);
}
else
{
newGhostPoints->InsertGhostLevel(numPoles, 1);
}
}
numPoles++;
}
// Create south pole if needed
if ( this->EndPhi >= 180.0 )
{
x[0] = this->Center[0];
x[1] = this->Center[1];
x[2] = this->Center[2] - this->Radius;
newPoints->InsertPoint(numPoles,x);
x[0] = x[1] = 0.0; x[2] = -1.0;
newNormals->InsertNormal(numPoles,x);
if (newGhostPoints)
{
if (piece == 0)
{
newGhostPoints->InsertGhostLevel(numPoles, 0);
}
else
{
newGhostPoints->InsertGhostLevel(numPoles, 1);
}
}
numPoles++;
}
// Check data, determine increments, and convert to radians
startTheta = (localStartTheta < localEndTheta ? localStartTheta : localEndTheta);
startTheta *= vtkMath::Pi() / 180.0;
endTheta = (localEndTheta > localStartTheta ? localEndTheta : localStartTheta);
endTheta *= vtkMath::Pi() / 180.0;
startPhi = (this->StartPhi < this->EndPhi ? this->StartPhi : this->EndPhi);
startPhi *= vtkMath::Pi() / 180.0;
endPhi = (this->EndPhi > this->StartPhi ? this->EndPhi : this->StartPhi);
endPhi *= vtkMath::Pi() / 180.0;
phiResolution = this->PhiResolution - numPoles;
deltaPhi = (endPhi - startPhi) / (this->PhiResolution - 1);
thetaResolution = localThetaResolution;
if (fabs(localStartTheta - localEndTheta) < 360.0)
{
++localThetaResolution;
}
deltaTheta = (endTheta - startTheta) / thetaResolution;
jStart = (this->StartPhi <= 0.0 ? 1 : 0);
jEnd = (this->EndPhi >= 180.0 ? this->PhiResolution - 1
: this->PhiResolution);
// Create intermediate points
for (i=0; i < localThetaResolution; i++)
{
theta = localStartTheta * vtkMath::Pi() / 180.0 + i*deltaTheta;
for (j=jStart; j<jEnd; j++)
{
phi = startPhi + j*deltaPhi;
radius = this->Radius * sin((double)phi);
n[0] = radius * cos((double)theta);
n[1] = radius * sin((double)theta);
n[2] = this->Radius * cos((double)phi);
x[0] = n[0] + this->Center[0];
x[1] = n[1] + this->Center[1];
x[2] = n[2] + this->Center[2];
newPoints->InsertNextPoint(x);
if ( (norm = vtkMath::Norm(n)) == 0.0 )
{
norm = 1.0;
}
n[0] /= norm; n[1] /= norm; n[2] /= norm;
newNormals->InsertNextNormal(n);
if (newGhostPoints)
{
if (i < ghostLevel + 1)
{
newGhostPoints->InsertNextGhostLevel(ghostLevel - i + 1);
}
else if (i >= localThetaResolution - ghostLevel)
{
newGhostPoints->InsertNextGhostLevel(i - localThetaResolution +
ghostLevel + 1);
}
else
{
newGhostPoints->InsertNextGhostLevel(0);
}
}
}
}
// Generate mesh connectivity
base = phiResolution * localThetaResolution;
if (fabs(localStartTheta - localEndTheta) < 360.0)
{
--localThetaResolution;
}
if ( this->StartPhi <= 0.0 ) // around north pole
{
for (i=0; i < localThetaResolution; i++)
{
pts[0] = phiResolution*i + numPoles;
pts[1] = (phiResolution*(i+1) % base) + numPoles;
pts[2] = 0;
newPolys->InsertNextCell(3, pts);
}
}
if ( this->EndPhi >= 180.0 ) // around south pole
{
numOffset = phiResolution - 1 + numPoles;
for (i=0; i < localThetaResolution; i++)
{
pts[0] = phiResolution*i + numOffset;
pts[2] = ((phiResolution*(i+1)) % base) + numOffset;
pts[1] = numPoles - 1;
newPolys->InsertNextCell(3, pts);
}
}
// bands in-between poles
for (i=0; i < localThetaResolution; i++)
{
for (j=0; j < (phiResolution-1); j++)
{
pts[0] = phiResolution*i + j + numPoles;
pts[1] = pts[0] + 1;
pts[2] = ((phiResolution*(i+1)+j) % base) + numPoles + 1;
newPolys->InsertNextCell(3, pts);
pts[1] = pts[2];
pts[2] = pts[1] - 1;
newPolys->InsertNextCell(3, pts);
}
}
//
// Update ourselves and release memeory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
if (newGhostPoints)
{
output->GetPointData()->SetGhostLevels(newGhostPoints);
newGhostPoints->Delete();
}
output->SetPolys(newPolys);
newPolys->Delete();
}
//----------------------------------------------------------------------------
void vtkSphereSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataSource::PrintSelf(os,indent);
os << indent << "Theta Resolution: " << this->ThetaResolution << "\n";
os << indent << "Phi Resolution: " << this->PhiResolution << "\n";
os << indent << "Theta Start: " << this->StartTheta << "\n";
os << indent << "Phi Start: " << this->StartPhi << "\n";
os << indent << "Theta End: " << this->EndTheta << "\n";
os << indent << "Phi End: " << this->EndPhi << "\n";
os << indent << "Radius: " << this->Radius << "\n";
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", " << this->Center[2] << ")\n";
}
//----------------------------------------------------------------------------
void vtkSphereSource::ExecuteInformation()
{
int numTris, numPts;
unsigned long size;
// ignore poles
numPts = this->ThetaResolution * (this->PhiResolution + 1);
numTris = this->ThetaResolution * this->PhiResolution * 2;
size = numPts * 3 * sizeof(float);
size += numTris * 4 * sizeof(int);
// convert to kilobytes
size = (size / 1000) + 1;
this->GetOutput()->SetMaximumNumberOfPieces(this->ThetaResolution);
}
<commit_msg>Added warning: cannot generate ghost cells.<commit_after>/*=========================================================================
Program: Visualization Toolkit
Module: vtkSphereSource.cxx
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) 1993-2000 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 REGENTS 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.
=========================================================================*/
#include <math.h>
#include "vtkSphereSource.h"
#include "vtkPoints.h"
#include "vtkNormals.h"
#include "vtkMath.h"
#include "vtkObjectFactory.h"
#include "vtkGhostLevels.h"
//------------------------------------------------------------------------------
vtkSphereSource* vtkSphereSource::New()
{
// First try to create the object from the vtkObjectFactory
vtkObject* ret = vtkObjectFactory::CreateInstance("vtkSphereSource");
if(ret)
{
return (vtkSphereSource*)ret;
}
// If the factory was unable to create the object, then create it here.
return new vtkSphereSource;
}
//----------------------------------------------------------------------------
// Construct sphere with radius=0.5 and default resolution 8 in both Phi
// and Theta directions. Theta ranges from (0,360) and phi (0,180) degrees.
vtkSphereSource::vtkSphereSource(int res)
{
res = res < 4 ? 4 : res;
this->Radius = 0.5;
this->Center[0] = 0.0;
this->Center[1] = 0.0;
this->Center[2] = 0.0;
this->ThetaResolution = res;
this->PhiResolution = res;
this->StartTheta = 0.0;
this->EndTheta = 360.0;
this->StartPhi = 0.0;
this->EndPhi = 180.0;
}
//----------------------------------------------------------------------------
void vtkSphereSource::Execute()
{
int i, j;
int jStart, jEnd, numOffset;
int numPts, numPolys;
vtkPoints *newPoints;
vtkNormals *newNormals;
vtkGhostLevels *newGhostPoints = NULL;
vtkCellArray *newPolys;
float x[3], n[3], deltaPhi, deltaTheta, phi, theta, radius, norm;
float startTheta, endTheta, startPhi, endPhi;
int pts[3], base, numPoles=0, thetaResolution, phiResolution;
vtkPolyData *output = this->GetOutput();
int piece = output->GetUpdatePiece();
int numPieces = output->GetUpdateNumberOfPieces();
int ghostLevel = output->GetUpdateGhostLevel();
if (ghostLevel > 0)
{
vtkWarningMacro("vtkSphereSource does not generate ghost cells.");
ghostLevel = 0;
}
// I want to modify the ivars resoultion start theta and end theta,
// so I will make local copies of them. THese might be able to be merged
// with the other copies of them, ...
int localThetaResolution = this->ThetaResolution;
float localStartTheta = this->StartTheta;
float localEndTheta = this->EndTheta;
while (localEndTheta < localStartTheta)
{
localEndTheta += 360.0;
}
deltaTheta = (localEndTheta - localStartTheta) / localThetaResolution;
// Change the ivars based on pieces.
int start, end;
start = piece * localThetaResolution / numPieces;
end = (piece+1) * localThetaResolution / numPieces;
localEndTheta = localStartTheta + (float)(end) * deltaTheta;
localStartTheta = localStartTheta + (float)(start) * deltaTheta;
localThetaResolution = end - start;
//
// Set things up; allocate memory
//
vtkDebugMacro("SphereSource Executing");
numPts = this->PhiResolution * localThetaResolution + 2;
// creating triangles
numPolys = this->PhiResolution * 2 * localThetaResolution;
newPoints = vtkPoints::New();
newPoints->Allocate(numPts);
newNormals = vtkNormals::New();
newNormals->Allocate(numPts);
if (numPieces > 1)
{
newGhostPoints = vtkGhostLevels::New();
newGhostPoints->Allocate(numPts);
}
newPolys = vtkCellArray::New();
newPolys->Allocate(newPolys->EstimateSize(numPolys, 3));
//
// Create sphere
//
// Create north pole if needed
if ( this->StartPhi <= 0.0 )
{
x[0] = this->Center[0];
x[1] = this->Center[1];
x[2] = this->Center[2] + this->Radius;
newPoints->InsertPoint(numPoles,x);
x[0] = x[1] = 0.0; x[2] = 1.0;
newNormals->InsertNormal(numPoles,x);
if (newGhostPoints)
{
if (piece == 0)
{
newGhostPoints->InsertGhostLevel(numPoles, 0);
}
else
{
newGhostPoints->InsertGhostLevel(numPoles, 1);
}
}
numPoles++;
}
// Create south pole if needed
if ( this->EndPhi >= 180.0 )
{
x[0] = this->Center[0];
x[1] = this->Center[1];
x[2] = this->Center[2] - this->Radius;
newPoints->InsertPoint(numPoles,x);
x[0] = x[1] = 0.0; x[2] = -1.0;
newNormals->InsertNormal(numPoles,x);
if (newGhostPoints)
{
if (piece == 0)
{
newGhostPoints->InsertGhostLevel(numPoles, 0);
}
else
{
newGhostPoints->InsertGhostLevel(numPoles, 1);
}
}
numPoles++;
}
// Check data, determine increments, and convert to radians
startTheta = (localStartTheta < localEndTheta ? localStartTheta : localEndTheta);
startTheta *= vtkMath::Pi() / 180.0;
endTheta = (localEndTheta > localStartTheta ? localEndTheta : localStartTheta);
endTheta *= vtkMath::Pi() / 180.0;
startPhi = (this->StartPhi < this->EndPhi ? this->StartPhi : this->EndPhi);
startPhi *= vtkMath::Pi() / 180.0;
endPhi = (this->EndPhi > this->StartPhi ? this->EndPhi : this->StartPhi);
endPhi *= vtkMath::Pi() / 180.0;
phiResolution = this->PhiResolution - numPoles;
deltaPhi = (endPhi - startPhi) / (this->PhiResolution - 1);
thetaResolution = localThetaResolution;
if (fabs(localStartTheta - localEndTheta) < 360.0)
{
++localThetaResolution;
}
deltaTheta = (endTheta - startTheta) / thetaResolution;
jStart = (this->StartPhi <= 0.0 ? 1 : 0);
jEnd = (this->EndPhi >= 180.0 ? this->PhiResolution - 1
: this->PhiResolution);
// Create intermediate points
for (i=0; i < localThetaResolution; i++)
{
theta = localStartTheta * vtkMath::Pi() / 180.0 + i*deltaTheta;
for (j=jStart; j<jEnd; j++)
{
phi = startPhi + j*deltaPhi;
radius = this->Radius * sin((double)phi);
n[0] = radius * cos((double)theta);
n[1] = radius * sin((double)theta);
n[2] = this->Radius * cos((double)phi);
x[0] = n[0] + this->Center[0];
x[1] = n[1] + this->Center[1];
x[2] = n[2] + this->Center[2];
newPoints->InsertNextPoint(x);
if ( (norm = vtkMath::Norm(n)) == 0.0 )
{
norm = 1.0;
}
n[0] /= norm; n[1] /= norm; n[2] /= norm;
newNormals->InsertNextNormal(n);
if (newGhostPoints)
{
if (i < ghostLevel + 1)
{
newGhostPoints->InsertNextGhostLevel(ghostLevel - i + 1);
}
else if (i >= localThetaResolution - ghostLevel)
{
newGhostPoints->InsertNextGhostLevel(i - localThetaResolution +
ghostLevel + 1);
}
else
{
newGhostPoints->InsertNextGhostLevel(0);
}
}
}
}
// Generate mesh connectivity
base = phiResolution * localThetaResolution;
if (fabs(localStartTheta - localEndTheta) < 360.0)
{
--localThetaResolution;
}
if ( this->StartPhi <= 0.0 ) // around north pole
{
for (i=0; i < localThetaResolution; i++)
{
pts[0] = phiResolution*i + numPoles;
pts[1] = (phiResolution*(i+1) % base) + numPoles;
pts[2] = 0;
newPolys->InsertNextCell(3, pts);
}
}
if ( this->EndPhi >= 180.0 ) // around south pole
{
numOffset = phiResolution - 1 + numPoles;
for (i=0; i < localThetaResolution; i++)
{
pts[0] = phiResolution*i + numOffset;
pts[2] = ((phiResolution*(i+1)) % base) + numOffset;
pts[1] = numPoles - 1;
newPolys->InsertNextCell(3, pts);
}
}
// bands in-between poles
for (i=0; i < localThetaResolution; i++)
{
for (j=0; j < (phiResolution-1); j++)
{
pts[0] = phiResolution*i + j + numPoles;
pts[1] = pts[0] + 1;
pts[2] = ((phiResolution*(i+1)+j) % base) + numPoles + 1;
newPolys->InsertNextCell(3, pts);
pts[1] = pts[2];
pts[2] = pts[1] - 1;
newPolys->InsertNextCell(3, pts);
}
}
//
// Update ourselves and release memeory
//
output->SetPoints(newPoints);
newPoints->Delete();
output->GetPointData()->SetNormals(newNormals);
newNormals->Delete();
if (newGhostPoints)
{
output->GetPointData()->SetGhostLevels(newGhostPoints);
newGhostPoints->Delete();
}
output->SetPolys(newPolys);
newPolys->Delete();
}
//----------------------------------------------------------------------------
void vtkSphereSource::PrintSelf(ostream& os, vtkIndent indent)
{
vtkPolyDataSource::PrintSelf(os,indent);
os << indent << "Theta Resolution: " << this->ThetaResolution << "\n";
os << indent << "Phi Resolution: " << this->PhiResolution << "\n";
os << indent << "Theta Start: " << this->StartTheta << "\n";
os << indent << "Phi Start: " << this->StartPhi << "\n";
os << indent << "Theta End: " << this->EndTheta << "\n";
os << indent << "Phi End: " << this->EndPhi << "\n";
os << indent << "Radius: " << this->Radius << "\n";
os << indent << "Center: (" << this->Center[0] << ", "
<< this->Center[1] << ", " << this->Center[2] << ")\n";
}
//----------------------------------------------------------------------------
void vtkSphereSource::ExecuteInformation()
{
int numTris, numPts;
unsigned long size;
// ignore poles
numPts = this->ThetaResolution * (this->PhiResolution + 1);
numTris = this->ThetaResolution * this->PhiResolution * 2;
size = numPts * 3 * sizeof(float);
size += numTris * 4 * sizeof(int);
// convert to kilobytes
size = (size / 1000) + 1;
this->GetOutput()->SetMaximumNumberOfPieces(this->ThetaResolution);
}
<|endoftext|> |
<commit_before>#pragma once
#include <list>
#include <cassert>
#include <unordered_map>
template <typename _Kty, typename _Ty>
class LRUCache
{
public:
using value_type = std::pair<const _Kty, _Ty>;
private:
int fixedCacheSize_;
std::list<value_type> values_;
public:
using value_iterator = decltype(values_.begin());
using mapping_type = std::unordered_map<_Kty, value_iterator>;
using mapping_iterator = typename mapping_type::iterator;
private:
mapping_type mapping_;
public:
LRUCache(const int cacheSize)
: fixedCacheSize_(cacheSize)
{
if (fixedCacheSize_ <= 0)
{
throw std::logic_error("LRUCache size must be greater than zero");
}
}
~LRUCache() = default;
LRUCache(const LRUCache&) = delete;
LRUCache& operator=(const LRUCache&) = delete;
LRUCache(LRUCache&&) = default;
LRUCache& operator=(LRUCache&&) = default;
// ---------
// Modifiers
// ---------
std::pair<value_iterator, bool> insert(const value_type& value)
{
// Trying to insert dummy value
auto result = mapping_.insert({ value.first, values_.end() });
if (result.second == false)
{
return std::make_pair(result.first->second, false);
}
// Replace by input value
values_.push_back(value);
result.first->second = --values_.end();
// Erase oldest value
if (values_.size() > fixedCacheSize_)
{
const auto& oldestValue = values_.front();
mapping_.erase(oldestValue.first);
values_.pop_front();
}
return std::make_pair(result.first->second, true);
}
bool erase(const _Kty& key)
{
const auto mappingIt = mapping_.find(key);
if (mappingIt != mapping_.end())
{
values_.erase(mappingIt->second);
mapping_.erase(mappingIt);
return true;
}
return false;
}
void clear() noexcept
{
values_.clear();
mapping_.clear();
}
// --------------
// Element access
// --------------
_Ty& operator[](const _Kty& key)
{
auto it = mapping_.find(key);
if (it != mapping_.cend())
{
return it->second->second;
}
auto result = insert({ key , _Ty{} });
return result.first->second;
}
_Ty& operator[](_Kty&& key)
{
auto it = mapping_.find(key);
if (it != mapping_.cend())
{
return it->second->second;
}
auto result = insert({ std::move(key), _Ty{} });
return result.first->second;
}
// --------
// Capacity
// --------
bool empty() const noexcept
{
return values_.empty();
}
size_t size() const noexcept
{
assert(values_.size() == mapping_.size());
return values_.size();
}
// --------------
// Element lookup
// --------------
std::pair<value_iterator, bool> find(const _Kty& key)
{
auto mappingIt = mapping_.find(key);
if (mappingIt != mapping_.end())
{
values_.splice(values_.end(), values_, mappingIt->second);
return std::make_pair(mappingIt->second, true);
}
return std::make_pair(values_.end(), false);
}
size_t count(const _Kty& key) const
{
return mapping_.count(key);
}
};
<commit_msg>Use size_t instead of int to store cache size<commit_after>#pragma once
#include <list>
#include <cassert>
#include <unordered_map>
template <typename _Kty, typename _Ty>
class LRUCache
{
public:
using value_type = std::pair<const _Kty, _Ty>;
private:
size_t cacheSize_;
std::list<value_type> values_;
public:
using value_iterator = decltype(values_.begin());
using mapping_type = std::unordered_map<_Kty, value_iterator>;
using mapping_iterator = typename mapping_type::iterator;
private:
mapping_type mapping_;
public:
LRUCache(const size_t cacheSize)
: cacheSize_(cacheSize)
{
if (cacheSize_ == 0)
{
throw std::logic_error("LRUCache size must be greater than zero");
}
}
~LRUCache() = default;
LRUCache(const LRUCache&) = delete;
LRUCache& operator=(const LRUCache&) = delete;
LRUCache(LRUCache&&) = default;
LRUCache& operator=(LRUCache&&) = default;
// ---------
// Modifiers
// ---------
std::pair<value_iterator, bool> insert(const value_type& value)
{
// Trying to insert dummy value
auto result = mapping_.insert({ value.first, values_.end() });
if (result.second == false)
{
return std::make_pair(result.first->second, false);
}
// Replace by input value
values_.push_back(value);
result.first->second = --values_.end();
// Erase oldest value
if (values_.size() > cacheSize_)
{
const auto& oldestValue = values_.front();
mapping_.erase(oldestValue.first);
values_.pop_front();
}
return std::make_pair(result.first->second, true);
}
bool erase(const _Kty& key)
{
const auto mappingIt = mapping_.find(key);
if (mappingIt != mapping_.end())
{
values_.erase(mappingIt->second);
mapping_.erase(mappingIt);
return true;
}
return false;
}
void clear() noexcept
{
values_.clear();
mapping_.clear();
}
// --------------
// Element access
// --------------
_Ty& operator[](const _Kty& key)
{
auto it = mapping_.find(key);
if (it != mapping_.cend())
{
return it->second->second;
}
auto result = insert({ key , _Ty{} });
return result.first->second;
}
_Ty& operator[](_Kty&& key)
{
auto it = mapping_.find(key);
if (it != mapping_.cend())
{
return it->second->second;
}
auto result = insert({ std::move(key), _Ty{} });
return result.first->second;
}
// --------
// Capacity
// --------
bool empty() const noexcept
{
return values_.empty();
}
size_t size() const noexcept
{
assert(values_.size() == mapping_.size());
return values_.size();
}
// --------------
// Element lookup
// --------------
std::pair<value_iterator, bool> find(const _Kty& key)
{
auto mappingIt = mapping_.find(key);
if (mappingIt != mapping_.end())
{
values_.splice(values_.end(), values_, mappingIt->second);
return std::make_pair(mappingIt->second, true);
}
return std::make_pair(values_.end(), false);
}
size_t count(const _Kty& key) const
{
return mapping_.count(key);
}
};
<|endoftext|> |
<commit_before>#ifndef DISPLAY_H
#include "mbed.h"
class Display {
public:
static Display *getInstance();
static const int height = 8;
static const int width = 16;
void set(int row, int col);
void clear(int row, int col);
void swapBuffer();
private:
Display();
~Display();
void resetBuffer(bool buffer[height][width]);
void shiftRow();
int generateShiftRegisterCode(int row);
void sendShiftRegisterCode(int code);
static Display *mInstance;
DigitalOut *sig;
DigitalOut *sclk;
DigitalOut *rclk;
Ticker ticker;
int surfaceBuffer;
int backBuffer;
bool buffers[2][height][width];
};
#endif
<commit_msg>ヘッダファイルのインクルードガードの修正<commit_after>#ifndef DISPLAY_H
#define DISPLAY_H
#include "mbed.h"
class Display {
public:
static Display *getInstance();
static const int height = 8;
static const int width = 16;
void set(int row, int col);
void clear(int row, int col);
void swapBuffer();
private:
Display();
~Display();
void resetBuffer(bool buffer[height][width]);
void shiftRow();
int generateShiftRegisterCode(int row);
void sendShiftRegisterCode(int code);
static Display *mInstance;
DigitalOut *sig;
DigitalOut *sclk;
DigitalOut *rclk;
Ticker ticker;
int surfaceBuffer;
int backBuffer;
bool buffers[2][height][width];
};
#endif /* end of include guard: DISPLAY_H */
<|endoftext|> |
<commit_before>// SPDX-License-Identifier: MIT
/**
Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
*/
#include "AdsLib.h"
#include "Log.h"
#include "wrap_endian.h"
#include <cstring>
namespace bhf
{
namespace ads
{
static bool PrependUdpLenTagId(Frame& frame, const uint16_t length, const uint16_t tagId)
{
frame.prepend(htole(length));
frame.prepend(htole(tagId));
return true;
}
static bool PrependUdpTag(Frame& frame, const std::string& value, const uint16_t tagId)
{
const uint16_t length = value.length() + 1;
frame.prepend(value.data(), length);
return PrependUdpLenTagId(frame, length, tagId);
}
static bool PrependUdpTag(Frame& frame, const AmsNetId& value, const uint16_t tagId)
{
const uint16_t length = sizeof(value);
frame.prepend(&value, length);
return PrependUdpLenTagId(frame, length, tagId);
}
enum UdpTag : uint16_t {
PASSWORD = 2,
COMPUTERNAME = 5,
NETID = 7,
ROUTENAME = 12,
USERNAME = 13,
};
enum UdpServiceId : uint32_t {
SERVERINFO = 1,
ADDROUTE = 6,
RESPONSE = 0x80000000,
};
static long SendRecv(const std::string& remote, Frame& f, const uint32_t serviceId)
{
f.prepend(htole(serviceId));
static const uint32_t invokeId = 0;
f.prepend(htole(invokeId));
static const uint32_t UDP_COOKIE = 0x71146603;
f.prepend(htole(UDP_COOKIE));
const auto addresses = GetListOfAddresses(remote, "48899");
UdpSocket s{addresses.get()};
s.write(f);
f.reset();
static constexpr auto headerLength = sizeof(serviceId) + sizeof(invokeId) + sizeof(UDP_COOKIE);
timeval timeout { 5, 0 };
s.read(f, &timeout);
if (headerLength > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
const auto cookie = f.pop_letoh<uint32_t>();
if (UDP_COOKIE != cookie) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid cookie '" << cookie << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
const auto invoke = f.pop_letoh<uint32_t>();
if (invokeId != invoke) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid invokeId '" << invoke << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
const auto service = f.pop_letoh<uint32_t>();
if ((UdpServiceId::RESPONSE | serviceId) != service) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid serviceId '" << std::hex << service << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
return 0;
}
long AddRemoteRoute(const std::string& remote,
AmsNetId destNetId,
const std::string& destAddr,
const std::string& routeName,
const std::string& remoteUsername,
const std::string& remotePassword)
{
Frame f { 256 };
uint32_t tagCount = 0;
tagCount += PrependUdpTag(f, destAddr, UdpTag::COMPUTERNAME);
tagCount += PrependUdpTag(f, remotePassword, UdpTag::PASSWORD);
tagCount += PrependUdpTag(f, remoteUsername, UdpTag::USERNAME);
tagCount += PrependUdpTag(f, destNetId, UdpTag::NETID);
tagCount += PrependUdpTag(f, routeName.empty() ? destAddr : routeName, UdpTag::ROUTENAME);
f.prepend(htole(tagCount));
const auto myAddr = AmsAddr { destNetId, 0 };
f.prepend(&myAddr, sizeof(myAddr));
const auto status = SendRecv(remote, f, UdpServiceId::ADDROUTE);
if (status) {
return status;
}
// We expect at least the AmsAddr and count fields
if (sizeof(AmsAddr) + sizeof(uint32_t) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
// ignore AmsAddr in response
f.remove(sizeof(AmsAddr));
// process UDP discovery tags
auto count = f.pop_letoh<uint32_t>();
while (count--) {
uint16_t tag;
uint16_t len;
if (sizeof(tag) + sizeof(len) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() <<
"'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
tag = f.pop_letoh<uint16_t>();
len = f.pop_letoh<uint16_t>();
if (1 != tag) {
LOG_WARN(__FUNCTION__ << "(): response contains tagId '0x" << std::hex << tag << "' -> ignoring\n");
f.remove(len);
continue;
}
if (sizeof(uint32_t) != len) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid tag length '" << std::hex << len << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
return f.pop_letoh<uint32_t>();
}
return ADSERR_DEVICE_INVALIDDATA;
}
long GetRemoteAddress(const std::string& remote, AmsNetId& netId)
{
Frame f { 128 };
const uint32_t tagCount = 0;
f.prepend(htole(tagCount));
const auto myAddr = AmsAddr { {}, 0 };
f.prepend(&myAddr, sizeof(myAddr));
const auto status = SendRecv(remote, f, UdpServiceId::SERVERINFO);
if (status) {
return status;
}
// We expect at least the AmsAddr
if (sizeof(netId) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
memcpy(&netId, f.data(), sizeof(netId));
return 0;
}
}
}
<commit_msg>AddRemoteRoute: ignore to long values in UDP tags<commit_after>// SPDX-License-Identifier: MIT
/**
Copyright (c) 2021 - 2022 Beckhoff Automation GmbH & Co. KG
*/
#include "AdsLib.h"
#include "Log.h"
#include "wrap_endian.h"
#include <cstring>
#include <limits>
namespace bhf
{
namespace ads
{
static bool PrependUdpLenTagId(Frame& frame, const uint16_t length, const uint16_t tagId)
{
frame.prepend(htole(length));
frame.prepend(htole(tagId));
return true;
}
static bool PrependUdpTag(Frame& frame, const std::string& value, const uint16_t tagId)
{
if (value.length() + 1 > std::numeric_limits<uint16_t>::max()) {
LOG_WARN(__FUNCTION__ << "(): value is too long, skipping tagId (" << std::dec << tagId << ")\n");
return false;
}
const auto length = static_cast<uint16_t>(value.length() + 1);
frame.prepend(value.data(), length);
return PrependUdpLenTagId(frame, length, tagId);
}
static bool PrependUdpTag(Frame& frame, const AmsNetId& value, const uint16_t tagId)
{
const uint16_t length = sizeof(value);
frame.prepend(&value, length);
return PrependUdpLenTagId(frame, length, tagId);
}
enum UdpTag : uint16_t {
PASSWORD = 2,
COMPUTERNAME = 5,
NETID = 7,
ROUTENAME = 12,
USERNAME = 13,
};
enum UdpServiceId : uint32_t {
SERVERINFO = 1,
ADDROUTE = 6,
RESPONSE = 0x80000000,
};
static long SendRecv(const std::string& remote, Frame& f, const uint32_t serviceId)
{
f.prepend(htole(serviceId));
static const uint32_t invokeId = 0;
f.prepend(htole(invokeId));
static const uint32_t UDP_COOKIE = 0x71146603;
f.prepend(htole(UDP_COOKIE));
const auto addresses = GetListOfAddresses(remote, "48899");
UdpSocket s{addresses.get()};
s.write(f);
f.reset();
static constexpr auto headerLength = sizeof(serviceId) + sizeof(invokeId) + sizeof(UDP_COOKIE);
timeval timeout { 5, 0 };
s.read(f, &timeout);
if (headerLength > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
const auto cookie = f.pop_letoh<uint32_t>();
if (UDP_COOKIE != cookie) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid cookie '" << cookie << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
const auto invoke = f.pop_letoh<uint32_t>();
if (invokeId != invoke) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid invokeId '" << invoke << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
const auto service = f.pop_letoh<uint32_t>();
if ((UdpServiceId::RESPONSE | serviceId) != service) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid serviceId '" << std::hex << service << "'\n");
return ADSERR_DEVICE_INVALIDDATA;
}
return 0;
}
long AddRemoteRoute(const std::string& remote,
AmsNetId destNetId,
const std::string& destAddr,
const std::string& routeName,
const std::string& remoteUsername,
const std::string& remotePassword)
{
Frame f { 256 };
uint32_t tagCount = 0;
tagCount += PrependUdpTag(f, destAddr, UdpTag::COMPUTERNAME);
tagCount += PrependUdpTag(f, remotePassword, UdpTag::PASSWORD);
tagCount += PrependUdpTag(f, remoteUsername, UdpTag::USERNAME);
tagCount += PrependUdpTag(f, destNetId, UdpTag::NETID);
tagCount += PrependUdpTag(f, routeName.empty() ? destAddr : routeName, UdpTag::ROUTENAME);
f.prepend(htole(tagCount));
const auto myAddr = AmsAddr { destNetId, 0 };
f.prepend(&myAddr, sizeof(myAddr));
const auto status = SendRecv(remote, f, UdpServiceId::ADDROUTE);
if (status) {
return status;
}
// We expect at least the AmsAddr and count fields
if (sizeof(AmsAddr) + sizeof(uint32_t) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
// ignore AmsAddr in response
f.remove(sizeof(AmsAddr));
// process UDP discovery tags
auto count = f.pop_letoh<uint32_t>();
while (count--) {
uint16_t tag;
uint16_t len;
if (sizeof(tag) + sizeof(len) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() <<
"'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
tag = f.pop_letoh<uint16_t>();
len = f.pop_letoh<uint16_t>();
if (1 != tag) {
LOG_WARN(__FUNCTION__ << "(): response contains tagId '0x" << std::hex << tag << "' -> ignoring\n");
f.remove(len);
continue;
}
if (sizeof(uint32_t) != len) {
LOG_ERROR(__FUNCTION__ << "(): response contains invalid tag length '" << std::hex << len << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
return f.pop_letoh<uint32_t>();
}
return ADSERR_DEVICE_INVALIDDATA;
}
long GetRemoteAddress(const std::string& remote, AmsNetId& netId)
{
Frame f { 128 };
const uint32_t tagCount = 0;
f.prepend(htole(tagCount));
const auto myAddr = AmsAddr { {}, 0 };
f.prepend(&myAddr, sizeof(myAddr));
const auto status = SendRecv(remote, f, UdpServiceId::SERVERINFO);
if (status) {
return status;
}
// We expect at least the AmsAddr
if (sizeof(netId) > f.capacity()) {
LOG_ERROR(__FUNCTION__ << "(): frame too short to be AMS response '0x" << std::hex << f.capacity() << "'\n");
return ADSERR_DEVICE_INVALIDSIZE;
}
memcpy(&netId, f.data(), sizeof(netId));
return 0;
}
}
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium 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 "chrome/browser/safe_browsing/download_protection_service.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/signature_util.h"
#include "chrome/common/net/http_return.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "content/browser/download/download_item.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_fetcher.h"
#include "content/public/common/url_fetcher_delegate.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
using content::BrowserThread;
namespace safe_browsing {
const char DownloadProtectionService::kDownloadRequestUrl[] =
"https://sb-ssl.google.com/safebrowsing/clientreport/download";
namespace {
bool IsBinaryFile(const FilePath& file) {
return (file.MatchesExtension(FILE_PATH_LITERAL(".exe")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".cab")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".msi")));
}
} // namespace
DownloadProtectionService::DownloadInfo::DownloadInfo()
: total_bytes(0), user_initiated(false) {}
DownloadProtectionService::DownloadInfo::~DownloadInfo() {}
// static
DownloadProtectionService::DownloadInfo
DownloadProtectionService::DownloadInfo::FromDownloadItem(
const DownloadItem& item) {
DownloadInfo download_info;
download_info.local_file = item.full_path();
download_info.download_url_chain = item.url_chain();
download_info.referrer_url = item.referrer_url();
// TODO(bryner): Fill in the hash (we shouldn't compute it again)
download_info.total_bytes = item.total_bytes();
// TODO(bryner): Populate user_initiated
return download_info;
}
class DownloadProtectionService::CheckClientDownloadRequest
: public base::RefCountedThreadSafe<
DownloadProtectionService::CheckClientDownloadRequest,
BrowserThread::DeleteOnUIThread>,
public content::URLFetcherDelegate {
public:
CheckClientDownloadRequest(const DownloadInfo& info,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
SafeBrowsingService* sb_service)
: info_(info),
callback_(callback),
service_(service),
sb_service_(sb_service),
pingback_enabled_(service_->enabled()),
is_signed_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void Start() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// TODO(noelutz): implement some cache to make sure we don't issue the same
// request over and over again if a user downloads the same binary multiple
// times.
if (info_.download_url_chain.empty()) {
RecordStats(REASON_INVALID_URL);
PostFinishTask(SAFE);
return;
}
const GURL& final_url = info_.download_url_chain.back();
if (!final_url.is_valid() || final_url.is_empty() ||
!final_url.SchemeIs("http")) {
RecordStats(REASON_INVALID_URL);
PostFinishTask(SAFE);
return; // For now we only support HTTP download URLs.
}
if (!IsBinaryFile(info_.local_file)) {
RecordStats(REASON_NOT_BINARY_FILE);
PostFinishTask(SAFE);
return;
}
// Compute features from the file contents. Note that we record histograms
// based on the result, so this runs regardless of whether the pingbacks
// are enabled. Since we do blocking I/O, this happens on the file thread.
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::ExtractFileFeatures, this));
}
// Canceling a request will cause us to always report the result as SAFE.
// In addition, the DownloadProtectionService will not be notified when the
// request finishes, so it must drop its reference after calling Cancel.
void Cancel() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
service_ = NULL;
if (fetcher_.get()) {
// The DownloadProtectionService is going to release its reference, so we
// might be destroyed before the URLFetcher completes. Cancel the
// fetcher so it does not try to invoke OnURLFetchComplete.
FinishRequest(SAFE);
fetcher_.reset();
}
// Note: If there is no fetcher, then some callback is still holding a
// reference to this object. We'll eventually wind up in some method on
// the UI thread that will call FinishRequest() and run the callback.
}
// From the content::URLFetcherDelegate interface.
virtual void OnURLFetchComplete(const content::URLFetcher* source) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK_EQ(source, fetcher_.get());
VLOG(2) << "Received a response for URL: "
<< info_.download_url_chain.back() << ": success="
<< source->GetStatus().is_success() << " response_code="
<< source->GetResponseCode();
DownloadCheckResultReason reason = REASON_MAX;
reason = REASON_SERVER_PING_FAILED;
if (source->GetStatus().is_success() &&
RC_REQUEST_OK == source->GetResponseCode()) {
std::string data;
source->GetResponseAsString(&data);
if (data.size() > 0) {
// For now no matter what we'll always say the download is safe.
// TODO(noelutz): Parse the response body to see exactly what's going
// on.
reason = REASON_INVALID_RESPONSE_PROTO;
}
}
if (reason != REASON_MAX) {
RecordStats(reason);
}
// We don't need the fetcher anymore.
fetcher_.reset();
FinishRequest(SAFE);
}
private:
friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
friend class DeleteTask<CheckClientDownloadRequest>;
virtual ~CheckClientDownloadRequest() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void ExtractFileFeatures() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (safe_browsing::signature_util::IsSigned(info_.local_file)) {
VLOG(2) << "Downloaded a signed binary: " << info_.local_file.value();
is_signed_ = true;
} else {
VLOG(2) << "Downloaded an unsigned binary: " << info_.local_file.value();
is_signed_ = false;
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.SignedBinaryDownload", is_signed_);
// TODO(noelutz): DownloadInfo should also contain the IP address of every
// URL in the redirect chain. We also should check whether the download
// URL is hosted on the internal network.
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::CheckWhitelists, this));
}
void CheckWhitelists() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DownloadCheckResultReason reason = REASON_MAX;
if (!sb_service_.get()) {
reason = REASON_SB_DISABLED;
} else {
for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
const GURL& url = info_.download_url_chain[i];
if (url.is_valid() && sb_service_->MatchDownloadWhitelistUrl(url)) {
reason = REASON_WHITELISTED_URL;
break;
}
}
if (info_.referrer_url.is_valid() && reason == REASON_MAX &&
sb_service_->MatchDownloadWhitelistUrl(info_.referrer_url)) {
reason = REASON_WHITELISTED_REFERRER;
}
if (reason != REASON_MAX || is_signed_) {
UMA_HISTOGRAM_COUNTS("SBClientDownload.SignedOrWhitelistedDownload", 1);
}
}
if (reason != REASON_MAX) {
RecordStats(reason);
PostFinishTask(SAFE);
} else if (!pingback_enabled_) {
RecordStats(REASON_SB_DISABLED);
PostFinishTask(SAFE);
} else {
// TODO(noelutz): check signature and CA against whitelist.
// The URLFetcher is owned by the UI thread, so post a message to
// start the pingback.
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::SendRequest, this));
}
}
void SendRequest() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// This is our last chance to check whether the request has been canceled
// before sending it.
if (!service_) {
RecordStats(REASON_REQUEST_CANCELED);
FinishRequest(SAFE);
return;
}
ClientDownloadRequest request;
request.set_url(info_.download_url_chain.back().spec());
request.mutable_digests()->set_sha256(info_.sha256_hash);
request.set_length(info_.total_bytes);
for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(info_.download_url_chain[i].spec());
if (i == info_.download_url_chain.size() - 1) {
// The last URL in the chain is the download URL.
resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
resource->set_referrer(info_.referrer_url.spec());
} else {
resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
}
// TODO(noelutz): fill out the remote IP addresses.
}
request.set_user_initiated(info_.user_initiated);
std::string request_data;
if (!request.SerializeToString(&request_data)) {
RecordStats(REASON_INVALID_REQUEST_PROTO);
FinishRequest(SAFE);
return;
}
VLOG(2) << "Sending a request for URL: "
<< info_.download_url_chain.back();
fetcher_.reset(content::URLFetcher::Create(0 /* ID used for testing */,
GURL(kDownloadRequestUrl),
content::URLFetcher::POST,
this));
fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher_->SetRequestContext(service_->request_context_getter_.get());
fetcher_->SetUploadData("application/octet-stream", request_data);
fetcher_->Start();
}
void PostFinishTask(DownloadCheckResult result) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::FinishRequest, this, result));
}
void FinishRequest(DownloadCheckResult result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (service_) {
callback_.Run(result);
service_->RequestFinished(this);
} else {
callback_.Run(SAFE);
}
}
void RecordStats(DownloadCheckResultReason reason) {
UMA_HISTOGRAM_ENUMERATION("SBClientDownload.CheckDownloadStats",
reason,
REASON_MAX);
}
DownloadInfo info_;
CheckDownloadCallback callback_;
// Will be NULL if the request has been canceled.
DownloadProtectionService* service_;
scoped_refptr<SafeBrowsingService> sb_service_;
const bool pingback_enabled_;
bool is_signed_;
scoped_ptr<content::URLFetcher> fetcher_;
DISALLOW_COPY_AND_ASSIGN(CheckClientDownloadRequest);
};
DownloadProtectionService::DownloadProtectionService(
SafeBrowsingService* sb_service,
net::URLRequestContextGetter* request_context_getter)
: sb_service_(sb_service),
request_context_getter_(request_context_getter),
enabled_(false) {}
DownloadProtectionService::~DownloadProtectionService() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CancelPendingRequests();
}
void DownloadProtectionService::SetEnabled(bool enabled) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (enabled == enabled_) {
return;
}
enabled_ = enabled;
if (!enabled_) {
CancelPendingRequests();
}
}
void DownloadProtectionService::CheckClientDownload(
const DownloadProtectionService::DownloadInfo& info,
const CheckDownloadCallback& callback) {
scoped_refptr<CheckClientDownloadRequest> request(
new CheckClientDownloadRequest(info, callback, this, sb_service_));
download_requests_.insert(request);
request->Start();
}
void DownloadProtectionService::CancelPendingRequests() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
download_requests_.begin();
it != download_requests_.end(); ++it) {
(*it)->Cancel();
}
download_requests_.clear();
}
void DownloadProtectionService::RequestFinished(
CheckClientDownloadRequest* request) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
download_requests_.find(request);
DCHECK(it != download_requests_.end());
download_requests_.erase(*it);
}
} // namespace safe_browsing
<commit_msg>This CL adds a histogram as part of the improved SafeBrowsing download protection to measure how frequently certain file extensions appear in downloads. In particular, we're interested in measuring how often users download files whose extension might be malicious (e.g., and exe file for example).<commit_after>// Copyright (c) 2011 The Chromium 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 "chrome/browser/safe_browsing/download_protection_service.h"
#include "base/bind.h"
#include "base/memory/scoped_ptr.h"
#include "base/metrics/histogram.h"
#include "base/stl_util.h"
#include "base/string_util.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/safe_browsing/signature_util.h"
#include "chrome/common/net/http_return.h"
#include "chrome/common/safe_browsing/csd.pb.h"
#include "content/browser/download/download_item.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/url_fetcher.h"
#include "content/public/common/url_fetcher_delegate.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
using content::BrowserThread;
namespace safe_browsing {
const char DownloadProtectionService::kDownloadRequestUrl[] =
"https://sb-ssl.google.com/safebrowsing/clientreport/download";
namespace {
bool IsBinaryFile(const FilePath& file) {
return (file.MatchesExtension(FILE_PATH_LITERAL(".exe")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".cab")) ||
file.MatchesExtension(FILE_PATH_LITERAL(".msi")));
}
// List of extensions for which we track some UMA stats.
enum MaliciousExtensionType {
EXTENSION_EXE,
EXTENSION_MSI,
EXTENSION_CAB,
EXTENSION_SYS,
EXTENSION_SCR,
EXTENSION_DRV,
EXTENSION_BAT,
EXTENSION_ZIP,
EXTENSION_RAR,
EXTENSION_DLL,
EXTENSION_PIF,
EXTENSION_COM,
EXTENSION_JAR,
EXTENSION_CLASS,
EXTENSION_PDF,
EXTENSION_VB,
EXTENSION_REG,
EXTENSION_GRP,
EXTENSION_OTHER, // Groups all other extensions into one bucket.
EXTENSION_MAX,
};
MaliciousExtensionType GetExtensionType(const FilePath& f) {
if (f.MatchesExtension(FILE_PATH_LITERAL(".exe"))) return EXTENSION_EXE;
if (f.MatchesExtension(FILE_PATH_LITERAL(".msi"))) return EXTENSION_MSI;
if (f.MatchesExtension(FILE_PATH_LITERAL(".cab"))) return EXTENSION_CAB;
if (f.MatchesExtension(FILE_PATH_LITERAL(".sys"))) return EXTENSION_SYS;
if (f.MatchesExtension(FILE_PATH_LITERAL(".scr"))) return EXTENSION_SCR;
if (f.MatchesExtension(FILE_PATH_LITERAL(".drv"))) return EXTENSION_DRV;
if (f.MatchesExtension(FILE_PATH_LITERAL(".bat"))) return EXTENSION_BAT;
if (f.MatchesExtension(FILE_PATH_LITERAL(".zip"))) return EXTENSION_ZIP;
if (f.MatchesExtension(FILE_PATH_LITERAL(".rar"))) return EXTENSION_RAR;
if (f.MatchesExtension(FILE_PATH_LITERAL(".dll"))) return EXTENSION_DLL;
if (f.MatchesExtension(FILE_PATH_LITERAL(".pif"))) return EXTENSION_PIF;
if (f.MatchesExtension(FILE_PATH_LITERAL(".com"))) return EXTENSION_COM;
if (f.MatchesExtension(FILE_PATH_LITERAL(".jar"))) return EXTENSION_JAR;
if (f.MatchesExtension(FILE_PATH_LITERAL(".class"))) return EXTENSION_CLASS;
if (f.MatchesExtension(FILE_PATH_LITERAL(".pdf"))) return EXTENSION_PDF;
if (f.MatchesExtension(FILE_PATH_LITERAL(".vb"))) return EXTENSION_VB;
if (f.MatchesExtension(FILE_PATH_LITERAL(".reg"))) return EXTENSION_REG;
if (f.MatchesExtension(FILE_PATH_LITERAL(".grp"))) return EXTENSION_GRP;
return EXTENSION_OTHER;
}
void RecordFileExtensionType(const FilePath& file) {
UMA_HISTOGRAM_ENUMERATION("SBClientDownload.DownloadExtensions",
GetExtensionType(file),
EXTENSION_MAX);
}
} // namespace
DownloadProtectionService::DownloadInfo::DownloadInfo()
: total_bytes(0), user_initiated(false) {}
DownloadProtectionService::DownloadInfo::~DownloadInfo() {}
// static
DownloadProtectionService::DownloadInfo
DownloadProtectionService::DownloadInfo::FromDownloadItem(
const DownloadItem& item) {
DownloadInfo download_info;
download_info.local_file = item.full_path();
download_info.download_url_chain = item.url_chain();
download_info.referrer_url = item.referrer_url();
// TODO(bryner): Fill in the hash (we shouldn't compute it again)
download_info.total_bytes = item.total_bytes();
// TODO(bryner): Populate user_initiated
return download_info;
}
class DownloadProtectionService::CheckClientDownloadRequest
: public base::RefCountedThreadSafe<
DownloadProtectionService::CheckClientDownloadRequest,
BrowserThread::DeleteOnUIThread>,
public content::URLFetcherDelegate {
public:
CheckClientDownloadRequest(const DownloadInfo& info,
const CheckDownloadCallback& callback,
DownloadProtectionService* service,
SafeBrowsingService* sb_service)
: info_(info),
callback_(callback),
service_(service),
sb_service_(sb_service),
pingback_enabled_(service_->enabled()),
is_signed_(false) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void Start() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// TODO(noelutz): implement some cache to make sure we don't issue the same
// request over and over again if a user downloads the same binary multiple
// times.
if (info_.download_url_chain.empty()) {
RecordStats(REASON_INVALID_URL);
PostFinishTask(SAFE);
return;
}
const GURL& final_url = info_.download_url_chain.back();
if (!final_url.is_valid() || final_url.is_empty() ||
!final_url.SchemeIs("http")) {
RecordStats(REASON_INVALID_URL);
PostFinishTask(SAFE);
return; // For now we only support HTTP download URLs.
}
RecordFileExtensionType(info_.local_file);
if (!IsBinaryFile(info_.local_file)) {
RecordStats(REASON_NOT_BINARY_FILE);
PostFinishTask(SAFE);
return;
}
// Compute features from the file contents. Note that we record histograms
// based on the result, so this runs regardless of whether the pingbacks
// are enabled. Since we do blocking I/O, this happens on the file thread.
BrowserThread::PostTask(
BrowserThread::FILE,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::ExtractFileFeatures, this));
}
// Canceling a request will cause us to always report the result as SAFE.
// In addition, the DownloadProtectionService will not be notified when the
// request finishes, so it must drop its reference after calling Cancel.
void Cancel() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
service_ = NULL;
if (fetcher_.get()) {
// The DownloadProtectionService is going to release its reference, so we
// might be destroyed before the URLFetcher completes. Cancel the
// fetcher so it does not try to invoke OnURLFetchComplete.
FinishRequest(SAFE);
fetcher_.reset();
}
// Note: If there is no fetcher, then some callback is still holding a
// reference to this object. We'll eventually wind up in some method on
// the UI thread that will call FinishRequest() and run the callback.
}
// From the content::URLFetcherDelegate interface.
virtual void OnURLFetchComplete(const content::URLFetcher* source) OVERRIDE {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
DCHECK_EQ(source, fetcher_.get());
VLOG(2) << "Received a response for URL: "
<< info_.download_url_chain.back() << ": success="
<< source->GetStatus().is_success() << " response_code="
<< source->GetResponseCode();
DownloadCheckResultReason reason = REASON_MAX;
reason = REASON_SERVER_PING_FAILED;
if (source->GetStatus().is_success() &&
RC_REQUEST_OK == source->GetResponseCode()) {
std::string data;
source->GetResponseAsString(&data);
if (data.size() > 0) {
// For now no matter what we'll always say the download is safe.
// TODO(noelutz): Parse the response body to see exactly what's going
// on.
reason = REASON_INVALID_RESPONSE_PROTO;
}
}
if (reason != REASON_MAX) {
RecordStats(reason);
}
// We don't need the fetcher anymore.
fetcher_.reset();
FinishRequest(SAFE);
}
private:
friend struct BrowserThread::DeleteOnThread<BrowserThread::UI>;
friend class DeleteTask<CheckClientDownloadRequest>;
virtual ~CheckClientDownloadRequest() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
}
void ExtractFileFeatures() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
if (safe_browsing::signature_util::IsSigned(info_.local_file)) {
VLOG(2) << "Downloaded a signed binary: " << info_.local_file.value();
is_signed_ = true;
} else {
VLOG(2) << "Downloaded an unsigned binary: " << info_.local_file.value();
is_signed_ = false;
}
UMA_HISTOGRAM_BOOLEAN("SBClientDownload.SignedBinaryDownload", is_signed_);
// TODO(noelutz): DownloadInfo should also contain the IP address of every
// URL in the redirect chain. We also should check whether the download
// URL is hosted on the internal network.
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::CheckWhitelists, this));
}
void CheckWhitelists() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DownloadCheckResultReason reason = REASON_MAX;
if (!sb_service_.get()) {
reason = REASON_SB_DISABLED;
} else {
for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
const GURL& url = info_.download_url_chain[i];
if (url.is_valid() && sb_service_->MatchDownloadWhitelistUrl(url)) {
reason = REASON_WHITELISTED_URL;
break;
}
}
if (info_.referrer_url.is_valid() && reason == REASON_MAX &&
sb_service_->MatchDownloadWhitelistUrl(info_.referrer_url)) {
reason = REASON_WHITELISTED_REFERRER;
}
if (reason != REASON_MAX || is_signed_) {
UMA_HISTOGRAM_COUNTS("SBClientDownload.SignedOrWhitelistedDownload", 1);
}
}
if (reason != REASON_MAX) {
RecordStats(reason);
PostFinishTask(SAFE);
} else if (!pingback_enabled_) {
RecordStats(REASON_SB_DISABLED);
PostFinishTask(SAFE);
} else {
// TODO(noelutz): check signature and CA against whitelist.
// The URLFetcher is owned by the UI thread, so post a message to
// start the pingback.
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::SendRequest, this));
}
}
void SendRequest() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
// This is our last chance to check whether the request has been canceled
// before sending it.
if (!service_) {
RecordStats(REASON_REQUEST_CANCELED);
FinishRequest(SAFE);
return;
}
ClientDownloadRequest request;
request.set_url(info_.download_url_chain.back().spec());
request.mutable_digests()->set_sha256(info_.sha256_hash);
request.set_length(info_.total_bytes);
for (size_t i = 0; i < info_.download_url_chain.size(); ++i) {
ClientDownloadRequest::Resource* resource = request.add_resources();
resource->set_url(info_.download_url_chain[i].spec());
if (i == info_.download_url_chain.size() - 1) {
// The last URL in the chain is the download URL.
resource->set_type(ClientDownloadRequest::DOWNLOAD_URL);
resource->set_referrer(info_.referrer_url.spec());
} else {
resource->set_type(ClientDownloadRequest::DOWNLOAD_REDIRECT);
}
// TODO(noelutz): fill out the remote IP addresses.
}
request.set_user_initiated(info_.user_initiated);
std::string request_data;
if (!request.SerializeToString(&request_data)) {
RecordStats(REASON_INVALID_REQUEST_PROTO);
FinishRequest(SAFE);
return;
}
VLOG(2) << "Sending a request for URL: "
<< info_.download_url_chain.back();
fetcher_.reset(content::URLFetcher::Create(0 /* ID used for testing */,
GURL(kDownloadRequestUrl),
content::URLFetcher::POST,
this));
fetcher_->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher_->SetRequestContext(service_->request_context_getter_.get());
fetcher_->SetUploadData("application/octet-stream", request_data);
fetcher_->Start();
}
void PostFinishTask(DownloadCheckResult result) {
BrowserThread::PostTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&CheckClientDownloadRequest::FinishRequest, this, result));
}
void FinishRequest(DownloadCheckResult result) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (service_) {
callback_.Run(result);
service_->RequestFinished(this);
} else {
callback_.Run(SAFE);
}
}
void RecordStats(DownloadCheckResultReason reason) {
UMA_HISTOGRAM_ENUMERATION("SBClientDownload.CheckDownloadStats",
reason,
REASON_MAX);
}
DownloadInfo info_;
CheckDownloadCallback callback_;
// Will be NULL if the request has been canceled.
DownloadProtectionService* service_;
scoped_refptr<SafeBrowsingService> sb_service_;
const bool pingback_enabled_;
bool is_signed_;
scoped_ptr<content::URLFetcher> fetcher_;
DISALLOW_COPY_AND_ASSIGN(CheckClientDownloadRequest);
};
DownloadProtectionService::DownloadProtectionService(
SafeBrowsingService* sb_service,
net::URLRequestContextGetter* request_context_getter)
: sb_service_(sb_service),
request_context_getter_(request_context_getter),
enabled_(false) {}
DownloadProtectionService::~DownloadProtectionService() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
CancelPendingRequests();
}
void DownloadProtectionService::SetEnabled(bool enabled) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
if (enabled == enabled_) {
return;
}
enabled_ = enabled;
if (!enabled_) {
CancelPendingRequests();
}
}
void DownloadProtectionService::CheckClientDownload(
const DownloadProtectionService::DownloadInfo& info,
const CheckDownloadCallback& callback) {
scoped_refptr<CheckClientDownloadRequest> request(
new CheckClientDownloadRequest(info, callback, this, sb_service_));
download_requests_.insert(request);
request->Start();
}
void DownloadProtectionService::CancelPendingRequests() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
for (std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
download_requests_.begin();
it != download_requests_.end(); ++it) {
(*it)->Cancel();
}
download_requests_.clear();
}
void DownloadProtectionService::RequestFinished(
CheckClientDownloadRequest* request) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
std::set<scoped_refptr<CheckClientDownloadRequest> >::iterator it =
download_requests_.find(request);
DCHECK(it != download_requests_.end());
download_requests_.erase(*it);
}
} // namespace safe_browsing
<|endoftext|> |
<commit_before>// Copyright (c) 2009 The Chromium 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 "chrome/browser/sync/notifier/listener/talk_mediator_impl.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "chrome/browser/sync/engine/auth_watcher.h"
#include "chrome/browser/sync/engine/syncer_thread.h"
#include "chrome/browser/sync/notifier/listener/mediator_thread_impl.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "talk/base/cryptstring.h"
#include "talk/base/ssladapter.h"
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmppengine.h"
namespace browser_sync {
// Before any authorization event from TalkMediatorImpl, we need to initialize
// the SSL library.
class SslInitializationSingleton {
public:
virtual ~SslInitializationSingleton() {
talk_base::CleanupSSL();
};
void RegisterClient() {}
static SslInitializationSingleton* GetInstance() {
return Singleton<SslInitializationSingleton>::get();
}
private:
friend struct DefaultSingletonTraits<SslInitializationSingleton>;
SslInitializationSingleton() {
talk_base::InitializeSSL();
};
DISALLOW_COPY_AND_ASSIGN(SslInitializationSingleton);
};
TalkMediatorImpl::TalkMediatorImpl(NotificationMethod notification_method,
bool invalidate_xmpp_auth_token)
: mediator_thread_(new MediatorThreadImpl(notification_method)),
invalidate_xmpp_auth_token_(invalidate_xmpp_auth_token) {
// Ensure the SSL library is initialized.
SslInitializationSingleton::GetInstance()->RegisterClient();
// Construct the callback channel with the shutdown event.
TalkMediatorInitialization(false);
}
TalkMediatorImpl::TalkMediatorImpl(MediatorThread *thread)
: mediator_thread_(thread),
invalidate_xmpp_auth_token_(false) {
// When testing we do not initialize the SSL library.
TalkMediatorInitialization(true);
}
void TalkMediatorImpl::TalkMediatorInitialization(bool should_connect) {
TalkMediatorEvent done = { TalkMediatorEvent::TALKMEDIATOR_DESTROYED };
channel_.reset(new TalkMediatorChannel(done));
if (should_connect) {
mediator_thread_->SignalStateChange.connect(
this,
&TalkMediatorImpl::MediatorThreadMessageHandler);
state_.connected = 1;
}
mediator_thread_->Start();
state_.started = 1;
}
TalkMediatorImpl::~TalkMediatorImpl() {
if (state_.started) {
Logout();
}
}
void TalkMediatorImpl::AuthWatcherEventHandler(
const AuthWatcherEvent& auth_event) {
AutoLock lock(mutex_);
switch (auth_event.what_happened) {
case AuthWatcherEvent::AUTHWATCHER_DESTROYED:
case AuthWatcherEvent::GAIA_AUTH_FAILED:
case AuthWatcherEvent::SERVICE_AUTH_FAILED:
case AuthWatcherEvent::SERVICE_CONNECTION_FAILED:
// We have failed to connect to the buzz server, and we maintain a
// decreased polling interval and stay in a flaky connection mode.
// Note that the failure is on the authwatcher's side and can not be
// resolved without manual retry.
break;
case AuthWatcherEvent::AUTHENTICATION_ATTEMPT_START:
// TODO(brg) : We are restarting the authentication attempt. We need to
// insure this code path is stable.
break;
case AuthWatcherEvent::AUTH_SUCCEEDED:
DoLogin();
break;
default:
// Do nothing.
break;
}
}
void TalkMediatorImpl::WatchAuthWatcher(AuthWatcher* watcher) {
auth_hookup_.reset(NewEventListenerHookup(
watcher->channel(),
this,
&TalkMediatorImpl::AuthWatcherEventHandler));
}
bool TalkMediatorImpl::Login() {
AutoLock lock(mutex_);
return DoLogin();
}
bool TalkMediatorImpl::DoLogin() {
mutex_.AssertAcquired();
// Connect to the mediator thread and start processing messages.
if (!state_.connected) {
mediator_thread_->SignalStateChange.connect(
this,
&TalkMediatorImpl::MediatorThreadMessageHandler);
state_.connected = 1;
}
if (state_.initialized && !state_.logging_in) {
mediator_thread_->Login(xmpp_settings_);
state_.logging_in = 1;
return true;
}
return false;
}
bool TalkMediatorImpl::Logout() {
AutoLock lock(mutex_);
// We do not want to be called back during logout since we may be closing.
if (state_.connected) {
mediator_thread_->SignalStateChange.disconnect(this);
state_.connected = 0;
}
if (state_.started) {
mediator_thread_->Logout();
state_.started = 0;
state_.logging_in = 0;
state_.logged_in = 0;
state_.subscribed = 0;
return true;
}
return false;
}
bool TalkMediatorImpl::SendNotification() {
AutoLock lock(mutex_);
if (state_.logged_in && state_.subscribed) {
mediator_thread_->SendNotification();
return true;
}
return false;
}
TalkMediatorChannel* TalkMediatorImpl::channel() const {
return channel_.get();
}
bool TalkMediatorImpl::SetAuthToken(const std::string& email,
const std::string& token) {
AutoLock lock(mutex_);
// Verify that we can create a JID from the email provided.
buzz::Jid jid = buzz::Jid(email);
if (jid.node().empty() || !jid.IsValid()) {
return false;
}
// Construct the XmppSettings object for login to buzz.
xmpp_settings_.set_user(jid.node());
xmpp_settings_.set_resource("chrome-sync");
xmpp_settings_.set_host(jid.domain());
xmpp_settings_.set_use_tls(true);
xmpp_settings_.set_auth_cookie(invalidate_xmpp_auth_token_ ?
token + "bogus" : token);
state_.initialized = 1;
return true;
}
void TalkMediatorImpl::MediatorThreadMessageHandler(
MediatorThread::MediatorMessage message) {
LOG(INFO) << "P2P: MediatorThread has passed a message";
switch (message) {
case MediatorThread::MSG_LOGGED_IN:
OnLogin();
break;
case MediatorThread::MSG_LOGGED_OUT:
OnLogout();
break;
case MediatorThread::MSG_SUBSCRIPTION_SUCCESS:
OnSubscriptionSuccess();
break;
case MediatorThread::MSG_SUBSCRIPTION_FAILURE:
OnSubscriptionFailure();
break;
case MediatorThread::MSG_NOTIFICATION_RECEIVED:
OnNotificationReceived();
break;
case MediatorThread::MSG_NOTIFICATION_SENT:
OnNotificationSent();
break;
default:
LOG(WARNING) << "P2P: Unknown message returned from mediator thread.";
break;
}
}
void TalkMediatorImpl::OnLogin() {
LOG(INFO) << "P2P: Logged in.";
AutoLock lock(mutex_);
state_.logging_in = 0;
state_.logged_in = 1;
// ListenForUpdates enables the ListenTask. This is done before
// SubscribeForUpdates.
mediator_thread_->ListenForUpdates();
mediator_thread_->SubscribeForUpdates();
TalkMediatorEvent event = { TalkMediatorEvent::LOGIN_SUCCEEDED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnLogout() {
LOG(INFO) << "P2P: Logged off.";
OnSubscriptionFailure();
AutoLock lock(mutex_);
state_.logging_in = 0;
state_.logged_in = 0;
TalkMediatorEvent event = { TalkMediatorEvent::LOGOUT_SUCCEEDED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnSubscriptionSuccess() {
LOG(INFO) << "P2P: Update subscription active.";
AutoLock lock(mutex_);
state_.subscribed = 1;
TalkMediatorEvent event = { TalkMediatorEvent::SUBSCRIPTIONS_ON };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnSubscriptionFailure() {
LOG(INFO) << "P2P: Update subscription failure.";
AutoLock lock(mutex_);
state_.subscribed = 0;
TalkMediatorEvent event = { TalkMediatorEvent::SUBSCRIPTIONS_OFF };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnNotificationReceived() {
LOG(INFO) << "P2P: Updates are available on the server.";
AutoLock lock(mutex_);
TalkMediatorEvent event = { TalkMediatorEvent::NOTIFICATION_RECEIVED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnNotificationSent() {
LOG(INFO) <<
"P2P: Peers were notified that updates are available on the server.";
AutoLock lock(mutex_);
TalkMediatorEvent event = { TalkMediatorEvent::NOTIFICATION_SENT };
channel_->NotifyListeners(event);
}
} // namespace browser_sync
<commit_msg>Send a notification when we connect to p2p<commit_after>// Copyright (c) 2009 The Chromium 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 "chrome/browser/sync/notifier/listener/talk_mediator_impl.h"
#include "base/logging.h"
#include "base/singleton.h"
#include "chrome/browser/sync/engine/auth_watcher.h"
#include "chrome/browser/sync/engine/syncer_thread.h"
#include "chrome/browser/sync/notifier/listener/mediator_thread_impl.h"
#include "chrome/browser/sync/util/event_sys-inl.h"
#include "talk/base/cryptstring.h"
#include "talk/base/ssladapter.h"
#include "talk/xmpp/xmppclientsettings.h"
#include "talk/xmpp/xmppengine.h"
namespace browser_sync {
// Before any authorization event from TalkMediatorImpl, we need to initialize
// the SSL library.
class SslInitializationSingleton {
public:
virtual ~SslInitializationSingleton() {
talk_base::CleanupSSL();
};
void RegisterClient() {}
static SslInitializationSingleton* GetInstance() {
return Singleton<SslInitializationSingleton>::get();
}
private:
friend struct DefaultSingletonTraits<SslInitializationSingleton>;
SslInitializationSingleton() {
talk_base::InitializeSSL();
};
DISALLOW_COPY_AND_ASSIGN(SslInitializationSingleton);
};
TalkMediatorImpl::TalkMediatorImpl(NotificationMethod notification_method,
bool invalidate_xmpp_auth_token)
: mediator_thread_(new MediatorThreadImpl(notification_method)),
invalidate_xmpp_auth_token_(invalidate_xmpp_auth_token) {
// Ensure the SSL library is initialized.
SslInitializationSingleton::GetInstance()->RegisterClient();
// Construct the callback channel with the shutdown event.
TalkMediatorInitialization(false);
}
TalkMediatorImpl::TalkMediatorImpl(MediatorThread *thread)
: mediator_thread_(thread),
invalidate_xmpp_auth_token_(false) {
// When testing we do not initialize the SSL library.
TalkMediatorInitialization(true);
}
void TalkMediatorImpl::TalkMediatorInitialization(bool should_connect) {
TalkMediatorEvent done = { TalkMediatorEvent::TALKMEDIATOR_DESTROYED };
channel_.reset(new TalkMediatorChannel(done));
if (should_connect) {
mediator_thread_->SignalStateChange.connect(
this,
&TalkMediatorImpl::MediatorThreadMessageHandler);
state_.connected = 1;
}
mediator_thread_->Start();
state_.started = 1;
}
TalkMediatorImpl::~TalkMediatorImpl() {
if (state_.started) {
Logout();
}
}
void TalkMediatorImpl::AuthWatcherEventHandler(
const AuthWatcherEvent& auth_event) {
AutoLock lock(mutex_);
switch (auth_event.what_happened) {
case AuthWatcherEvent::AUTHWATCHER_DESTROYED:
case AuthWatcherEvent::GAIA_AUTH_FAILED:
case AuthWatcherEvent::SERVICE_AUTH_FAILED:
case AuthWatcherEvent::SERVICE_CONNECTION_FAILED:
// We have failed to connect to the buzz server, and we maintain a
// decreased polling interval and stay in a flaky connection mode.
// Note that the failure is on the authwatcher's side and can not be
// resolved without manual retry.
break;
case AuthWatcherEvent::AUTHENTICATION_ATTEMPT_START:
// TODO(brg) : We are restarting the authentication attempt. We need to
// insure this code path is stable.
break;
case AuthWatcherEvent::AUTH_SUCCEEDED:
DoLogin();
break;
default:
// Do nothing.
break;
}
}
void TalkMediatorImpl::WatchAuthWatcher(AuthWatcher* watcher) {
auth_hookup_.reset(NewEventListenerHookup(
watcher->channel(),
this,
&TalkMediatorImpl::AuthWatcherEventHandler));
}
bool TalkMediatorImpl::Login() {
AutoLock lock(mutex_);
return DoLogin();
}
bool TalkMediatorImpl::DoLogin() {
mutex_.AssertAcquired();
// Connect to the mediator thread and start processing messages.
if (!state_.connected) {
mediator_thread_->SignalStateChange.connect(
this,
&TalkMediatorImpl::MediatorThreadMessageHandler);
state_.connected = 1;
}
if (state_.initialized && !state_.logging_in) {
mediator_thread_->Login(xmpp_settings_);
state_.logging_in = 1;
return true;
}
return false;
}
bool TalkMediatorImpl::Logout() {
AutoLock lock(mutex_);
// We do not want to be called back during logout since we may be closing.
if (state_.connected) {
mediator_thread_->SignalStateChange.disconnect(this);
state_.connected = 0;
}
if (state_.started) {
mediator_thread_->Logout();
state_.started = 0;
state_.logging_in = 0;
state_.logged_in = 0;
state_.subscribed = 0;
return true;
}
return false;
}
bool TalkMediatorImpl::SendNotification() {
AutoLock lock(mutex_);
if (state_.logged_in && state_.subscribed) {
mediator_thread_->SendNotification();
return true;
}
return false;
}
TalkMediatorChannel* TalkMediatorImpl::channel() const {
return channel_.get();
}
bool TalkMediatorImpl::SetAuthToken(const std::string& email,
const std::string& token) {
AutoLock lock(mutex_);
// Verify that we can create a JID from the email provided.
buzz::Jid jid = buzz::Jid(email);
if (jid.node().empty() || !jid.IsValid()) {
return false;
}
// Construct the XmppSettings object for login to buzz.
xmpp_settings_.set_user(jid.node());
xmpp_settings_.set_resource("chrome-sync");
xmpp_settings_.set_host(jid.domain());
xmpp_settings_.set_use_tls(true);
xmpp_settings_.set_auth_cookie(invalidate_xmpp_auth_token_ ?
token + "bogus" : token);
state_.initialized = 1;
return true;
}
void TalkMediatorImpl::MediatorThreadMessageHandler(
MediatorThread::MediatorMessage message) {
LOG(INFO) << "P2P: MediatorThread has passed a message";
switch (message) {
case MediatorThread::MSG_LOGGED_IN:
OnLogin();
break;
case MediatorThread::MSG_LOGGED_OUT:
OnLogout();
break;
case MediatorThread::MSG_SUBSCRIPTION_SUCCESS:
OnSubscriptionSuccess();
break;
case MediatorThread::MSG_SUBSCRIPTION_FAILURE:
OnSubscriptionFailure();
break;
case MediatorThread::MSG_NOTIFICATION_RECEIVED:
OnNotificationReceived();
break;
case MediatorThread::MSG_NOTIFICATION_SENT:
OnNotificationSent();
break;
default:
LOG(WARNING) << "P2P: Unknown message returned from mediator thread.";
break;
}
}
void TalkMediatorImpl::OnLogin() {
LOG(INFO) << "P2P: Logged in.";
AutoLock lock(mutex_);
state_.logging_in = 0;
state_.logged_in = 1;
// ListenForUpdates enables the ListenTask. This is done before
// SubscribeForUpdates.
mediator_thread_->ListenForUpdates();
mediator_thread_->SubscribeForUpdates();
TalkMediatorEvent event = { TalkMediatorEvent::LOGIN_SUCCEEDED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnLogout() {
LOG(INFO) << "P2P: Logged off.";
OnSubscriptionFailure();
AutoLock lock(mutex_);
state_.logging_in = 0;
state_.logged_in = 0;
TalkMediatorEvent event = { TalkMediatorEvent::LOGOUT_SUCCEEDED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnSubscriptionSuccess() {
LOG(INFO) << "P2P: Update subscription active.";
AutoLock lock(mutex_);
state_.subscribed = 1;
TalkMediatorEvent event = { TalkMediatorEvent::SUBSCRIPTIONS_ON };
channel_->NotifyListeners(event);
// Send an initial nudge when we connect. This is to deal with the
// case that there are unsynced changes when Chromium starts up. This would
// caused changes to be submitted before p2p is enabled, and therefore
// the notification won't get sent out.
mediator_thread_->SendNotification();
}
void TalkMediatorImpl::OnSubscriptionFailure() {
LOG(INFO) << "P2P: Update subscription failure.";
AutoLock lock(mutex_);
state_.subscribed = 0;
TalkMediatorEvent event = { TalkMediatorEvent::SUBSCRIPTIONS_OFF };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnNotificationReceived() {
LOG(INFO) << "P2P: Updates are available on the server.";
AutoLock lock(mutex_);
TalkMediatorEvent event = { TalkMediatorEvent::NOTIFICATION_RECEIVED };
channel_->NotifyListeners(event);
}
void TalkMediatorImpl::OnNotificationSent() {
LOG(INFO) <<
"P2P: Peers were notified that updates are available on the server.";
AutoLock lock(mutex_);
TalkMediatorEvent event = { TalkMediatorEvent::NOTIFICATION_SENT };
channel_->NotifyListeners(event);
}
} // namespace browser_sync
<|endoftext|> |
<commit_before>// Copyright (c) 2011 The Chromium 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 "base/process_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/find_bar/find_notification_details.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/find_bar_host.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/test/test_server.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
#include "views/views_delegate.h"
namespace {
// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";
void Checkpoint(const char* message, const base::TimeTicks& start_time) {
LOG(INFO) << message << " : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
}
class FindInPageTest : public InProcessBrowserTest {
public:
FindInPageTest() {
set_show_window(true);
FindBarHost::disable_animations_during_testing_ = true;
}
string16 GetFindBarText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindText();
}
string16 GetFindBarSelectedText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindSelectedText();
}
};
} // namespace
#if defined(TOOLKIT_USES_GTK)
#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers
#else
#define MAYBE_CrashEscHandlers CrashEscHandlers
#endif
IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Select tab A.
browser()->ActivateTabAt(0, true);
// Close tab B.
browser()->CloseTabContents(browser()->GetTabContentsAt(1));
// Click on the location bar so that Find box loses focus.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
// Check the location bar is focused.
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif
// This used to crash until bug 1303709 was fixed.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL("title1.html");
ui_test_utils::NavigateToURL(browser(), url);
// Focus the location bar, open and close the find-in-page, focus should
// return to the location bar.
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Ensure the creation of the find bar controller.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Focus the location bar, find something on the page, close the find box,
// focus should go to the page.
browser()->FocusLocationBar();
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("a"), true, false, NULL);
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Focus the location bar, open and close the find box, focus should return to
// the location bar (same as before, just checking that http://crbug.com/23599
// is fixed).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
// Search for 'a'.
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("a"), true, false, NULL);
EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
// Make sure Find box is open.
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Search for 'b'.
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("b"), true, false, NULL);
EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText());
// Set focus away from the Find bar (to the Location bar).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Select tab A. Find bar should get focus.
browser()->ActivateTabAt(0, true);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());
// Select tab B. Location bar should get focus.
browser()->ActivateTabAt(1, true);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
// FindInPage on Mac doesn't use prepopulated values. Search there is global.
return;
#endif
base::TimeTicks start_time = base::TimeTicks::Now();
Checkpoint("Test starting", start_time);
ASSERT_TRUE(test_server()->Start());
// Make sure Chrome is in the foreground, otherwise sending input
// won't do anything and the test will hang.
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
Checkpoint("Navigate", start_time);
// First we navigate to any page.
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
Checkpoint("Show Find bar", start_time);
// Show the Find bar.
browser()->GetFindBarController()->Show();
Checkpoint("Search for 'a'", start_time);
// Search for "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_A, false, false, false, false));
// We should find "a" here.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
Checkpoint("Delete 'a'", start_time);
// Delete "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_BACK, false, false, false, false));
// Validate we have cleared the text.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Close find bar", start_time);
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
Checkpoint("Show Find bar", start_time);
// Show the Find bar.
browser()->GetFindBarController()->Show();
Checkpoint("Validate text", start_time);
// After the Find box has been reopened, it should not have been prepopulated
// with "a" again.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Close Find bar", start_time);
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
Checkpoint("FindNext", start_time);
// Press F3 to trigger FindNext.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_F3, false, false, false, false));
Checkpoint("Validate", start_time);
// After the Find box has been reopened, it should still have no prepopulate
// value.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Test done", start_time);
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, PasteWithoutTextChange) {
ASSERT_TRUE(test_server()->Start());
// Make sure Chrome is in the foreground, otherwise sending input
// won't do anything and the test will hang.
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
// First we navigate to any page.
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
// Show the Find bar.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Search for "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_A, false, false, false, false));
// We should find "a" here.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
// Reload the page to clear the matching result.
browser()->Reload(CURRENT_TAB);
// Focus the Find bar again to make sure the text is selected.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// "a" should be selected.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());
// Press Ctrl-C to copy the content.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_C, true, false, false, false));
string16 str;
views::ViewsDelegate::views_delegate->GetClipboard()->
ReadText(ui::Clipboard::BUFFER_STANDARD, &str);
// Make sure the text is copied successfully.
EXPECT_EQ(ASCIIToUTF16("a"), str);
// Press Ctrl-V to paste the content back, it should start finding even if the
// content is not changed.
Source<TabContents> notification_source(browser()->GetSelectedTabContents());
ui_test_utils::WindowedNotificationObserverWithDetails
<FindNotificationDetails> observer(
chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_V, true, false, false, false));
ASSERT_NO_FATAL_FAILURE(observer.Wait());
FindNotificationDetails details;
ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));
EXPECT_TRUE(details.number_of_matches() > 0);
}
<commit_msg>Mark FindInPageTest.PasteWithoutTextChange flaky on Win.<commit_after>// Copyright (c) 2011 The Chromium 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 "base/process_util.h"
#include "base/string_util.h"
#include "base/utf_string_conversions.h"
#include "chrome/browser/tabs/tab_strip_model.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/find_bar/find_bar_controller.h"
#include "chrome/browser/ui/find_bar/find_notification_details.h"
#include "chrome/browser/ui/view_ids.h"
#include "chrome/browser/ui/views/find_bar_host.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/browser/tab_contents/tab_contents.h"
#include "net/test/test_server.h"
#include "ui/base/clipboard/clipboard.h"
#include "ui/base/keycodes/keyboard_codes.h"
#include "views/focus/focus_manager.h"
#include "views/view.h"
#include "views/views_delegate.h"
namespace {
// The delay waited after sending an OS simulated event.
static const int kActionDelayMs = 500;
static const char kSimplePage[] = "files/find_in_page/simple.html";
void Checkpoint(const char* message, const base::TimeTicks& start_time) {
LOG(INFO) << message << " : "
<< (base::TimeTicks::Now() - start_time).InMilliseconds()
<< " ms" << std::flush;
}
class FindInPageTest : public InProcessBrowserTest {
public:
FindInPageTest() {
set_show_window(true);
FindBarHost::disable_animations_during_testing_ = true;
}
string16 GetFindBarText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindText();
}
string16 GetFindBarSelectedText() {
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
return find_bar->GetFindSelectedText();
}
};
} // namespace
#if defined(TOOLKIT_USES_GTK)
#define MAYBE_CrashEscHandlers FLAKY_CrashEscHandlers
#else
#define MAYBE_CrashEscHandlers CrashEscHandlers
#endif
IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_CrashEscHandlers) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Select tab A.
browser()->ActivateTabAt(0, true);
// Close tab B.
browser()->CloseTabContents(browser()->GetTabContentsAt(1));
// Click on the location bar so that Find box loses focus.
ASSERT_NO_FATAL_FAILURE(ui_test_utils::ClickOnView(browser(),
VIEW_ID_LOCATION_BAR));
#if defined(TOOLKIT_VIEWS) || defined(OS_WIN)
// Check the location bar is focused.
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
#endif
// This used to crash until bug 1303709 was fixed.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestore) {
ASSERT_TRUE(test_server()->Start());
GURL url = test_server()->GetURL("title1.html");
ui_test_utils::NavigateToURL(browser(), url);
// Focus the location bar, open and close the find-in-page, focus should
// return to the location bar.
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Ensure the creation of the find bar controller.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Focus the location bar, find something on the page, close the find box,
// focus should go to the page.
browser()->FocusLocationBar();
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("a"), true, false, NULL);
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_TAB_CONTAINER_FOCUS_VIEW));
// Focus the location bar, open and close the find box, focus should return to
// the location bar (same as before, just checking that http://crbug.com/23599
// is fixed).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
browser()->GetFindBarController()->EndFindSession(
FindBarController::kKeepSelection);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
IN_PROC_BROWSER_TEST_F(FindInPageTest, FocusRestoreOnTabSwitch) {
ASSERT_TRUE(test_server()->Start());
// First we navigate to our test page (tab A).
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
FindBarTesting* find_bar =
browser()->GetFindBarController()->find_bar()->GetFindBarTesting();
// Search for 'a'.
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("a"), true, false, NULL);
EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());
// Open another tab (tab B).
browser()->AddSelectedTabWithURL(url, PageTransition::TYPED);
ASSERT_TRUE(ui_test_utils::WaitForNavigationInCurrentTab(browser()));
// Make sure Find box is open.
browser()->Find();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Search for 'b'.
ui_test_utils::FindInPage(browser()->GetSelectedTabContentsWrapper(),
ASCIIToUTF16("b"), true, false, NULL);
EXPECT_TRUE(ASCIIToUTF16("b") == find_bar->GetFindSelectedText());
// Set focus away from the Find bar (to the Location bar).
browser()->FocusLocationBar();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
// Select tab A. Find bar should get focus.
browser()->ActivateTabAt(0, true);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
EXPECT_TRUE(ASCIIToUTF16("a") == find_bar->GetFindSelectedText());
// Select tab B. Location bar should get focus.
browser()->ActivateTabAt(1, true);
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(), VIEW_ID_LOCATION_BAR));
}
// This tests that whenever you clear values from the Find box and close it that
// it respects that and doesn't show you the last search, as reported in bug:
// http://crbug.com/40121.
IN_PROC_BROWSER_TEST_F(FindInPageTest, PrepopulateRespectBlank) {
#if defined(OS_MACOSX)
// FindInPage on Mac doesn't use prepopulated values. Search there is global.
return;
#endif
base::TimeTicks start_time = base::TimeTicks::Now();
Checkpoint("Test starting", start_time);
ASSERT_TRUE(test_server()->Start());
// Make sure Chrome is in the foreground, otherwise sending input
// won't do anything and the test will hang.
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
Checkpoint("Navigate", start_time);
// First we navigate to any page.
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
Checkpoint("Show Find bar", start_time);
// Show the Find bar.
browser()->GetFindBarController()->Show();
Checkpoint("Search for 'a'", start_time);
// Search for "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_A, false, false, false, false));
// We should find "a" here.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
Checkpoint("Delete 'a'", start_time);
// Delete "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_BACK, false, false, false, false));
// Validate we have cleared the text.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Close find bar", start_time);
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
Checkpoint("Show Find bar", start_time);
// Show the Find bar.
browser()->GetFindBarController()->Show();
Checkpoint("Validate text", start_time);
// After the Find box has been reopened, it should not have been prepopulated
// with "a" again.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Close Find bar", start_time);
// Close the Find box.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_ESCAPE, false, false, false, false));
Checkpoint("FindNext", start_time);
// Press F3 to trigger FindNext.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_F3, false, false, false, false));
Checkpoint("Validate", start_time);
// After the Find box has been reopened, it should still have no prepopulate
// value.
EXPECT_EQ(string16(), GetFindBarText());
Checkpoint("Test done", start_time);
}
// Flaky on Win. http://crbug.com/92467
#if defined(OS_WIN)
#define MAYBE_PasteWithoutTextChange FLAKY_PasteWithoutTextChange
#else
#define MAYBE_PasteWithoutTextChange PasteWithoutTextChange
#endif
IN_PROC_BROWSER_TEST_F(FindInPageTest, MAYBE_PasteWithoutTextChange) {
ASSERT_TRUE(test_server()->Start());
// Make sure Chrome is in the foreground, otherwise sending input
// won't do anything and the test will hang.
ASSERT_TRUE(ui_test_utils::BringBrowserWindowToFront(browser()));
// First we navigate to any page.
GURL url = test_server()->GetURL(kSimplePage);
ui_test_utils::NavigateToURL(browser(), url);
// Show the Find bar.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// Search for "a".
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_A, false, false, false, false));
// We should find "a" here.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarText());
// Reload the page to clear the matching result.
browser()->Reload(CURRENT_TAB);
// Focus the Find bar again to make sure the text is selected.
browser()->GetFindBarController()->Show();
EXPECT_TRUE(ui_test_utils::IsViewFocused(browser(),
VIEW_ID_FIND_IN_PAGE_TEXT_FIELD));
// "a" should be selected.
EXPECT_EQ(ASCIIToUTF16("a"), GetFindBarSelectedText());
// Press Ctrl-C to copy the content.
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_C, true, false, false, false));
string16 str;
views::ViewsDelegate::views_delegate->GetClipboard()->
ReadText(ui::Clipboard::BUFFER_STANDARD, &str);
// Make sure the text is copied successfully.
EXPECT_EQ(ASCIIToUTF16("a"), str);
// Press Ctrl-V to paste the content back, it should start finding even if the
// content is not changed.
Source<TabContents> notification_source(browser()->GetSelectedTabContents());
ui_test_utils::WindowedNotificationObserverWithDetails
<FindNotificationDetails> observer(
chrome::NOTIFICATION_FIND_RESULT_AVAILABLE, notification_source);
ASSERT_TRUE(ui_test_utils::SendKeyPressSync(
browser(), ui::VKEY_V, true, false, false, false));
ASSERT_NO_FATAL_FAILURE(observer.Wait());
FindNotificationDetails details;
ASSERT_TRUE(observer.GetDetailsFor(notification_source.map_key(), &details));
EXPECT_TRUE(details.number_of_matches() > 0);
}
<|endoftext|> |
<commit_before>// Copyright (c) 2012 The Chromium 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 "chrome/browser/ui/website_settings/permission_menu_model.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
PermissionMenuModel::PermissionMenuModel(
Delegate* delegate,
ContentSettingsType type,
ContentSetting default_setting,
ContentSetting current_setting)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
delegate_(delegate) {
string16 label;
switch (default_setting) {
case CONTENT_SETTING_ALLOW:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);
break;
case CONTENT_SETTING_BLOCK:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);
break;
case CONTENT_SETTING_ASK:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);
break;
default:
break;
}
AddCheckItem(COMMAND_SET_TO_DEFAULT, label);
if (type != CONTENT_SETTINGS_TYPE_MEDIASTREAM) {
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);
AddCheckItem(COMMAND_SET_TO_ALLOW, label);
}
if (type != CONTENT_SETTINGS_TYPE_FULLSCREEN &&
type != CONTENT_SETTINGS_TYPE_MEDIASTREAM) {
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);
AddCheckItem(COMMAND_SET_TO_BLOCK, label);
}
}
bool PermissionMenuModel::IsCommandIdChecked(int command_id) const {
if (delegate_)
return delegate_->IsCommandIdChecked(command_id);
return false;
}
bool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {
return true;
}
bool PermissionMenuModel::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
// Accelerators are not supported.
return false;
}
void PermissionMenuModel::ExecuteCommand(int command_id) {
if (delegate_)
delegate_->ExecuteCommand(command_id);
}
<commit_msg>Add a TODO for adding the allow setting to the permissions dropdown for media settings on the website settings UI.<commit_after>// Copyright (c) 2012 The Chromium 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 "chrome/browser/ui/website_settings/permission_menu_model.h"
#include "grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"
PermissionMenuModel::PermissionMenuModel(
Delegate* delegate,
ContentSettingsType type,
ContentSetting default_setting,
ContentSetting current_setting)
: ALLOW_THIS_IN_INITIALIZER_LIST(ui::SimpleMenuModel(this)),
delegate_(delegate) {
string16 label;
switch (default_setting) {
case CONTENT_SETTING_ALLOW:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ALLOW);
break;
case CONTENT_SETTING_BLOCK:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_BLOCK);
break;
case CONTENT_SETTING_ASK:
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_DEFAULT_ASK);
break;
default:
break;
}
AddCheckItem(COMMAND_SET_TO_DEFAULT, label);
// TODO(xians): Remove this special case once allow exceptions are supported
// for CONTENT_SETTINGS_TYPE_MEDIASTREAM.
if (type != CONTENT_SETTINGS_TYPE_MEDIASTREAM) {
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_ALLOW);
AddCheckItem(COMMAND_SET_TO_ALLOW, label);
}
if (type != CONTENT_SETTINGS_TYPE_FULLSCREEN &&
type != CONTENT_SETTINGS_TYPE_MEDIASTREAM) {
label = l10n_util::GetStringUTF16(
IDS_WEBSITE_SETTINGS_MENU_ITEM_BLOCK);
AddCheckItem(COMMAND_SET_TO_BLOCK, label);
}
}
bool PermissionMenuModel::IsCommandIdChecked(int command_id) const {
if (delegate_)
return delegate_->IsCommandIdChecked(command_id);
return false;
}
bool PermissionMenuModel::IsCommandIdEnabled(int command_id) const {
return true;
}
bool PermissionMenuModel::GetAcceleratorForCommandId(
int command_id,
ui::Accelerator* accelerator) {
// Accelerators are not supported.
return false;
}
void PermissionMenuModel::ExecuteCommand(int command_id) {
if (delegate_)
delegate_->ExecuteCommand(command_id);
}
<|endoftext|> |
<commit_before>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file battery.cpp
*
* Library calls for battery functionality.
*
* @author Julian Oes <[email protected]>
*/
#include "battery.h"
Battery::Battery() :
SuperBlock(NULL, "BAT"),
_param_v_empty(this, "V_EMPTY"),
_param_v_full(this, "V_CHARGED"),
_param_n_cells(this, "N_CELLS"),
_param_capacity(this, "CAPACITY"),
_param_v_load_drop(this, "V_LOAD_DROP"),
_voltage_filtered_v(0.0f),
_throttle_filtered(0.0f),
_discharged_mah(0.0f),
_remaining(1.0f),
_warning(battery_status_s::BATTERY_WARNING_NONE),
_last_timestamp(0)
{
/* load initial params */
updateParams();
}
Battery::~Battery()
{
}
void
Battery::reset(battery_status_s *battery_status)
{
memset(battery_status, 0, sizeof(*battery_status));
battery_status->current_a = -1.0f;
battery_status->remaining = 0.0f;
battery_status->cell_count = _param_n_cells.get();
// TODO: check if it is sane to reset warning to NONE
battery_status->warning = battery_status_s::BATTERY_WARNING_NONE;
}
void
Battery::updateBatteryStatus(hrt_abstime timestamp, float voltage_v, float current_a, float throttle_normalized,
battery_status_s *battery_status)
{
reset(battery_status);
battery_status->timestamp = timestamp;
filterVoltage(voltage_v);
sumDischarged(timestamp, current_a);
estimateRemaining(voltage_v, throttle_normalized);
determineWarning();
if (_voltage_filtered_v > 2.1f) {
battery_status->voltage_v = voltage_v;
battery_status->voltage_filtered_v = _voltage_filtered_v;
battery_status->current_a = current_a;
battery_status->discharged_mah = _discharged_mah;
battery_status->warning = _warning;
battery_status->remaining = _remaining;
}
}
void
Battery::filterVoltage(float voltage_v)
{
// TODO: inspect that filter performance
const float filtered_next = _voltage_filtered_v * 0.999f + voltage_v * 0.001f;
if (PX4_ISFINITE(filtered_next)) {
_voltage_filtered_v = filtered_next;
}
}
void
Battery::sumDischarged(hrt_abstime timestamp, float current_a)
{
// Not a valid measurement
if (current_a < 0.0f) {
// Because the measurement was invalid we need to stop integration
// and re-initialize with the next valid measurement
_last_timestamp = 0;
return;
}
// Ignore first update because we don't know dT.
if (_last_timestamp != 0) {
_discharged_mah = current_a * (timestamp - _last_timestamp) * 1.0e-3f / 3600.0f;
}
_last_timestamp = timestamp;
}
void
Battery::estimateRemaining(float voltage_v, float throttle_normalized)
{
// XXX this time constant needs to become tunable but really, the right fix are smart batteries.
const float filtered_next = _throttle_filtered * 0.97f + throttle_normalized * 0.03f;
if (PX4_ISFINITE(filtered_next)) {
_throttle_filtered = filtered_next;
}
/* remaining charge estimate based on voltage and internal resistance (drop under load) */
const float bat_v_empty_dynamic = _param_v_empty.get() - (_param_v_load_drop.get() * _throttle_filtered);
/* the range from full to empty is the same for batteries under load and without load,
* since the voltage drop applies to both the full and empty state
*/
const float voltage_range = (_param_v_full.get() - _param_v_empty.get());
const float remaining_voltage = (voltage_v - (_param_n_cells.get() * bat_v_empty_dynamic))
/ (_param_n_cells.get() * voltage_range);
if (_param_capacity.get() > 0.0f) {
/* if battery capacity is known, use discharged current for estimate, but don't show more than voltage estimate */
_remaining = fminf(remaining_voltage, 1.0f - _discharged_mah / _param_capacity.get());
} else {
/* else use voltage */
_remaining = remaining_voltage;
}
/* limit to sane values */
_remaining = (_remaining < 0.0f) ? 0.0f : _remaining;
_remaining = (_remaining > 1.0f) ? 1.0f : _remaining;
}
void
Battery::determineWarning()
{
// TODO: Determine threshold or make params.
if (_remaining < 0.18f) {
_warning = battery_status_s::BATTERY_WARNING_LOW;
} else if (_remaining < 0.09f) {
_warning = battery_status_s::BATTERY_WARNING_CRITICAL;
}
}
<commit_msg>Battery handling: Make critical state accessible<commit_after>/****************************************************************************
*
* Copyright (c) 2016 PX4 Development Team. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. 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.
* 3. Neither the name PX4 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.
*
****************************************************************************/
/**
* @file battery.cpp
*
* Library calls for battery functionality.
*
* @author Julian Oes <[email protected]>
*/
#include "battery.h"
Battery::Battery() :
SuperBlock(NULL, "BAT"),
_param_v_empty(this, "V_EMPTY"),
_param_v_full(this, "V_CHARGED"),
_param_n_cells(this, "N_CELLS"),
_param_capacity(this, "CAPACITY"),
_param_v_load_drop(this, "V_LOAD_DROP"),
_voltage_filtered_v(0.0f),
_throttle_filtered(0.0f),
_discharged_mah(0.0f),
_remaining(1.0f),
_warning(battery_status_s::BATTERY_WARNING_NONE),
_last_timestamp(0)
{
/* load initial params */
updateParams();
}
Battery::~Battery()
{
}
void
Battery::reset(battery_status_s *battery_status)
{
memset(battery_status, 0, sizeof(*battery_status));
battery_status->current_a = -1.0f;
battery_status->remaining = 0.0f;
battery_status->cell_count = _param_n_cells.get();
// TODO: check if it is sane to reset warning to NONE
battery_status->warning = battery_status_s::BATTERY_WARNING_NONE;
}
void
Battery::updateBatteryStatus(hrt_abstime timestamp, float voltage_v, float current_a, float throttle_normalized,
battery_status_s *battery_status)
{
reset(battery_status);
battery_status->timestamp = timestamp;
filterVoltage(voltage_v);
sumDischarged(timestamp, current_a);
estimateRemaining(voltage_v, throttle_normalized);
determineWarning();
if (_voltage_filtered_v > 2.1f) {
battery_status->voltage_v = voltage_v;
battery_status->voltage_filtered_v = _voltage_filtered_v;
battery_status->current_a = current_a;
battery_status->discharged_mah = _discharged_mah;
battery_status->warning = _warning;
battery_status->remaining = _remaining;
}
}
void
Battery::filterVoltage(float voltage_v)
{
// TODO: inspect that filter performance
const float filtered_next = _voltage_filtered_v * 0.999f + voltage_v * 0.001f;
if (PX4_ISFINITE(filtered_next)) {
_voltage_filtered_v = filtered_next;
}
}
void
Battery::sumDischarged(hrt_abstime timestamp, float current_a)
{
// Not a valid measurement
if (current_a < 0.0f) {
// Because the measurement was invalid we need to stop integration
// and re-initialize with the next valid measurement
_last_timestamp = 0;
return;
}
// Ignore first update because we don't know dT.
if (_last_timestamp != 0) {
_discharged_mah = current_a * (timestamp - _last_timestamp) * 1.0e-3f / 3600.0f;
}
_last_timestamp = timestamp;
}
void
Battery::estimateRemaining(float voltage_v, float throttle_normalized)
{
// XXX this time constant needs to become tunable but really, the right fix are smart batteries.
const float filtered_next = _throttle_filtered * 0.97f + throttle_normalized * 0.03f;
if (PX4_ISFINITE(filtered_next)) {
_throttle_filtered = filtered_next;
}
/* remaining charge estimate based on voltage and internal resistance (drop under load) */
const float bat_v_empty_dynamic = _param_v_empty.get() - (_param_v_load_drop.get() * _throttle_filtered);
/* the range from full to empty is the same for batteries under load and without load,
* since the voltage drop applies to both the full and empty state
*/
const float voltage_range = (_param_v_full.get() - _param_v_empty.get());
const float remaining_voltage = (voltage_v - (_param_n_cells.get() * bat_v_empty_dynamic))
/ (_param_n_cells.get() * voltage_range);
if (_param_capacity.get() > 0.0f) {
/* if battery capacity is known, use discharged current for estimate, but don't show more than voltage estimate */
_remaining = fminf(remaining_voltage, 1.0f - _discharged_mah / _param_capacity.get());
} else {
/* else use voltage */
_remaining = remaining_voltage;
}
/* limit to sane values */
_remaining = (_remaining < 0.0f) ? 0.0f : _remaining;
_remaining = (_remaining > 1.0f) ? 1.0f : _remaining;
}
void
Battery::determineWarning()
{
// TODO: Determine threshold or make params.
// Smallest values must come first
if (_remaining < 0.09f) {
_warning = battery_status_s::BATTERY_WARNING_CRITICAL;
} else if (_remaining < 0.18f) {
_warning = battery_status_s::BATTERY_WARNING_LOW;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: NeuroLib (DTI command line tools)
Language: C++
Date: $Date: 2009/01/09 15:39:51 $
Version: $Revision: 1.3 $
Author: Casey Goodlett ([email protected])
Copyright (c) Casey Goodlett. All rights reserved.
See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <numeric>
#include <set>
// ITK includes
#include <itkVersion.h>
#include <itkIndex.h>
#include "fiberio.h"
#include "dtitypes.h"
#include "pomacros.h"
#include "fiberstatsCLP.h"
int main(int argc, char* argv[])
{
#if 0
namespace po = boost::program_options;
using namespace boost::lambda;
// Read program options/configuration
po::options_description config("Usage: fiberstats input-fiber [options]");
config.add_options()
("help,h", "produce this help message")
("verbose,v", "produces verbose output")
;
po::options_description hidden("Hidden options");
hidden.add_options()
("fiber-file", po::value<std::string>(), "DTI fiber file")
;
po::options_description all;
all.add(config).add(hidden);
po::positional_options_description p;
p.add("fiber-file", 1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
}
catch( const po::error & e )
{
std::cout << "Parse error: " << std::endl;
std::cout << config << std::endl;
return EXIT_FAILURE;
}
#endif
PARSE_ARGS;
// End option reading configuration
const bool VERBOSE = verbose;
GroupType::Pointer group = readFiberFile(fiberFile);
verboseMessage("Getting spacing");
// Get Spacing and offset from group
const double* spacing = group->GetSpacing();
typedef itk::Index<3> IndexType;
typedef itk::Functor::IndexLexicographicCompare<3> IndexCompare;
typedef std::set<IndexType, IndexCompare> VoxelSet;
typedef std::list<float> MeasureSample;
typedef std::map<std::string, MeasureSample> SampleMap;
VoxelSet seenvoxels;
SampleMap bundlestats;
bundlestats["fa"] = MeasureSample();
bundlestats["md"] = MeasureSample();
bundlestats["fro"] = MeasureSample();
// For each fiber
ChildrenListType* children = group->GetChildren(0);
ChildrenListType::iterator it;
for( it = children->begin(); it != children->end(); it++ )
{
DTIPointListType pointlist =
dynamic_cast<DTITubeType *>( (*it).GetPointer() )->GetPoints();
DTITubeType::Pointer newtube = DTITubeType::New();
// For each point along the fiber
for( DTIPointListType::iterator pit = pointlist.begin();
pit != pointlist.end(); ++pit )
{
typedef DTIPointType::PointType PointType;
PointType p = pit->GetPosition();
IndexType i;
i[0] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[0]) );
i[1] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[1]) );
i[2] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[2]) );
seenvoxels.insert(i);
typedef DTIPointType::FieldListType FieldList;
const FieldList & fl = pit->GetFields();
for( FieldList::const_iterator flit = fl.begin();
flit != fl.end(); ++flit )
{
if( bundlestats.count(flit->first) )
{
bundlestats[flit->first].push_back(flit->second);
}
}
} // end point loop
} // end fiber loop
double voxelsize = spacing[0] * spacing[1] * spacing[2];
std::cout << "Volume (mm^3): " << seenvoxels.size() * voxelsize << std::endl;
// std::cout << "Measure statistics" << std::endl;
for( SampleMap::const_iterator smit = bundlestats.begin();
smit != bundlestats.end(); ++smit )
{
const std::string statname = smit->first;
double mean = std::accumulate(smit->second.begin(), smit->second.end(), 0.0) / smit->second.size();
std::cout << statname << " mean: " << mean << std::endl;
double var = 0.0; // = std::accumulate(smit->second.begin(), smit->second.end(), 0.0,
// (_1 - mean)*(_1 - mean)) / (smit->second.size() - 1);
for( MeasureSample::const_iterator it2 = smit->second.begin();
it2 != smit->second.end(); it2++ )
{
double minusMean( (*it2) - mean);
var += (minusMean * minusMean) / (smit->second.size() - 1);
}
std::cout << statname << " std: " << std::sqrt(var) << std::endl;
}
delete children;
return EXIT_SUCCESS;
}
<commit_msg>ENH: Add computation of fiber length and average+quantiles on fiber lengths<commit_after>/*=========================================================================
Program: NeuroLib (DTI command line tools)
Language: C++
Date: $Date: 2009/01/09 15:39:51 $
Version: $Revision: 1.3 $
Author: Casey Goodlett ([email protected])
Copyright (c) Casey Goodlett. All rights reserved.
See NeuroLibCopyright.txt or http://www.ia.unc.edu/dev/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
// STL includes
#include <string>
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
// ITK includes
#include <itkVersion.h>
#include <itkIndex.h>
#include "fiberio.h"
#include "dtitypes.h"
#include "pomacros.h"
#include "fiberstatsCLP.h"
int main(int argc, char* argv[])
{
#if 0
namespace po = boost::program_options;
using namespace boost::lambda;
// Read program options/configuration
po::options_description config("Usage: fiberstats input-fiber [options]");
config.add_options()
("help,h", "produce this help message")
("verbose,v", "produces verbose output")
;
po::options_description hidden("Hidden options");
hidden.add_options()
("fiber-file", po::value<std::string>(), "DTI fiber file")
;
po::options_description all;
all.add(config).add(hidden);
po::positional_options_description p;
p.add("fiber-file", 1);
po::variables_map vm;
try
{
po::store(po::command_line_parser(argc, argv).
options(all).positional(p).run(), vm);
po::notify(vm);
}
catch( const po::error & e )
{
std::cout << "Parse error: " << std::endl;
std::cout << config << std::endl;
return EXIT_FAILURE;
}
#endif
PARSE_ARGS;
// End option reading configuration
const bool VERBOSE = verbose;
GroupType::Pointer group = readFiberFile(fiberFile);
verboseMessage("Getting spacing");
// Get Spacing and offset from group
const double* spacing = group->GetSpacing();
typedef itk::Index<3> IndexType;
typedef itk::Functor::IndexLexicographicCompare<3> IndexCompare;
typedef std::set<IndexType, IndexCompare> VoxelSet;
typedef std::list<float> MeasureSample;
typedef std::map<std::string, MeasureSample> SampleMap;
VoxelSet seenvoxels;
SampleMap bundlestats;
bundlestats["fa"] = MeasureSample();
bundlestats["md"] = MeasureSample();
bundlestats["fro"] = MeasureSample();
// For each fiber
std::vector<double> FiberLengthsVector;
ChildrenListType* children = group->GetChildren(0);
ChildrenListType::iterator it;
for( it = children->begin(); it != children->end(); it++ )
{
DTIPointListType pointlist =
dynamic_cast<DTITubeType *>( (*it).GetPointer() )->GetPoints();
DTITubeType::Pointer newtube = DTITubeType::New();
// For each point along the fiber
double FiberLength=0;// Added by Adrien Kaiser 04-03-2013
typedef DTIPointType::PointType PointType;
PointType Previousp = pointlist.begin()->GetPosition();// Added by Adrien Kaiser 04-03-2013
for( DTIPointListType::iterator pit = pointlist.begin();
pit != pointlist.end(); ++pit )
{
PointType p = pit->GetPosition();
// Added by Adrien Kaiser 04-03-2013: Compute length between 2 points
if(pit != pointlist.begin()) // no previous for the first one
{
double length = sqrt( (Previousp[0]-p[0])*(Previousp[0]-p[0]) + (Previousp[1]-p[1])*(Previousp[1]-p[1]) +(Previousp[2]-p[2])*(Previousp[2]-p[2]) );
FiberLength = FiberLength + length;
}
Previousp = p;
//
IndexType i;
i[0] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[0]) );
i[1] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[1]) );
i[2] = static_cast<long int>(vnl_math_rnd_halfinttoeven(p[2]) );
seenvoxels.insert(i);
typedef DTIPointType::FieldListType FieldList;
const FieldList & fl = pit->GetFields();
for( FieldList::const_iterator flit = fl.begin();
flit != fl.end(); ++flit )
{
if( bundlestats.count(flit->first) )
{
bundlestats[flit->first].push_back(flit->second);
}
}
} // end point loop
FiberLengthsVector.push_back(FiberLength);// Added by Adrien Kaiser 04-03-2013
} // end fiber loop
// Added by Adrien Kaiser 04-03-2013: compute average fiber length and quantiles
std::cout<< FiberLengthsVector.size() <<" fibers found"<<std::endl;
if( FiberLengthsVector.empty() )
{
std::cout<<"This fiber file is empty. ABORT."<<std::endl;
return EXIT_FAILURE;
}
double AverageFiberLength = 0;
for(unsigned int AFLVecIter=0; AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
{
AverageFiberLength = AverageFiberLength + FiberLengthsVector[AFLVecIter];
}
AverageFiberLength = AverageFiberLength / FiberLengthsVector.size();
std::cout<<"Average Fiber Length: "<<AverageFiberLength<<std::endl;
sort( FiberLengthsVector.begin(), FiberLengthsVector.end() );
std::cout<<"Minimum Fiber Length: "<< FiberLengthsVector[0] <<std::endl;
std::cout<<"Maximum Fiber Length: "<< FiberLengthsVector[FiberLengthsVector.size()-1] <<std::endl;
std::cout<<"75 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.75*FiberLengthsVector.size()) ] <<std::endl;
std::cout<<"90 percentile Fiber Length: "<< FiberLengthsVector[ (int)(0.9*FiberLengthsVector.size()) ] <<std::endl;
double Average75PercFiberLength = 0;
for(unsigned int AFLVecIter=(int)(0.75*FiberLengthsVector.size()); AFLVecIter < FiberLengthsVector.size();AFLVecIter++)
{
Average75PercFiberLength = Average75PercFiberLength + FiberLengthsVector[AFLVecIter];
}
Average75PercFiberLength = Average75PercFiberLength / (FiberLengthsVector.size() - (int)(0.75*FiberLengthsVector.size())) ;
std::cout<<"Average 75 Percentile Fiber Length: "<<Average75PercFiberLength<<std::endl;
//
double voxelsize = spacing[0] * spacing[1] * spacing[2];
std::cout << "Volume (mm^3): " << seenvoxels.size() * voxelsize << std::endl;
// std::cout << "Measure statistics" << std::endl;
/* for( SampleMap::const_iterator smit = bundlestats.begin();
smit != bundlestats.end(); ++smit )
{
const std::string statname = smit->first;
double mean = std::accumulate(smit->second.begin(), smit->second.end(), 0.0) / smit->second.size();
std::cout << statname << " mean: " << mean << std::endl;
double var = 0.0; // = std::accumulate(smit->second.begin(), smit->second.end(), 0.0,
// (_1 - mean)*(_1 - mean)) / (smit->second.size() - 1);
for( MeasureSample::const_iterator it2 = smit->second.begin();
it2 != smit->second.end(); it2++ )
{
double minusMean( (*it2) - mean);
var += (minusMean * minusMean) / (smit->second.size() - 1);
}
std::cout << statname << " std: " << std::sqrt(var) << std::endl;
}
*/
delete children;
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>/*******************************************************************************
* thrill/mem/allocator_base.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_MEM_ALLOCATOR_BASE_HEADER
#define THRILL_MEM_ALLOCATOR_BASE_HEADER
#include <thrill/common/string.hpp>
#include <thrill/mem/malloc_tracker.hpp>
#include <thrill/mem/manager.hpp>
#include <atomic>
#include <cassert>
#include <deque>
#include <iosfwd>
#include <memory>
#include <new>
#include <string>
#include <type_traits>
#include <vector>
namespace thrill {
namespace mem {
template <typename Type>
class AllocatorBase
{
static const bool debug = true;
public:
using value_type = Type;
using pointer = Type *;
using const_pointer = const Type *;
using reference = Type &;
using const_reference = const Type &;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
//! C++11 type flag
using is_always_equal = std::true_type;
//! C++11 type flag
using propagate_on_container_move_assignment = std::true_type;
//! Returns the address of x.
pointer address(reference x) const noexcept {
return std::addressof(x);
}
//! Returns the address of x.
const_pointer address(const_reference x) const noexcept {
return std::addressof(x);
}
//! Maximum size possible to allocate
size_type max_size() const noexcept {
return size_t(-1) / sizeof(Type);
}
//! Constructs an element object on the location pointed by p.
void construct(pointer p, const_reference value) {
::new ((void*)p)Type(value); // NOLINT
}
//! Destroys in-place the object pointed by p.
void destroy(pointer p) const noexcept {
p->~Type();
}
//! Constructs an element object on the location pointed by p.
template <class SubType, typename ... Args>
void construct(SubType* p, Args&& ... args) {
::new ((void*)p)SubType(std::forward<Args>(args) ...); // NOLINT
}
//! Destroys in-place the object pointed by p.
template <class SubType>
void destroy(SubType* p) const noexcept {
p->~SubType();
}
};
/******************************************************************************/
// FixedAllocator
template <typename Type, Manager& manager_>
class FixedAllocator : public AllocatorBase<Type>
{
static const bool debug = false;
public:
using value_type = Type;
using pointer = Type *;
using const_pointer = const Type *;
using reference = Type &;
using const_reference = const Type &;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
//! C++11 type flag
using is_always_equal = std::true_type;
//! Return allocator for different type.
template <class U>
struct rebind { using other = FixedAllocator<U, manager_>; };
//! default constructor
FixedAllocator() noexcept = default;
//! copy-constructor
FixedAllocator(const FixedAllocator&) noexcept = default;
//! copy-constructor from a rebound allocator
template <typename OtherType>
FixedAllocator(const FixedAllocator<OtherType, manager_>& other) noexcept
{ }
//! Attempts to allocate a block of storage with a size large enough to
//! contain n elements of member type value_type, and returns a pointer to
//! the first element.
pointer allocate(size_type n, const void* /* hint */ = nullptr) {
if (n > this->max_size())
throw std::bad_alloc();
manager_.add(n * sizeof(Type));
if (debug) {
printf("allocate() n=%lu sizeof(T)=%lu total=%lu\n",
n, sizeof(Type), manager_.total());
}
return static_cast<Type*>(bypass_malloc(n * sizeof(Type)));
}
//! Releases a block of storage previously allocated with member allocate
//! and not yet released.
void deallocate(pointer p, size_type n) const noexcept {
manager_.subtract(n * sizeof(Type));
if (debug) {
printf("deallocate() n=%lu sizeof(T)=%lu total=%lu\n",
n, sizeof(Type), manager_.total());
}
bypass_free(p);
}
//! Compare to another allocator of same type
template <class Other>
bool operator == (const FixedAllocator<Other, manager_>&) const noexcept {
return true;
}
//! Compare to another allocator of same type
template <class Other>
bool operator != (const FixedAllocator<Other, manager_>&) const noexcept {
return true;
}
};
template <Manager& manager_>
class FixedAllocator<void, manager_>
{
public:
using pointer = void*;
using const_pointer = const void*;
using value_type = void;
template <class U>
struct rebind { using other = FixedAllocator<U, manager_>; };
};
/******************************************************************************/
// BypassAllocator
//! global bypass memory manager
extern Manager g_bypass_manager;
//! instantiate FixedAllocator as BypassAllocator
template <typename Type>
using BypassAllocator = FixedAllocator<Type, g_bypass_manager>;
//! operator new with our Allocator
template <typename T, class ... Args>
T * by_new(Args&& ... args) {
BypassAllocator<T> allocator;
T* value = allocator.allocate(1);
allocator.construct(value, std::forward<Args>(args) ...);
return value;
}
//! operator delete with our Allocator
template <typename T>
void by_delete(T* value) {
BypassAllocator<T> allocator;
allocator.destroy(value);
allocator.deallocate(value, 1);
}
/******************************************************************************/
// template aliases with BypassAllocator
//! string without malloc tracking
using by_string = std::basic_string<
char, std::char_traits<char>, BypassAllocator<char> >;
//! stringbuf without malloc tracking
using by_stringbuf = std::basic_stringbuf<
char, std::char_traits<char>, BypassAllocator<char> >;
//! vector without malloc tracking
template <typename T>
using by_vector = std::vector<T, BypassAllocator<T> >;
//! deque without malloc tracking
template <typename T>
using by_deque = std::deque<T, BypassAllocator<T> >;
//! convert to string
static inline by_string to_string(int val) {
return common::str_snprintf<by_string>(4 * sizeof(int), "%d", val);
}
//! convert to string
static inline by_string to_string(unsigned val) {
return common::str_snprintf<by_string>(4 * sizeof(int), "%u", val);
}
//! convert to string
static inline by_string to_string(long val) {
return common::str_snprintf<by_string>(4 * sizeof(long), "%ld", val);
}
//! convert to string
static inline by_string to_string(unsigned long val) {
return common::str_snprintf<by_string>(4 * sizeof(long), "%lu", val);
}
} // namespace mem
} // namespace thrill
#endif // !THRILL_MEM_ALLOCATOR_BASE_HEADER
/******************************************************************************/
<commit_msg>Fix unused parameter warning in FixedAllocator copy ctor<commit_after>/*******************************************************************************
* thrill/mem/allocator_base.hpp
*
* Part of Project Thrill.
*
* Copyright (C) 2015 Timo Bingmann <[email protected]>
*
* This file has no license. Only Chuck Norris can compile it.
******************************************************************************/
#pragma once
#ifndef THRILL_MEM_ALLOCATOR_BASE_HEADER
#define THRILL_MEM_ALLOCATOR_BASE_HEADER
#include <thrill/common/string.hpp>
#include <thrill/mem/malloc_tracker.hpp>
#include <thrill/mem/manager.hpp>
#include <atomic>
#include <cassert>
#include <deque>
#include <iosfwd>
#include <memory>
#include <new>
#include <string>
#include <type_traits>
#include <vector>
namespace thrill {
namespace mem {
template <typename Type>
class AllocatorBase
{
static const bool debug = true;
public:
using value_type = Type;
using pointer = Type *;
using const_pointer = const Type *;
using reference = Type &;
using const_reference = const Type &;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
//! C++11 type flag
using is_always_equal = std::true_type;
//! C++11 type flag
using propagate_on_container_move_assignment = std::true_type;
//! Returns the address of x.
pointer address(reference x) const noexcept {
return std::addressof(x);
}
//! Returns the address of x.
const_pointer address(const_reference x) const noexcept {
return std::addressof(x);
}
//! Maximum size possible to allocate
size_type max_size() const noexcept {
return size_t(-1) / sizeof(Type);
}
//! Constructs an element object on the location pointed by p.
void construct(pointer p, const_reference value) {
::new ((void*)p)Type(value); // NOLINT
}
//! Destroys in-place the object pointed by p.
void destroy(pointer p) const noexcept {
p->~Type();
}
//! Constructs an element object on the location pointed by p.
template <class SubType, typename ... Args>
void construct(SubType* p, Args&& ... args) {
::new ((void*)p)SubType(std::forward<Args>(args) ...); // NOLINT
}
//! Destroys in-place the object pointed by p.
template <class SubType>
void destroy(SubType* p) const noexcept {
p->~SubType();
}
};
/******************************************************************************/
// FixedAllocator
template <typename Type, Manager& manager_>
class FixedAllocator : public AllocatorBase<Type>
{
static const bool debug = false;
public:
using value_type = Type;
using pointer = Type *;
using const_pointer = const Type *;
using reference = Type &;
using const_reference = const Type &;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
//! C++11 type flag
using is_always_equal = std::true_type;
//! Return allocator for different type.
template <class U>
struct rebind { using other = FixedAllocator<U, manager_>; };
//! default constructor
FixedAllocator() noexcept = default;
//! copy-constructor
FixedAllocator(const FixedAllocator&) noexcept = default;
//! copy-constructor from a rebound allocator
template <typename OtherType>
FixedAllocator(const FixedAllocator<OtherType, manager_>&) noexcept
{ }
//! Attempts to allocate a block of storage with a size large enough to
//! contain n elements of member type value_type, and returns a pointer to
//! the first element.
pointer allocate(size_type n, const void* /* hint */ = nullptr) {
if (n > this->max_size())
throw std::bad_alloc();
manager_.add(n * sizeof(Type));
if (debug) {
printf("allocate() n=%lu sizeof(T)=%lu total=%lu\n",
n, sizeof(Type), manager_.total());
}
return static_cast<Type*>(bypass_malloc(n * sizeof(Type)));
}
//! Releases a block of storage previously allocated with member allocate
//! and not yet released.
void deallocate(pointer p, size_type n) const noexcept {
manager_.subtract(n * sizeof(Type));
if (debug) {
printf("deallocate() n=%lu sizeof(T)=%lu total=%lu\n",
n, sizeof(Type), manager_.total());
}
bypass_free(p);
}
//! Compare to another allocator of same type
template <class Other>
bool operator == (const FixedAllocator<Other, manager_>&) const noexcept {
return true;
}
//! Compare to another allocator of same type
template <class Other>
bool operator != (const FixedAllocator<Other, manager_>&) const noexcept {
return true;
}
};
template <Manager& manager_>
class FixedAllocator<void, manager_>
{
public:
using pointer = void*;
using const_pointer = const void*;
using value_type = void;
template <class U>
struct rebind { using other = FixedAllocator<U, manager_>; };
};
/******************************************************************************/
// BypassAllocator
//! global bypass memory manager
extern Manager g_bypass_manager;
//! instantiate FixedAllocator as BypassAllocator
template <typename Type>
using BypassAllocator = FixedAllocator<Type, g_bypass_manager>;
//! operator new with our Allocator
template <typename T, class ... Args>
T * by_new(Args&& ... args) {
BypassAllocator<T> allocator;
T* value = allocator.allocate(1);
allocator.construct(value, std::forward<Args>(args) ...);
return value;
}
//! operator delete with our Allocator
template <typename T>
void by_delete(T* value) {
BypassAllocator<T> allocator;
allocator.destroy(value);
allocator.deallocate(value, 1);
}
/******************************************************************************/
// template aliases with BypassAllocator
//! string without malloc tracking
using by_string = std::basic_string<
char, std::char_traits<char>, BypassAllocator<char> >;
//! stringbuf without malloc tracking
using by_stringbuf = std::basic_stringbuf<
char, std::char_traits<char>, BypassAllocator<char> >;
//! vector without malloc tracking
template <typename T>
using by_vector = std::vector<T, BypassAllocator<T> >;
//! deque without malloc tracking
template <typename T>
using by_deque = std::deque<T, BypassAllocator<T> >;
//! convert to string
static inline by_string to_string(int val) {
return common::str_snprintf<by_string>(4 * sizeof(int), "%d", val);
}
//! convert to string
static inline by_string to_string(unsigned val) {
return common::str_snprintf<by_string>(4 * sizeof(int), "%u", val);
}
//! convert to string
static inline by_string to_string(long val) {
return common::str_snprintf<by_string>(4 * sizeof(long), "%ld", val);
}
//! convert to string
static inline by_string to_string(unsigned long val) {
return common::str_snprintf<by_string>(4 * sizeof(long), "%lu", val);
}
} // namespace mem
} // namespace thrill
#endif // !THRILL_MEM_ALLOCATOR_BASE_HEADER
/******************************************************************************/
<|endoftext|> |
<commit_before>#ifndef SYMBOLS_H
#define SYMBOLS_H
#include"objects.hpp"
#include"heaps.hpp"
#include"mutexes.hpp"
#include<vector>
#include<string>
#include<map>
class SymbolsTable;
class Symbol {
ValueHolderRef value;
std::string printname; //utf-8
AppMutex m;
Symbol(); //disallowed
explicit Symbol(std::string x) : printname(x) {};
std::vector<Process*> notification_list;
public:
void copy_value_to(ValueHolderRef&);
void copy_value_to_and_add_notify(ValueHolderRef&, Process*);
void set_value(Object::ref);
std::string getPrintName() { return printname; } // for debugging
/*WARNING! not thread safe. intended for use during soft-stop*/
void traverse_objects(HeapTraverser* ht) {
value->traverse_objects(ht);
}
friend class SymbolsTable;
};
class SymbolsTableTraverser {
public:
virtual void traverse(Symbol*) =0;
virtual ~SymbolsTableTraverser() { }
};
class SymbolsTable {
private:
std::map<std::string, Symbol*> tb;
AppMutex m;
public:
Symbol* lookup(std::string);
inline Symbol* lookup(char const* s) {
return lookup(std::string(s));
}
/*note! no atomicity checks. assumes that traversal
occurs only when all other worker threads are suspended.
*/
void traverse_symbols(SymbolsTableTraverser*) const;
~SymbolsTable();
};
#endif //SYMBOLS_H
<commit_msg>inc/symbols.hpp: Added missing Process declaration<commit_after>#ifndef SYMBOLS_H
#define SYMBOLS_H
#include"objects.hpp"
#include"heaps.hpp"
#include"mutexes.hpp"
#include<vector>
#include<string>
#include<map>
class SymbolsTable;
class Process;
class Symbol {
ValueHolderRef value;
std::string printname; //utf-8
AppMutex m;
Symbol(); //disallowed
explicit Symbol(std::string x) : printname(x) {};
std::vector<Process*> notification_list;
public:
void copy_value_to(ValueHolderRef&);
void copy_value_to_and_add_notify(ValueHolderRef&, Process*);
void set_value(Object::ref);
std::string getPrintName() { return printname; } // for debugging
/*WARNING! not thread safe. intended for use during soft-stop*/
void traverse_objects(HeapTraverser* ht) {
value->traverse_objects(ht);
}
friend class SymbolsTable;
};
class SymbolsTableTraverser {
public:
virtual void traverse(Symbol*) =0;
virtual ~SymbolsTableTraverser() { }
};
class SymbolsTable {
private:
std::map<std::string, Symbol*> tb;
AppMutex m;
public:
Symbol* lookup(std::string);
inline Symbol* lookup(char const* s) {
return lookup(std::string(s));
}
/*note! no atomicity checks. assumes that traversal
occurs only when all other worker threads are suspended.
*/
void traverse_symbols(SymbolsTableTraverser*) const;
~SymbolsTable();
};
#endif //SYMBOLS_H
<|endoftext|> |
<commit_before>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* @(#)root/roofitcore:$Id$
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, [email protected] *
* DK, David Kirkby, UC Irvine, [email protected] *
* *
* Copyright (c) 2000-2005, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////
//
// BEGIN_HTML
// RooStudyManager is a utility class to manage studies that consist of
// repeated applications of generate-and-fit operations on a workspace
//
// END_HTML
//
#include "RooFit.h"
#include "Riostream.h"
#include "RooStudyManager.h"
#include "RooWorkspace.h"
#include "RooAbsStudy.h"
#include "RooDataSet.h"
#include "RooMsgService.h"
#include "RooStudyPackage.h"
#include "TTree.h"
#include "TFile.h"
#include "TRegexp.h"
#include "TKey.h"
#include <string>
#include "TROOT.h"
#include "TSystem.h"
using namespace std ;
ClassImp(RooStudyManager)
;
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(RooWorkspace& w)
{
_pkg = new RooStudyPackage(w) ;
}
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(RooWorkspace& w, RooAbsStudy& study)
{
_pkg = new RooStudyPackage(w) ;
_pkg->addStudy(study) ;
}
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(const char* studyPackFileName)
{
string pwd = gDirectory->GetName() ;
TFile *f = new TFile(studyPackFileName) ;
_pkg = dynamic_cast<RooStudyPackage*>(f->Get("studypack")) ;
gDirectory->cd(Form("%s:",pwd.c_str())) ;
}
//_____________________________________________________________________________
void RooStudyManager::addStudy(RooAbsStudy& study)
{
_pkg->addStudy(study) ;
}
//_____________________________________________________________________________
void RooStudyManager::run(Int_t nExperiments)
{
_pkg->driver(nExperiments) ;
}
//_____________________________________________________________________________
void RooStudyManager::runProof(Int_t nExperiments, const char* proofHost)
{
// Open PROOF-Lite session
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") opening PROOF session" << endl ;
void* p = (void*) gROOT->ProcessLineFast(Form("TProof::Open(\"%s\")",proofHost)) ;
// Propagate workspace to proof nodes
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") sending work package to PROOF servers" << endl ;
gROOT->ProcessLineFast(Form("((TProof*)%p)->AddInput((TObject*)%p) ;",p,(void*)_pkg) ) ;
// Run selector in parallel
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") starting PROOF processing of " << nExperiments << " experiments" << endl ;
gROOT->ProcessLineFast(Form("((TProof*)%p)->Process(\"RooProofDriverSelector\",%d) ;",p,nExperiments)) ;
// Aggregate results data
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") aggregating results data" << endl ;
TList* olist = (TList*) gROOT->ProcessLineFast(Form("((TProof*)%p)->GetOutputList()",p)) ;
aggregateData(olist) ;
}
//_____________________________________________________________________________
void RooStudyManager::prepareBatchInput(const char* studyName, Int_t nExpPerJob, Bool_t unifiedInput=kFALSE)
{
TFile f(Form("study_data_%s.root",studyName),"RECREATE") ;
_pkg->Write("studypack") ;
f.Close() ;
if (unifiedInput) {
// Write header of driver script
ofstream bdr(Form("study_driver_%s.sh",studyName)) ;
bdr << "#!/bin/sh" << endl
<< Form("if [ ! -f study_data_%s.root ] ; then",studyName) << endl
<< "uudecode <<EOR" << endl ;
bdr.close() ;
// Write uuencoded ROOT file (base64) in driver script
gSystem->Exec(Form("cat study_data_%s.root | uuencode -m study_data_%s.root >> study_driver_%s.sh",studyName,studyName,studyName)) ;
// Write remainder of deriver script
ofstream bdr2 (Form("study_driver_%s.sh",studyName),ios::app) ;
bdr2 << "EOR" << endl
<< "fi" << endl
<< "root -l -b <<EOR" << endl
<< Form("RooStudyPackage::processFile(\"%s\",%d) ;",studyName,nExpPerJob) << endl
<< ".q" << endl
<< "EOR" << endl ;
// Remove binary input file
gSystem->Unlink(Form("study_data_%s.root",studyName)) ;
coutI(DataHandling) << "RooStudyManager::prepareBatchInput batch driver file is '" << Form("study_driver_%s.sh",studyName) << "," << endl
<< " input data files is embedded in driver script" << endl ;
} else {
ofstream bdr(Form("study_driver_%s.sh",studyName)) ;
bdr << "#!/bin/sh" << endl
<< "root -l -b <<EOR" << endl
<< Form("RooStudyPackage::processFile(\"%s\",%d) ;",studyName,nExpPerJob) << endl
<< ".q" << endl
<< "EOR" << endl ;
coutI(DataHandling) << "RooStudyManager::prepareBatchInput batch driver file is '" << Form("study_driver_%s.sh",studyName) << "," << endl
<< " input data file is " << Form("study_data_%s.root",studyName) << endl ;
}
}
//_____________________________________________________________________________
void RooStudyManager::processBatchOutput(const char* filePat)
{
list<string> flist ;
expandWildCardSpec(filePat,flist) ;
TList olist ;
for (list<string>::iterator iter = flist.begin() ; iter!=flist.end() ; ++iter) {
coutP(DataHandling) << "RooStudyManager::processBatchOutput() now reading file " << *iter << endl ;
TFile f(iter->c_str()) ;
TList* list = f.GetListOfKeys() ;
TIterator* kiter = list->MakeIterator();
TObject* obj ;
TKey* key ;
while((key=(TKey*)kiter->Next())) {
obj = f.Get(key->GetName()) ;
TObject* clone = obj->Clone(obj->GetName()) ;
olist.Add(clone) ;
}
delete kiter ;
}
aggregateData(&olist) ;
olist.Delete() ;
}
//_____________________________________________________________________________
void RooStudyManager::aggregateData(TList* olist)
{
for (list<RooAbsStudy*>::iterator iter=_pkg->studies().begin() ; iter!=_pkg->studies().end() ; iter++) {
(*iter)->aggregateSummaryOutput(olist) ;
}
}
//_____________________________________________________________________________
void RooStudyManager::expandWildCardSpec(const char* name, list<string>& result)
{
// case with one single file
if (!TString(name).MaybeWildcard()) {
result.push_back(name) ;
return ;
}
// wildcarding used in name
TString basename(name);
Int_t dotslashpos = -1;
{
Int_t next_dot = basename.Index(".root");
while(next_dot>=0) {
dotslashpos = next_dot;
next_dot = basename.Index(".root",dotslashpos+1);
}
if (basename[dotslashpos+5]!='/') {
// We found the 'last' .root in the name and it is not followed by
// a '/', so the tree name is _not_ specified in the name.
dotslashpos = -1;
}
}
//Int_t dotslashpos = basename.Index(".root/");
TString behind_dot_root;
if (dotslashpos>=0) {
// Copy the tree name specification
behind_dot_root = basename(dotslashpos+6,basename.Length()-dotslashpos+6);
// and remove it from basename
basename.Remove(dotslashpos+5);
}
Int_t slashpos = basename.Last('/');
TString directory;
if (slashpos>=0) {
directory = basename(0,slashpos); // Copy the directory name
basename.Remove(0,slashpos+1); // and remove it from basename
} else {
directory = gSystem->UnixPathName(gSystem->WorkingDirectory());
}
const char *file;
void *dir = gSystem->OpenDirectory(gSystem->ExpandPathName(directory.Data()));
if (dir) {
//create a TList to store the file names (not yet sorted)
TList l;
TRegexp re(basename,kTRUE);
while ((file = gSystem->GetDirEntry(dir))) {
if (!strcmp(file,".") || !strcmp(file,"..")) continue;
TString s = file;
if ( (basename!=file) && s.Index(re) == kNPOS) continue;
l.Add(new TObjString(file));
}
gSystem->FreeDirectory(dir);
//sort the files in alphanumeric order
l.Sort();
TIter next(&l);
TObjString *obj;
while ((obj = (TObjString*)next())) {
file = obj->GetName();
if (behind_dot_root.Length() != 0)
result.push_back(Form("%s/%s/%s",directory.Data(),file,behind_dot_root.Data())) ;
else
result.push_back(Form("%s/%s",directory.Data(),file)) ;
}
l.Delete();
}
}
<commit_msg><commit_after>/*****************************************************************************
* Project: RooFit *
* Package: RooFitCore *
* @(#)root/roofitcore:$Id$
* Authors: *
* WV, Wouter Verkerke, UC Santa Barbara, [email protected] *
* DK, David Kirkby, UC Irvine, [email protected] *
* *
* Copyright (c) 2000-2005, Regents of the University of California *
* and Stanford University. All rights reserved. *
* *
* Redistribution and use in source and binary forms, *
* with or without modification, are permitted according to the terms *
* listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
*****************************************************************************/
//////////////////////////////////////////////////////////////////////////////
//
// BEGIN_HTML
// RooStudyManager is a utility class to manage studies that consist of
// repeated applications of generate-and-fit operations on a workspace
//
// END_HTML
//
#include "RooFit.h"
#include "Riostream.h"
#include "RooStudyManager.h"
#include "RooWorkspace.h"
#include "RooAbsStudy.h"
#include "RooDataSet.h"
#include "RooMsgService.h"
#include "RooStudyPackage.h"
#include "TTree.h"
#include "TFile.h"
#include "TRegexp.h"
#include "TKey.h"
#include <string>
#include "TROOT.h"
#include "TSystem.h"
using namespace std ;
ClassImp(RooStudyManager)
;
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(RooWorkspace& w)
{
_pkg = new RooStudyPackage(w) ;
}
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(RooWorkspace& w, RooAbsStudy& study)
{
_pkg = new RooStudyPackage(w) ;
_pkg->addStudy(study) ;
}
//_____________________________________________________________________________
RooStudyManager::RooStudyManager(const char* studyPackFileName)
{
string pwd = gDirectory->GetName() ;
TFile *f = new TFile(studyPackFileName) ;
_pkg = dynamic_cast<RooStudyPackage*>(f->Get("studypack")) ;
gDirectory->cd(Form("%s:",pwd.c_str())) ;
}
//_____________________________________________________________________________
void RooStudyManager::addStudy(RooAbsStudy& study)
{
_pkg->addStudy(study) ;
}
//_____________________________________________________________________________
void RooStudyManager::run(Int_t nExperiments)
{
_pkg->driver(nExperiments) ;
}
//_____________________________________________________________________________
void RooStudyManager::runProof(Int_t nExperiments, const char* proofHost)
{
// Open PROOF-Lite session
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") opening PROOF session" << endl ;
void* p = (void*) gROOT->ProcessLineFast(Form("TProof::Open(\"%s\")",proofHost)) ;
// Propagate workspace to proof nodes
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") sending work package to PROOF servers" << endl ;
gROOT->ProcessLineFast(Form("((TProof*)%p)->AddInput((TObject*)%p) ;",p,(void*)_pkg) ) ;
// Run selector in parallel
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") starting PROOF processing of " << nExperiments << " experiments" << endl ;
gROOT->ProcessLineFast(Form("((TProof*)%p)->Process(\"RooProofDriverSelector\",%d) ;",p,nExperiments)) ;
// Aggregate results data
coutP(Generation) << "RooStudyManager::runProof(" << GetName() << ") aggregating results data" << endl ;
TList* olist = (TList*) gROOT->ProcessLineFast(Form("((TProof*)%p)->GetOutputList()",p)) ;
aggregateData(olist) ;
// close proof session
gROOT->ProcessLineFast(Form("((TProof*)%p)->Close(\"s\") ;",p)) ;
gROOT->ProcessLineFast(Form("delete ((TProof*)%p) ;",p)) ;
}
//_____________________________________________________________________________
void RooStudyManager::prepareBatchInput(const char* studyName, Int_t nExpPerJob, Bool_t unifiedInput=kFALSE)
{
TFile f(Form("study_data_%s.root",studyName),"RECREATE") ;
_pkg->Write("studypack") ;
f.Close() ;
if (unifiedInput) {
// Write header of driver script
ofstream bdr(Form("study_driver_%s.sh",studyName)) ;
bdr << "#!/bin/sh" << endl
<< Form("if [ ! -f study_data_%s.root ] ; then",studyName) << endl
<< "uudecode <<EOR" << endl ;
bdr.close() ;
// Write uuencoded ROOT file (base64) in driver script
gSystem->Exec(Form("cat study_data_%s.root | uuencode -m study_data_%s.root >> study_driver_%s.sh",studyName,studyName,studyName)) ;
// Write remainder of deriver script
ofstream bdr2 (Form("study_driver_%s.sh",studyName),ios::app) ;
bdr2 << "EOR" << endl
<< "fi" << endl
<< "root -l -b <<EOR" << endl
<< Form("RooStudyPackage::processFile(\"%s\",%d) ;",studyName,nExpPerJob) << endl
<< ".q" << endl
<< "EOR" << endl ;
// Remove binary input file
gSystem->Unlink(Form("study_data_%s.root",studyName)) ;
coutI(DataHandling) << "RooStudyManager::prepareBatchInput batch driver file is '" << Form("study_driver_%s.sh",studyName) << "," << endl
<< " input data files is embedded in driver script" << endl ;
} else {
ofstream bdr(Form("study_driver_%s.sh",studyName)) ;
bdr << "#!/bin/sh" << endl
<< "root -l -b <<EOR" << endl
<< Form("RooStudyPackage::processFile(\"%s\",%d) ;",studyName,nExpPerJob) << endl
<< ".q" << endl
<< "EOR" << endl ;
coutI(DataHandling) << "RooStudyManager::prepareBatchInput batch driver file is '" << Form("study_driver_%s.sh",studyName) << "," << endl
<< " input data file is " << Form("study_data_%s.root",studyName) << endl ;
}
}
//_____________________________________________________________________________
void RooStudyManager::processBatchOutput(const char* filePat)
{
list<string> flist ;
expandWildCardSpec(filePat,flist) ;
TList olist ;
for (list<string>::iterator iter = flist.begin() ; iter!=flist.end() ; ++iter) {
coutP(DataHandling) << "RooStudyManager::processBatchOutput() now reading file " << *iter << endl ;
TFile f(iter->c_str()) ;
TList* list = f.GetListOfKeys() ;
TIterator* kiter = list->MakeIterator();
TObject* obj ;
TKey* key ;
while((key=(TKey*)kiter->Next())) {
obj = f.Get(key->GetName()) ;
TObject* clone = obj->Clone(obj->GetName()) ;
olist.Add(clone) ;
}
delete kiter ;
}
aggregateData(&olist) ;
olist.Delete() ;
}
//_____________________________________________________________________________
void RooStudyManager::aggregateData(TList* olist)
{
for (list<RooAbsStudy*>::iterator iter=_pkg->studies().begin() ; iter!=_pkg->studies().end() ; iter++) {
(*iter)->aggregateSummaryOutput(olist) ;
}
}
//_____________________________________________________________________________
void RooStudyManager::expandWildCardSpec(const char* name, list<string>& result)
{
// case with one single file
if (!TString(name).MaybeWildcard()) {
result.push_back(name) ;
return ;
}
// wildcarding used in name
TString basename(name);
Int_t dotslashpos = -1;
{
Int_t next_dot = basename.Index(".root");
while(next_dot>=0) {
dotslashpos = next_dot;
next_dot = basename.Index(".root",dotslashpos+1);
}
if (basename[dotslashpos+5]!='/') {
// We found the 'last' .root in the name and it is not followed by
// a '/', so the tree name is _not_ specified in the name.
dotslashpos = -1;
}
}
//Int_t dotslashpos = basename.Index(".root/");
TString behind_dot_root;
if (dotslashpos>=0) {
// Copy the tree name specification
behind_dot_root = basename(dotslashpos+6,basename.Length()-dotslashpos+6);
// and remove it from basename
basename.Remove(dotslashpos+5);
}
Int_t slashpos = basename.Last('/');
TString directory;
if (slashpos>=0) {
directory = basename(0,slashpos); // Copy the directory name
basename.Remove(0,slashpos+1); // and remove it from basename
} else {
directory = gSystem->UnixPathName(gSystem->WorkingDirectory());
}
const char *file;
void *dir = gSystem->OpenDirectory(gSystem->ExpandPathName(directory.Data()));
if (dir) {
//create a TList to store the file names (not yet sorted)
TList l;
TRegexp re(basename,kTRUE);
while ((file = gSystem->GetDirEntry(dir))) {
if (!strcmp(file,".") || !strcmp(file,"..")) continue;
TString s = file;
if ( (basename!=file) && s.Index(re) == kNPOS) continue;
l.Add(new TObjString(file));
}
gSystem->FreeDirectory(dir);
//sort the files in alphanumeric order
l.Sort();
TIter next(&l);
TObjString *obj;
while ((obj = (TObjString*)next())) {
file = obj->GetName();
if (behind_dot_root.Length() != 0)
result.push_back(Form("%s/%s/%s",directory.Data(),file,behind_dot_root.Data())) ;
else
result.push_back(Form("%s/%s",directory.Data(),file)) ;
}
l.Delete();
}
}
<|endoftext|> |
<commit_before><commit_msg>Fixed another bug in iso engine, cells can now be emptied correctly.<commit_after><|endoftext|> |
<commit_before>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <sstream>
#include "ngraph/file_util.hpp"
#include "ngraph/runtime/executable.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "ngraph/util.hpp"
using namespace std;
using namespace ngraph;
runtime::Executable::Executable()
{
}
runtime::Executable::~Executable()
{
}
bool runtime::Executable::call_with_validate(const vector<shared_ptr<runtime::Tensor>>& outputs,
const vector<shared_ptr<runtime::Tensor>>& inputs)
{
validate(outputs, inputs);
return call(outputs, inputs);
}
void runtime::Executable::validate(const vector<std::shared_ptr<runtime::Tensor>>& outputs,
const vector<std::shared_ptr<runtime::Tensor>>& inputs)
{
const ParameterVector& parameters = get_parameters();
const ResultVector& results = get_results();
if (parameters.size() != inputs.size())
{
stringstream ss;
ss << "Call input count " << inputs.size() << " does not match Function's Parameter count "
<< parameters.size();
throw runtime_error(ss.str());
}
if (results.size() != outputs.size())
{
stringstream ss;
ss << "Call output count " << outputs.size() << " does not match Function's Result count "
<< results.size();
throw runtime_error(ss.str());
}
for (size_t i = 0; i < parameters.size(); i++)
{
if (parameters[i]->get_element_type().is_static() &&
parameters[i]->get_element_type() != inputs[i]->get_element_type())
{
stringstream ss;
ss << "Input " << i << " type '" << inputs[i]->get_element_type()
<< "' does not match Parameter type '" << parameters[i]->get_element_type() << "'";
throw runtime_error(ss.str());
}
if (!(parameters[i]->get_output_partial_shape(0).relaxes(inputs[i]->get_partial_shape())))
{
stringstream ss;
ss << "Input " << i << " shape " << inputs[i]->get_partial_shape()
<< " does not match Parameter shape " << parameters[i]->get_output_partial_shape(0);
throw runtime_error(ss.str());
}
}
for (size_t i = 0; i < results.size(); i++)
{
if (outputs[i]->get_element_type().is_static() &&
results[i]->get_element_type() != outputs[i]->get_element_type())
{
stringstream ss;
ss << "Output " << i << " type '" << outputs[i]->get_element_type()
<< "' does not match Result type '" << results[i]->get_element_type() << "'";
throw runtime_error(ss.str());
}
if (!(outputs[i]->get_partial_shape()).relaxes(results[i]->get_output_partial_shape(0)))
{
stringstream ss;
ss << "Output " << i << " shape " << outputs[i]->get_partial_shape()
<< " does not match Result shape " << results[i]->get_output_partial_shape(0);
throw runtime_error(ss.str());
}
}
}
const ngraph::ParameterVector& runtime::Executable::get_parameters() const
{
return m_parameters;
}
const ngraph::ResultVector& runtime::Executable::get_results() const
{
return m_results;
}
void runtime::Executable::set_parameters_and_results(const Function& func)
{
m_parameters = func.get_parameters();
m_results = func.get_results();
}
vector<runtime::PerformanceCounter> runtime::Executable::get_performance_data() const
{
return vector<PerformanceCounter>();
}
void runtime::Executable::save(std::ostream& output_stream)
{
throw runtime_error("save opertion unimplemented.");
}
shared_ptr<runtime::Tensor> runtime::Executable::create_input_tensor(size_t input_index)
{
throw runtime_error("create_input_tensor unimplemented");
}
shared_ptr<runtime::Tensor> runtime::Executable::create_output_tensor(size_t output_index)
{
throw runtime_error("create_output_tensor unimplemented");
}
vector<shared_ptr<runtime::Tensor>> runtime::Executable::create_input_tensor(size_t input_index,
size_t pipeline_depth)
{
throw runtime_error("create_input_tensor unimplemented");
}
vector<shared_ptr<runtime::Tensor>> runtime::Executable::create_output_tensor(size_t output_index,
size_t pipeline_depth)
{
throw runtime_error("create_output_tensor unimplemented");
}
<commit_msg>fix typo (#3449)<commit_after>//*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#include <sstream>
#include "ngraph/file_util.hpp"
#include "ngraph/runtime/executable.hpp"
#include "ngraph/runtime/tensor.hpp"
#include "ngraph/util.hpp"
using namespace std;
using namespace ngraph;
runtime::Executable::Executable()
{
}
runtime::Executable::~Executable()
{
}
bool runtime::Executable::call_with_validate(const vector<shared_ptr<runtime::Tensor>>& outputs,
const vector<shared_ptr<runtime::Tensor>>& inputs)
{
validate(outputs, inputs);
return call(outputs, inputs);
}
void runtime::Executable::validate(const vector<std::shared_ptr<runtime::Tensor>>& outputs,
const vector<std::shared_ptr<runtime::Tensor>>& inputs)
{
const ParameterVector& parameters = get_parameters();
const ResultVector& results = get_results();
if (parameters.size() != inputs.size())
{
stringstream ss;
ss << "Call input count " << inputs.size() << " does not match Function's Parameter count "
<< parameters.size();
throw runtime_error(ss.str());
}
if (results.size() != outputs.size())
{
stringstream ss;
ss << "Call output count " << outputs.size() << " does not match Function's Result count "
<< results.size();
throw runtime_error(ss.str());
}
for (size_t i = 0; i < parameters.size(); i++)
{
if (parameters[i]->get_element_type().is_static() &&
parameters[i]->get_element_type() != inputs[i]->get_element_type())
{
stringstream ss;
ss << "Input " << i << " type '" << inputs[i]->get_element_type()
<< "' does not match Parameter type '" << parameters[i]->get_element_type() << "'";
throw runtime_error(ss.str());
}
if (!(parameters[i]->get_output_partial_shape(0).relaxes(inputs[i]->get_partial_shape())))
{
stringstream ss;
ss << "Input " << i << " shape " << inputs[i]->get_partial_shape()
<< " does not match Parameter shape " << parameters[i]->get_output_partial_shape(0);
throw runtime_error(ss.str());
}
}
for (size_t i = 0; i < results.size(); i++)
{
if (outputs[i]->get_element_type().is_static() &&
results[i]->get_element_type() != outputs[i]->get_element_type())
{
stringstream ss;
ss << "Output " << i << " type '" << outputs[i]->get_element_type()
<< "' does not match Result type '" << results[i]->get_element_type() << "'";
throw runtime_error(ss.str());
}
if (!(outputs[i]->get_partial_shape()).relaxes(results[i]->get_output_partial_shape(0)))
{
stringstream ss;
ss << "Output " << i << " shape " << outputs[i]->get_partial_shape()
<< " does not match Result shape " << results[i]->get_output_partial_shape(0);
throw runtime_error(ss.str());
}
}
}
const ngraph::ParameterVector& runtime::Executable::get_parameters() const
{
return m_parameters;
}
const ngraph::ResultVector& runtime::Executable::get_results() const
{
return m_results;
}
void runtime::Executable::set_parameters_and_results(const Function& func)
{
m_parameters = func.get_parameters();
m_results = func.get_results();
}
vector<runtime::PerformanceCounter> runtime::Executable::get_performance_data() const
{
return vector<PerformanceCounter>();
}
void runtime::Executable::save(std::ostream& output_stream)
{
throw runtime_error("save operation unimplemented.");
}
shared_ptr<runtime::Tensor> runtime::Executable::create_input_tensor(size_t input_index)
{
throw runtime_error("create_input_tensor unimplemented");
}
shared_ptr<runtime::Tensor> runtime::Executable::create_output_tensor(size_t output_index)
{
throw runtime_error("create_output_tensor unimplemented");
}
vector<shared_ptr<runtime::Tensor>> runtime::Executable::create_input_tensor(size_t input_index,
size_t pipeline_depth)
{
throw runtime_error("create_input_tensor unimplemented");
}
vector<shared_ptr<runtime::Tensor>> runtime::Executable::create_output_tensor(size_t output_index,
size_t pipeline_depth)
{
throw runtime_error("create_output_tensor unimplemented");
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.