Convert submodules to normal folders

This commit is contained in:
2025-10-13 10:53:09 +02:00
parent 6d96f1b99c
commit db100ab012
1319 changed files with 143609 additions and 7 deletions
Submodule ros2_ws/src/cmd_vel_mux deleted from bf9f4ce6eb
+68
View File
@@ -0,0 +1,68 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1612295671">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1612295671" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1612295671" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.520406189" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.778880296" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder arguments="-f ${YUJIN_WORKSPACE}/build/yujin_ocs/${ProjName}/Makefile -j8" command="make" id="cdt.managedbuild.target.gnu.builder.base.1328555746" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.1304797274" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1243660247" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.991921373" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1000098092" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.7779663" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.176134653" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.370153349" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.494129810" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.1233806798" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.1933798163" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/yocs_cmd_vel_mux"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="cmd_vel_mux.null.53888827" name="cmd_vel_mux"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId=""/>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1612295671;cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576;cdt.managedbuild.tool.gnu.c.compiler.base.1000098092;cdt.managedbuild.tool.gnu.c.compiler.input.7779663">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1612295671;cdt.managedbuild.toolchain.gnu.base.1612295671.1777191576;cdt.managedbuild.tool.gnu.cpp.compiler.base.1243660247;cdt.managedbuild.tool.gnu.cpp.compiler.input.991921373">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/yocs_cmd_vel_mux"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
</cproject>
+4
View File
@@ -0,0 +1,4 @@
/bin
/build
/lib
**/__pycache__
+85
View File
@@ -0,0 +1,85 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>yocs_cmd_vel_mux</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.python.pydev.PyDevBuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>make</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>true</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<triggers>full,incremental,</triggers>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
<nature>org.python.pydev.pythonNature</nature>
</natures>
</projectDescription>
+7
View File
@@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?eclipse-pydev version="1.0"?>
<pydev_project>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_INTERPRETER">Default</pydev_property>
<pydev_property name="org.python.pydev.PYTHON_PROJECT_VERSION">python 2.7</pydev_property>
</pydev_project>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<project>
<configuration id="cdt.managedbuild.toolchain.gnu.base.1612295671" name="Default">
<extension point="org.eclipse.cdt.core.LanguageSettingsProvider">
<provider copy-of="extension" id="org.eclipse.cdt.ui.UserLanguageSettingsProvider"/>
<provider-reference id="org.eclipse.cdt.core.ReferencedProjectsLanguageSettingsProvider" ref="shared-provider"/>
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuildCommandParser" id="org.eclipse.cdt.managedbuilder.core.GCCBuildCommandParser" keep-relative-paths="false" name="CDT GCC Build Output Parser" parameter="(.*gcc)|(.*[gc]\+\+)|(clang)" prefer-non-shared="true"/>
<provider-reference id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" ref="shared-provider"/>
<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
</extension>
</configuration>
</project>
+83
View File
@@ -0,0 +1,83 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package yocs_cmd_vel_mux
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0.6.3 (2014-12-05)
------------------
0.6.2 (2014-11-30)
------------------
* yocs_cmd_vel_mux: fixes node handle for output pub
to keep backwards compatibility
* adds a little launcher restructing for muxer and smoother
* Contributors: Marcus Liebhardt
0.6.0 (2014-07-08)
------------------
* updating package informations. remove email for authors. updating maintainer
* Contributors: Jihoon Lee
0.5.3 (2014-03-24)
------------------
* Added support for YAML-CPP 0.5+.
The new yaml-cpp API removes the "node >> outputvar;" operator, and
it has a new way of loading documents. There's no version hint in the
library's headers, so I'm getting the version number from pkg-config.
This part of the patch is a port of the ones created by @ktossell for
map_server and other packages.
The new yaml-cpp also does not have FindValue.
* Contributors: Scott K Logan
0.5.2 (2013-11-05)
------------------
0.5.1 (2013-10-14)
------------------
* Unify naming politics for binaries and plugins.
0.5.0 (2013-10-11)
------------------
* Renamed as yocs_cmd_vel_mux.
0.4.1 (2013-10-08)
------------------
0.4.0 (2013-08-29)
------------------
* Add bugtracker and repo info URLs.
* Changelogs at package level.
* License link fixed.
0.3.0 (2013-07-02)
------------------
0.2.3 (2013-04-15)
------------------
0.2.2 (2013-02-10)
------------------
0.2.1 (2013-02-08)
------------------
0.2.0 (2013-02-07)
------------------
* Catkinized.
0.1.3 (2013-01-08)
------------------
* More generous description.
0.1.2 (2013-01-02)
------------------
* Dynamically reconfigurable.
* Upgraded to new groovy plugin formats.
* Add reconfigure launcher and parameter file.
* Add a dynamic reconfigure script to accept a yaml filename.
0.1.1 (2012-12-21)
------------------
0.1.0 (2012-12-05)
------------------
* Initial version.
+68
View File
@@ -0,0 +1,68 @@
cmake_minimum_required(VERSION 3.5)
project(cmd_vel_mux)
# Default to C++14
if(NOT CMAKE_CXX_STANDARD)
set(CMAKE_CXX_STANDARD 14)
endif()
if(CMAKE_COMPILER_IS_GNUCXX OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")
add_compile_options(-Wall -Wextra -Wpedantic)
endif()
find_package(ament_cmake_ros REQUIRED)
find_package(geometry_msgs REQUIRED)
find_package(rcl_interfaces REQUIRED)
find_package(rclcpp REQUIRED)
find_package(rclcpp_components REQUIRED)
find_package(rcpputils REQUIRED)
find_package(std_msgs REQUIRED)
include_directories(include)
# Nodelet library
add_library(${PROJECT_NAME} SHARED src/cmd_vel_mux.cpp)
ament_target_dependencies(${PROJECT_NAME}
geometry_msgs
rcl_interfaces
rclcpp
rclcpp_components
rcpputils
std_msgs
)
rclcpp_components_register_node(${PROJECT_NAME}
PLUGIN "cmd_vel_mux::CmdVelMux"
EXECUTABLE cmd_vel_mux_node)
install(TARGETS ${PROJECT_NAME}
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
RUNTIME DESTINATION bin
)
install(DIRECTORY include/${PROJECT_NAME}/
DESTINATION include/${PROJECT_NAME}
)
install(DIRECTORY config launch
DESTINATION share/${PROJECT_NAME}
)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
find_package(ros_testing REQUIRED)
add_ros_test(test/test_cmd_vel_mux.py
TARGET test_cmd_vel_mux
TIMEOUT 30
)
add_ros_test(test/test_cmd_vel_mux_updates.py
TARGET test_cmd_vel_mux_updates
TIMEOUT 30
)
endif()
ament_package()
+31
View File
@@ -0,0 +1,31 @@
# Software License Agreement (BSD License)
#
# Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
# 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 Yujin Robot 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.
+47
View File
@@ -0,0 +1,47 @@
# cmd_vel mux
## About
A ROS 2 package for selecting among a number of incoming geometry_msg/msg/Twist messages, choosing the highest
priority one to republish on the output topic. It will automatically dislodge streams that are lower
priority or that stop publishing for any reason. The stream currently in use is published on the
"active" topic.
## Published Topics
* `/active` (`std_msgs/msg/String`) - A latched topic. Publishes the "name" field of the currently active `geometry_msgs/msg/Twist` stream (see Parameters below), or "idle" if nothing is being a published.
* `/cmd_vel` (`geometry_msgs/msg/Twist`) - The current `geometry_msgs/msg/Twist` message. The values from the current highest-priority `geometry_msgs/msg/Twist` are republished here without change.
## Subscribed Topics
* `/any` (`geometry_msgs/msg/Twist`) - For each named input (see Parameters below), a topic of type `geometry_msgs/msg/Twist` is subscribed to based on the `topic` parameter. The data from the highest-priority of these inputs is republished on the output `/cmd_vel`.
## Parameters
The cmd_vel_mux node uses a dictionary to hold the subscribers, with `name` being the key of each element:
* `name` (string) - The "name" of each of the input `geometry_msgs/msg/Twist` topics. This is what will be published on the `active` topic when the currently active publisher changes.
* `topic` (string) - The "topic" corresponding to each of the input `geometry_msgs/msg/Twist` topics. This is what will be subscribed to.
* `timeout` (double) - The "timeout" of each of the input `geometry_msgs/msg/Twist` topics. If no data is received on the input topic for this amount of time, the input will be automatically disabled.
* `priority` (integer) - The "priority" of each of the input `geometry_msgs/msg/Twist` topics. The higher the number, the higher the priority. Higher priority topics will dislodge lower priority topics and start publishing to the output topic automatically.
* `short_desc` (string) - The "short description" of each of the input `geometry_msgs/msg/Twist` topics. This is informational only.
See config/cmd_vel_mux_params.yaml for an example of how to set these up.
## Changing values
The dictionary translates to parameters in the form of `subscribers.` + name + `topic/timeout/priority/short_desc`.
It can be changed on the fly using `ros2 param set` command, followed with the parameter in the form mentioned above and the value.
## Adding subscriber
To add a new subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic, timeout, priority and short_desc. All 4 need to be present for a new subscriber to be added.
**Ex.1** for testing:
```
ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 4, string_value: /input/new_input}}, {name : subscribers.new_input.priority, value: {type: 2, integer_value: 20}}, {name : subscribers.new_input.timeout, value: {type: 3, double_value: 0.2}}, {name : subscribers.new_input.short_desc, value: {type: 4, string_value: 'test input'}}]}"
```
sets *new_input* subscriber listening at topic `/input/new_input`
## Deleting subscriber
To delete a subscriber, call the service `/cmd_vel_mux/set_parameters_atomically` with a `rcl_interfaces/srv/SetParametersAtomically` message with a parameters value equal to an array of 4 `rcl_interfaces/msg/Parameter` messages, containing the new subscriber topic,timeout,priority and short_desc with the `type` key inside the `rcl/parameter/ParameterValue` being set to 0 (PARAMETER_NOT_SET).
**Ex.2** for testing:
```
ros2 service call /cmd_vel_mux/set_parameters_atomically rcl_interfaces/srv/SetParametersAtomically "{parameters: [{name : subscribers.new_input.topic, value: {type: 0}}, {name : subscribers.new_input.priority, value: {type: 0}}, {name : subscribers.new_input.timeout, value: {type: 0}}, {name : subscribers.new_input.short_desc, value: {type: 0}}]}"
```
deletes *new_input* subscriber added at ex.1
@@ -0,0 +1,47 @@
# Created on: Feb 05, 2020
# Author: Jose Tomas Lorente
# Configuration for subscribers to cmd_vel sources. This file is provided just as an example.
# Typically automatic controllers, as ROS navigation stack should have the minimum priority
#
# Used with example.launch
#
# Individual subscriber configuration:
# name: Source name
# topic: The topic that provides cmd_vel messages
# timeout: Time in seconds without incoming messages to consider this topic inactive
# priority: Priority: an UNIQUE unsigned integer from 0 (lowest) to MAX_INT
# short_desc: Short description
cmd_vel_mux:
ros__parameters:
subscribers:
default_input:
topic: "input/default"
timeout: 0.1
priority: 0
short_desc: "The default cmd_vel, controllers unaware that we are multiplexing cmd_vel should come here"
navigation_stack:
topic: "input/navigation"
timeout: 0.5
priority: 1
short_desc: "Navigation stack controller"
navigation_stack_controller:
topic: "input/joystick"
timeout: 0.1
priority: 10
short_desc: "Navigation stack remote control"
remote_control:
topic: "input/remote"
timeout: 0.1
priority: 9
short_desc: "Remote control"
web_application:
topic: "input/webapp"
timeout: 0.3
priority: 8
short_desc: "Web application"
keyboard_operation:
topic: "input/keyop"
timeout: 0.1
priority: 7
short_desc: "Keyboard operation"
@@ -0,0 +1,152 @@
// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// 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 Yujin Robot 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.
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef CMD_VEL_MUX__CMD_VEL_MUX_HPP_
#define CMD_VEL_MUX__CMD_VEL_MUX_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "geometry_msgs/msg/twist.hpp"
#include "rcl_interfaces/msg/set_parameters_result.hpp"
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace cmd_vel_mux
{
/*****************************************************************************
** CmdVelMux
*****************************************************************************/
struct ParameterValues
{
std::string topic; /**< The name of the topic */
double timeout{-1.0}; /**< Timer's timeout, in seconds */
int64_t priority{-1}; /**< UNIQUE integer from 0 (lowest priority) to MAX_INT */
std::string short_desc; /**< Short description */
};
bool operator==(const ParameterValues & parameters1, const ParameterValues & parameters2)
{
if (parameters1.topic != parameters2.topic) {
return false;
} else if (parameters1.timeout != parameters2.timeout) {
return false;
} else if (parameters1.priority != parameters2.priority) {
return false;
} else if (parameters1.short_desc != parameters2.short_desc) {
return false;
}
return true;
}
class CmdVelMux final : public rclcpp::Node
{
public:
explicit CmdVelMux(rclcpp::NodeOptions options);
~CmdVelMux() override = default;
CmdVelMux(CmdVelMux && c) = delete;
CmdVelMux & operator=(CmdVelMux && c) = delete;
CmdVelMux(const CmdVelMux & c) = delete;
CmdVelMux & operator=(const CmdVelMux & c) = delete;
private:
/// ID for "nobody" active input
static const char * const VACANT;
/// Multiplexed command velocity topic
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr output_topic_pub_;
/// Currently allowed cmd_vel subscriber
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr active_subscriber_pub_;
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr param_cb_;
std::string allowed_;
void timerCallback(const std::string & key);
void cmdVelCallback(
const std::shared_ptr<geometry_msgs::msg::Twist> msg,
const std::string & key);
rcl_interfaces::msg::SetParametersResult parameterUpdate(
const std::vector<rclcpp::Parameter> & update_parameters);
/*********************
** Private Classes
**********************/
/**
* Inner class describing an individual subscriber to a cmd_vel topic
*/
struct CmdVelSub final
{
/// Descriptive name; must be unique to this subscriber
std::string name_;
ParameterValues values_;
/// The subscriber itself
rclcpp::Subscription<geometry_msgs::msg::Twist>::SharedPtr sub_;
/// No incoming messages timeout
rclcpp::TimerBase::SharedPtr timer_;
};
bool addInputToParameterMap(
std::map<std::string, ParameterValues> & parsed_parameters,
const std::string & input_name, const std::string & parameter_name,
const rclcpp::Parameter & parameter_value);
bool parametersAreValid(
const std::map<std::string, ParameterValues> & parameters) const;
void configureFromParameters(
const std::map<std::string, ParameterValues> & parameters);
std::map<std::string, ParameterValues> parseFromParametersMap(
const std::map<std::string,
rclcpp::Parameter> & parameters);
std::map<std::string, std::shared_ptr<CmdVelSub>> map_;
};
} // namespace cmd_vel_mux
#endif // CMD_VEL_MUX__CMD_VEL_MUX_HPP_
@@ -0,0 +1,71 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# 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 {copyright_holder} 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.
"""Launch the cmd_vel_mux node composed with default configuration."""
import os
import ament_index_python.packages
from launch import LaunchDescription
from launch_ros.actions import ComposableNodeContainer
from launch_ros.descriptions import ComposableNode
import yaml
def generate_launch_description():
share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux')
# Passing parameters to a composed node must be done via a dictionary of
# key -> value pairs. Here we read in the data from the configuration file
# and create a dictionary of it that the ComposableNode will accept.
params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml')
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters']
container = ComposableNodeContainer(
name='cmd_vel_mux_container',
namespace='',
package='rclcpp_components',
executable='component_container',
composable_node_descriptions=[
ComposableNode(
package='cmd_vel_mux',
plugin='cmd_vel_mux::CmdVelMux',
name='cmd_vel_mux',
parameters=[params]
),
],
output='both',
)
return LaunchDescription([container])
@@ -0,0 +1,63 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# 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 {copyright_holder} 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.
"""Launch the cmd_vel_mux node with default configuration."""
import os
import ament_index_python.packages
import launch
import launch_ros.actions
import yaml
def generate_launch_description():
share_dir = ament_index_python.packages.get_package_share_directory('cmd_vel_mux')
# There are two different ways to pass parameters to a non-composed node;
# either by specifying the path to the file containing the parameters, or by
# passing a dictionary containing the key -> value pairs of the parameters.
# When starting a *composed* node on the other hand, only the dictionary
# style is supported. To keep the code between the non-composed and
# composed launch file similar, we use that style here as well.
params_file = os.path.join(share_dir, 'config', 'cmd_vel_mux_params.yaml')
with open(params_file, 'r') as f:
params = yaml.safe_load(f)['cmd_vel_mux']['ros__parameters']
cmd_vel_mux_node = launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
output='both',
parameters=[params]
)
return launch.LaunchDescription([cmd_vel_mux_node])
+50
View File
@@ -0,0 +1,50 @@
<?xml version="1.0" encoding="utf-8"?>
<?xml-model href="http://download.ros.org/schema/package_format2.xsd" schematypens="http://www.w3.org/2001/XMLSchema"?>
<package format="2">
<name>cmd_vel_mux</name>
<version>0.12.1</version>
<description>
A multiplexer for command velocity inputs. Arbitrates incoming cmd_vel messages from several topics,
allowing one topic at a time to command the robot, based on priorities. It also deallocates current
allowed topic if no messages are received after a configured timeout. All topics, together with their
priority and timeout are configured through a YAML file, that can be reload at runtime.
</description>
<maintainer email="clalancette@openrobotics.org">Chris Lalancette</maintainer>
<license>BSD</license>
<url type="website">https://github.com/kobuki-base/cmd_vel_mux</url>
<url type="repository">https://github.com/kobuki-base/cmd_vel_mux</url>
<url type="bugtracker">https://github.com/kobuki-base/cmd_vel_mux/issues</url>
<author>Jorge Santos Simon</author>
<author email="jihoonl@yujinrobot.com">Jihoon Lee</author>
<buildtool_depend>ament_cmake_ros</buildtool_depend>
<build_depend>geometry_msgs</build_depend>
<build_depend>rcl_interfaces</build_depend>
<build_depend>rclcpp</build_depend>
<build_depend>rclcpp_components</build_depend>
<build_depend>rcpputils</build_depend>
<build_depend>std_msgs</build_depend>
<exec_depend>geometry_msgs</exec_depend>
<exec_depend>rcl_interfaces</exec_depend>
<exec_depend>rclcpp</exec_depend>
<exec_depend>rclcpp_components</exec_depend>
<exec_depend>rcpputils</exec_depend>
<exec_depend>std_msgs</exec_depend>
<!-- <test_depend>ament_cmake_copyright</test_depend> -->
<test_depend>ament_cmake_cppcheck</test_depend>
<test_depend>ament_cmake_cpplint</test_depend>
<test_depend>ament_cmake_flake8</test_depend>
<test_depend>ament_cmake_lint_cmake</test_depend>
<test_depend>ament_cmake_pep257</test_depend>
<test_depend>ament_cmake_uncrustify</test_depend>
<test_depend>ament_cmake_xmllint</test_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ros_testing</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
+429
View File
@@ -0,0 +1,429 @@
// Copyright (c) 2012 Yujin Robot, Daniel Stonier, Jorge Santos
// All rights reserved.
//
// Software License Agreement (BSD License 2.0)
//
// 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 Yujin Robot 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.
/*****************************************************************************
** Includes
*****************************************************************************/
#include <chrono>
#include <cinttypes>
#include <fstream>
#include <functional>
#include <limits>
#include <map>
#include <memory>
#include <set>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
#include "cmd_vel_mux/cmd_vel_mux.hpp"
#include "geometry_msgs/msg/twist.hpp"
#include "rcl_interfaces/msg/set_parameters_result.hpp"
#include "rclcpp/rclcpp.hpp"
#include "rclcpp_components/register_node_macro.hpp"
#include "rcpputils/split.hpp"
#include "std_msgs/msg/string.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace cmd_vel_mux
{
/*****************************************************************************
** Implementation
*****************************************************************************/
const char * const CmdVelMux::VACANT = "empty";
CmdVelMux::CmdVelMux(rclcpp::NodeOptions options)
: rclcpp::Node("cmd_vel_mux", options.allow_undeclared_parameters(
true).automatically_declare_parameters_from_overrides(true)), allowed_(VACANT)
{
std::map<std::string, rclcpp::Parameter> parameters;
// Check if there are loaded parameters from config file besides sim_time_used
if (!get_parameters("subscribers", parameters) || parameters.size() < 1) {
RCLCPP_WARN(get_logger(), "No subscribers configured!");
} else {
std::map<std::string, ParameterValues> parsed_parameters = parseFromParametersMap(parameters);
if (parsed_parameters.empty()) {
// We ran into some kind of error while configuring, quit
throw std::runtime_error("Invalid parameters");
}
if (!parametersAreValid(parsed_parameters)) {
throw std::runtime_error("Incomplete parameters");
}
configureFromParameters(parsed_parameters);
}
param_cb_ =
add_on_set_parameters_callback(
std::bind(&CmdVelMux::parameterUpdate, this, std::placeholders::_1));
output_topic_pub_ = this->create_publisher<geometry_msgs::msg::Twist>("cmd_vel", 10);
RCLCPP_DEBUG(get_logger(), "CmdVelMux : subscribe to output topic 'cmd_vel'");
active_subscriber_pub_ = this->create_publisher<std_msgs::msg::String>(
"active", rclcpp::QoS(1).transient_local()); // latched topic
// Notify the world that right now nobody is publishing on cmd_vel yet
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
RCLCPP_DEBUG(get_logger(), "CmdVelMux : successfully initialized");
}
bool CmdVelMux::parametersAreValid(const std::map<std::string, ParameterValues> & parameters) const
{
std::set<int64_t> used_priorities;
for (const std::pair<const std::string, ParameterValues> & parameter : parameters) {
if (parameter.second.topic.empty()) {
RCLCPP_WARN(get_logger(), "Empty topic for '%s'", parameter.first.c_str());
return false;
}
if (parameter.second.timeout < 0.0) {
RCLCPP_WARN(get_logger(), "Missing timeout for '%s', ignoring", parameter.first.c_str());
return false;
}
if (parameter.second.priority < 0) {
RCLCPP_WARN(get_logger(), "Missing priority for '%s', ignoring", parameter.first.c_str());
return false;
}
if (parameter.second.short_desc.empty()) {
RCLCPP_WARN(get_logger(), "Empty short_desc for '%s', ignoring", parameter.first.c_str());
return false;
}
if (used_priorities.count(parameter.second.priority) != 0) {
RCLCPP_WARN(get_logger(), "Cannot have duplicate priorities, ignoring");
return false;
}
used_priorities.insert(parameter.second.priority);
}
return true;
}
void CmdVelMux::configureFromParameters(const std::map<std::string, ParameterValues> & parameters)
{
std::map<std::string, std::shared_ptr<CmdVelSub>> new_map;
for (const std::pair<const std::string, ParameterValues> & parameter : parameters) {
const std::string & key = parameter.first;
const ParameterValues & parameter_values = parameter.second;
// Check if parameter subscriber has all its necessary values
if (map_.count(key) != 0) {
// For names already in the subscribers map, retain current
// object so we don't re-subscribe to the topic
new_map[key] = map_[key];
} else {
new_map[key] = std::make_shared<CmdVelSub>();
}
// update existing or new object with the new configuration
new_map[key]->name_ = key;
new_map[key]->values_.priority = parameter_values.priority;
new_map[key]->values_.short_desc = parameter_values.short_desc;
if (parameter_values.topic != new_map[key]->values_.topic) {
// Shutdown the topic if the name has changed so it gets recreated
// on configuration reload. In the case of new subscribers, topic
// is empty and shutdown has just no effect
new_map[key]->values_.topic = parameter_values.topic;
new_map[key]->sub_ = nullptr;
}
if (parameter_values.timeout != new_map[key]->values_.timeout) {
// Change timer period if the timeout changed
new_map[key]->values_.timeout = parameter_values.timeout;
new_map[key]->timer_ = nullptr;
}
}
// Take down the deleted subscriber if it was the one being used as source
if (allowed_ != VACANT && new_map.count(allowed_) == 0) {
allowed_ = VACANT;
// ...notify the world that nobody is publishing on cmd_vel; its vacant
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
}
map_ = new_map;
// (Re)create subscribers whose topic is invalid: new ones and those with changed names
for (std::pair<const std::string, std::shared_ptr<CmdVelSub>> & m : map_) {
const std::string & key = m.first;
const std::shared_ptr<CmdVelSub> & values = m.second;
if (!values->sub_) {
values->sub_ = this->create_subscription<geometry_msgs::msg::Twist>(
values->values_.topic, 10,
[this, key](const geometry_msgs::msg::Twist::SharedPtr msg) {cmdVelCallback(msg, key);});
RCLCPP_DEBUG(
get_logger(), "CmdVelMux : subscribed to '%s' on topic '%s'. pr: %" PRId64 ", to: %.2f",
values->name_.c_str(), values->values_.topic.c_str(),
values->values_.priority, values->values_.timeout);
} else {
RCLCPP_DEBUG(
get_logger(), "CmdVelMux : no need to re-subscribe to input topic '%s'",
values->values_.topic.c_str());
}
if (!values->timer_) {
// Create (stopped by now) a one-shot timer for every subscriber, if it doesn't exist yet
values->timer_ = this->create_wall_timer(
std::chrono::duration_cast<std::chrono::nanoseconds>(
std::chrono::duration<double>(
values->values_.timeout)), [this, key]() {timerCallback(key);});
}
}
RCLCPP_INFO(get_logger(), "CmdVelMux : (re)configured");
}
bool CmdVelMux::addInputToParameterMap(
std::map<std::string, ParameterValues> & parsed_parameters,
const std::string & input_name,
const std::string & parameter_name,
const rclcpp::Parameter & parameter_value)
{
if (parameter_name == "topic") {
std::string topic;
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
topic.clear();
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) {
topic = parameter_value.as_string();
} else {
RCLCPP_WARN(get_logger(), "topic must be a string; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].topic = topic;
} else if (parameter_name == "timeout") {
double timeout{-1.0};
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
timeout = -1.0;
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_DOUBLE) {
timeout = parameter_value.as_double();
} else {
RCLCPP_WARN(get_logger(), "timeout must be a double; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].timeout = timeout;
} else if (parameter_name == "priority") {
int64_t priority{-1};
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
priority = -1;
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_INTEGER) {
priority = parameter_value.as_int();
if (priority < 0 || priority > std::numeric_limits<uint32_t>::max()) {
RCLCPP_WARN(get_logger(), "Priority out of range, must be between 0 and MAX_UINT32");
return false;
}
} else {
RCLCPP_WARN(get_logger(), "priority must be an integer; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].priority = priority;
} else if (parameter_name == "short_desc") {
std::string short_desc;
if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_NOT_SET) {
short_desc.clear();
} else if (parameter_value.get_type() == rclcpp::ParameterType::PARAMETER_STRING) {
short_desc = parameter_value.as_string();
} else {
RCLCPP_WARN(get_logger(), "short_desc must be a string; ignoring");
return false;
}
if (parsed_parameters.count(input_name) == 0) {
parsed_parameters.emplace(std::make_pair(input_name, ParameterValues()));
}
parsed_parameters[input_name].short_desc = short_desc;
} else {
RCLCPP_WARN(get_logger(), "Invalid input variable '%s'; ignored", parameter_name.c_str());
return false;
}
return true;
}
std::map<std::string, ParameterValues> CmdVelMux::parseFromParametersMap(
const std::map<std::string,
rclcpp::Parameter> & parameters)
{
std::map<std::string, ParameterValues> parsed_parameters;
// Iterate over all parameters and parse their content
for (const std::pair<const std::string, rclcpp::Parameter> & parameter : parameters) {
std::vector<std::string> splits = rcpputils::split(parameter.first, '.');
if (splits.size() != 2) {
RCLCPP_WARN(
get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.first.c_str());
continue;
}
const std::string & input_name = splits[0];
const std::string & parameter_name = splits[1];
const rclcpp::Parameter & parameter_value = parameter.second;
if (!addInputToParameterMap(parsed_parameters, input_name, parameter_name, parameter_value)) {
parsed_parameters.clear();
break;
}
}
return parsed_parameters;
}
void CmdVelMux::cmdVelCallback(
const std::shared_ptr<geometry_msgs::msg::Twist> msg,
const std::string & key)
{
// if subscriber was deleted or the one being called right now just ignore
if (map_.count(key) == 0) {
return;
}
// Reset timer for this source
map_[key]->timer_->reset();
// Give permit to publish to this source if it's the only active or is
// already allowed or has higher priority that the currently allowed
if ((allowed_ == VACANT) ||
(allowed_ == key) ||
(map_[key]->values_.priority > map_[allowed_]->values_.priority))
{
if (allowed_ != key) {
allowed_ = key;
// Notify the world that a new cmd_vel source took the control
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = map_[key]->name_;
active_subscriber_pub_->publish(std::move(active_msg));
}
output_topic_pub_->publish(*msg);
}
}
// The per-topic timerCallback is continually reset as cmd_vel messages are
// received. Thus, if it ever expires, then the topic hasn't published within
// the specified timeout period and it should be removed.
void CmdVelMux::timerCallback(const std::string & key)
{
if (allowed_ == key) {
// No cmd_vel messages timeout happened to currently active source, so...
allowed_ = VACANT;
// ...notify the world that nobody is publishing on cmd_vel; its vacant
auto active_msg = std::make_unique<std_msgs::msg::String>();
active_msg->data = "idle";
active_subscriber_pub_->publish(std::move(active_msg));
}
}
rcl_interfaces::msg::SetParametersResult CmdVelMux::parameterUpdate(
const std::vector<rclcpp::Parameter> & update_parameters)
{
rcl_interfaces::msg::SetParametersResult result;
result.successful = true;
std::map<std::string, rclcpp::Parameter> old_parameters;
if (!get_parameters("subscribers", old_parameters) || old_parameters.size() <= 1) {
result.successful = false;
result.reason = "no parameters loaded";
return result;
}
std::map<std::string, ParameterValues> parameters = parseFromParametersMap(old_parameters);
// And then merge them
for (const rclcpp::Parameter & parameter : update_parameters) {
std::vector<std::string> splits = rcpputils::split(parameter.get_name(), '.');
if (splits.size() != 3) {
RCLCPP_WARN(
get_logger(), "Invalid or unknown parameter '%s', ignoring", parameter.get_name().c_str());
result.successful = false;
result.reason = "Invalid or unknown parameter";
break;
}
if (splits[0] != "subscribers") {
RCLCPP_WARN(
get_logger(), "Unknown parameter prefix '%s', ignoring", parameter.get_name().c_str());
result.successful = false;
result.reason = "Unknown parameter prefix";
break;
}
const std::string & input_name = splits[1];
const std::string & parameter_name = splits[2];
if (!addInputToParameterMap(parameters, input_name, parameter_name, parameter)) {
result.successful = false;
result.reason = "Invalid parameter";
break;
}
}
if (result.successful) {
if (parametersAreValid(parameters)) {
configureFromParameters(parameters);
} else {
result.successful = false;
result.reason = "Incomplete parameters";
}
}
return result;
}
} // namespace cmd_vel_mux
RCLCPP_COMPONENTS_REGISTER_NODE(cmd_vel_mux::CmdVelMux)
@@ -0,0 +1,217 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# 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 {copyright_holder} 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.
import collections.abc
import contextlib
import unittest
import geometry_msgs.msg
import launch
import launch.actions
import launch.substitutions
import launch_ros.actions
import launch_ros.substitutions
import launch_testing.actions
import launch_testing.tools
import rclpy
import rclpy.qos
import std_msgs.msg
def generate_test_description():
path_to_cmd_vel_mux_params = launch.substitutions.PathJoinSubstitution([
launch_ros.substitutions.FindPackageShare(package='cmd_vel_mux'),
'config',
'cmd_vel_mux_params.yaml'
])
return launch.LaunchDescription([
launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
parameters=[path_to_cmd_vel_mux_params],
output='screen'
),
launch_testing.actions.ReadyToTest()
])
latching_qos_profile = rclpy.qos.QoSProfile(depth=1)
latching_qos_profile.reliability = rclpy.qos.QoSReliabilityPolicy.RELIABLE
latching_qos_profile.durability = rclpy.qos.QoSDurabilityPolicy.TRANSIENT_LOCAL
class TestCmdVelMux(unittest.TestCase):
@classmethod
def setUpClass(
cls,
launch_service,
proc_info,
proc_output
):
rclpy.init()
cls._node = rclpy.create_node(
'cmd_vel_mux_testing_node', start_parameter_services=False
)
@classmethod
def tearDownClass(cls):
cls._node.destroy_node()
rclpy.shutdown()
@contextlib.contextmanager
def pub(
self,
message,
*,
topic,
rate,
qos_profile=None
):
if qos_profile is None:
qos_profile = rclpy.qos.qos_profile_system_default
publisher = self._node.create_publisher(type(message), topic, qos_profile=qos_profile)
timer = self._node.create_timer(1.0 / rate, lambda *args: publisher.publish(message))
try:
yield
finally:
self._node.destroy_timer(timer)
self._node.destroy_publisher(publisher)
def expect(
self,
expected_sequence,
*,
topic,
message_type=None,
timeout=None,
qos_profile=None
):
future = rclpy.task.Future()
if not isinstance(expected_sequence, collections.abc.Sequence):
if expected_sequence is not None:
expected_sequence = [expected_sequence]
if expected_sequence is not None and len(expected_sequence) > 0:
if message_type is None:
message_type = type(expected_sequence[0])
sequence_types = tuple(type(message) for message in expected_sequence)
if not all(type_ == message_type for type_ in sequence_types):
raise ValueError(
f'inconsistent message types: found {sequence_types}'
f' but expected {message_type} only'
)
def _callback(message):
nonlocal expected_sequence
if expected_sequence[0] == message:
expected_sequence = expected_sequence[1:]
if len(expected_sequence) == 0:
future.set_result(None)
else:
if message_type is None:
raise ValueError('cannot infer message type')
def _callback(message):
future.set_result(None)
if qos_profile is None:
qos_profile = rclpy.qos.qos_profile_system_default
subscription = self._node.create_subscription(
message_type, topic, _callback, qos_profile=qos_profile
)
try:
rclpy.spin_until_future_complete(self._node, future, timeout_sec=timeout)
return ((expected_sequence is None) ^ future.done())
finally:
self._node.destroy_subscription(subscription)
def test_idle_mux(self):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'idle'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(
None, topic='cmd_vel', message_type=geometry_msgs.msg.Twist, timeout=2
))
def test_mux_with_single_input(self):
default_twist = geometry_msgs.msg.Twist()
default_twist.linear.x = 1.0
with self.pub(default_twist, topic='input/default', rate=20):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'default_input'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(default_twist, topic='cmd_vel', timeout=2))
def test_mux_priority_override(self):
default_twist = geometry_msgs.msg.Twist()
default_twist.linear.x = 1.0
joystick_twist = geometry_msgs.msg.Twist()
joystick_twist.angular.z = 1.0
with self.pub(
default_twist, topic='input/default', rate=20
), self.pub(
joystick_twist, topic='input/joystick', rate=20
):
expected_active_input = std_msgs.msg.String()
expected_active_input.data = 'navigation_stack_controller'
self.assertTrue(self.expect(
expected_active_input,
topic='active', timeout=2,
qos_profile=latching_qos_profile
))
self.assertTrue(self.expect(joystick_twist, topic='cmd_vel', timeout=2))
def test_mux_timeout(self):
no_twist = geometry_msgs.msg.Twist()
with self.pub(no_twist, topic='input/default', rate=8):
idle_input = std_msgs.msg.String()
idle_input.data = 'idle'
default_input = std_msgs.msg.String()
default_input.data = 'default_input'
self.assertTrue(self.expect(
[idle_input, default_input, idle_input],
topic='active', timeout=5,
qos_profile=latching_qos_profile
))
@@ -0,0 +1,249 @@
# Copyright 2020 Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Software License Agreement (BSD License 2.0)
#
# 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 {copyright_holder} 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.
import collections
import contextlib
import functools
import re
import unittest
import launch
import launch.actions
import launch.substitutions
import launch_ros.actions
import launch_ros.substitutions
import launch_testing.actions
import launch_testing.markers
import launch_testing.tools
import rcl_interfaces.srv
import rclpy
def flatten(d, prefix=None):
assert isinstance(d, collections.abc.Mapping)
flat_d = {}
for k, v in d.items():
if prefix is not None:
k = prefix + '.' + k
if isinstance(v, collections.abc.Mapping):
flat_d.update(flatten(v, prefix=k))
else:
flat_d[k] = v
return flat_d
@launch_testing.markers.keep_alive
def generate_test_description():
return launch.LaunchDescription([
launch_testing.actions.ReadyToTest()
])
class TestCmdVelMux(unittest.TestCase):
@classmethod
def setUpClass(
cls,
launch_service,
proc_info,
proc_output
):
@contextlib.contextmanager
def launch_cmd_vel_mux_node(self, *, parameters):
cmd_vel_mux_node_action = launch_ros.actions.Node(
package='cmd_vel_mux',
executable='cmd_vel_mux_node',
name='cmd_vel_mux',
parameters=[parameters],
output='screen'
)
with launch_testing.tools.launch_process(
launch_service, cmd_vel_mux_node_action, proc_info, proc_output
) as node_process:
yield node_process
cls.launch_cmd_vel_mux_node = launch_cmd_vel_mux_node
rclpy.init()
cls._node = rclpy.create_node(
'cmd_vel_mux_testing_node', start_parameter_services=False
)
cls._cmd_vel_mux_set_parameters_client = cls._node.create_client(
rcl_interfaces.srv.SetParametersAtomically,
'/cmd_vel_mux/set_parameters_atomically'
)
def update_cmd_vel_mux_params(self, *, parameters):
self.assertTrue(self._cmd_vel_mux_set_parameters_client.wait_for_service(timeout_sec=5))
request = rcl_interfaces.srv.SetParametersAtomically.Request()
print(flatten(parameters))
request.parameters = [
rclpy.Parameter(name=name, value=value).to_parameter_msg()
for name, value in flatten(parameters).items()
]
future = self._cmd_vel_mux_set_parameters_client.call_async(request)
rclpy.spin_until_future_complete(self._node, future, timeout_sec=5.0)
self.assertTrue(future.done())
response = future.result()
return response.result.successful, response.result.reason
@classmethod
def tearDownClass(cls):
cls._node.destroy_client(cls._cmd_vel_mux_set_parameters_client)
cls._node.destroy_node()
rclpy.shutdown()
def test_no_params(self):
with self.launch_cmd_vel_mux_node(parameters={}) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*WARN.*No subscribers configured!')
], strict=False
), timeout=2))
def test_invalid_subscriber(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_invalid_subscriber': ''
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Invalid parameters.*')
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_invalid_subscriber_params(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_subscriber': {
'topic': 0
}
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Invalid parameters.*')
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_incomplete_params(self):
with self.launch_cmd_vel_mux_node(
parameters={
'subscribers': {
'some_subscriber': {
'topic': 'some_topic',
'priority': 0,
'short_desc': ''
}
}
}
) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*std::runtime_error.*'),
re.compile(r'.*Incomplete parameters.*'),
], strict=False
), timeout=2))
self.assertTrue(node_process.wait_for_shutdown(timeout=2))
self.assertNotEqual(node_process.exit_code, launch_testing.asserts.EXIT_OK)
def test_params_update(self):
with self.launch_cmd_vel_mux_node(parameters={
'subscribers': {
'some_subscriber': {
'topic': 'some_topic',
'priority': 0,
'timeout': 1.0,
'short_desc': 'A dummy description'
}
}
}) as node_process:
self.assertTrue(node_process.wait_for_output(functools.partial(
launch_testing.tools.expect_output, expected_lines=[
re.compile(r'.*CmdVelMux : \(re\)configured.*'),
], strict=False
), timeout=2))
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'some_invalid_subscriber': ''
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Invalid or unknown parameter')
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 'another_topic',
'priority': 0,
'timeout': 0.1,
}
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Incomplete parameters')
ok, reason = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 0,
}
}
})
self.assertFalse(ok)
self.assertEqual(reason, 'Invalid parameter')
ok, _ = self.update_cmd_vel_mux_params(parameters={
'subscribers': {
'another_subscriber': {
'topic': 'another_topic',
'priority': 1,
'timeout': 0.1,
'short_desc': 'Another dummy description'
}
}
})
self.assertTrue(ok)
Submodule ros2_ws/src/ecl_core deleted from 7bcdf80423
+16
View File
@@ -0,0 +1,16 @@
# Compiled Object files
*.slo
*.lo
*.o
# Eclipse
.settings
# Compiled Dynamic libraries
*.so
*.dylib
# Compiled Static libraries
*.lai
*.la
*.a
+32
View File
@@ -0,0 +1,32 @@
# Software License Agreement (BSD License)
#
# Copyright (c) 2022 Daniel Stonier
# 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 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.
+5
View File
@@ -0,0 +1,5 @@
ecl_core
========
A set of tools and interfaces extending the capabilities of c++ to provide a lightweight,
consistent interface with a focus for control programming.
@@ -0,0 +1,338 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1069310076">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1069310076" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="command_line" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1069310076" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1069310076.97404362" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.711160990" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.506759735" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder buildPath="${workspace_loc:${ProjName}}/../../../build/${ProjName}" id="cdt.managedbuild.target.gnu.builder.base.1386481711" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.1422431335" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.143374507" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1927254483" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1076063647" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.1749256354" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.1518170669" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.2122196183" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1000782804" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.977298002" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.954666529" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/ecl"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="command_line.null.646541467" name="command_line"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1069310076;cdt.managedbuild.toolchain.gnu.base.1069310076.97404362;cdt.managedbuild.tool.gnu.c.compiler.base.1076063647;cdt.managedbuild.tool.gnu.c.compiler.input.1749256354">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1069310076;cdt.managedbuild.toolchain.gnu.base.1069310076.97404362;cdt.managedbuild.tool.gnu.cpp.compiler.base.143374507;cdt.managedbuild.tool.gnu.cpp.compiler.input.1927254483">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/ecl_command_line"/>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="all" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>all</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="test" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>test</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
</cproject>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ecl_command_line</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>make</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>true</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,12 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package ecl_command_line
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0.60.8 (2014-02-10)
-------------------
0.60.7 (2014-02-03)
-------------------
0.60.6 (2014-01-29)
-------------------
@@ -0,0 +1,57 @@
##############################################################################
# Cmake
##############################################################################
cmake_minimum_required(VERSION 3.5)
project(ecl_command_line)
##############################################################################
# Ament
##############################################################################
find_package(ament_cmake_ros REQUIRED)
find_package(ecl_build REQUIRED)
##############################################################################
# Project Configuration
##############################################################################
ament_package_xml()
ecl_enable_cxx14_compiler()
ecl_enable_cxx_warnings()
##############################################################################
# Header Library Targets
##############################################################################
add_library(${PROJECT_NAME} INTERFACE)
target_include_directories(
${PROJECT_NAME}
INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
##############################################################################
# Sources
##############################################################################
add_subdirectory(include)
add_subdirectory(src)
##############################################################################
# Exports
##############################################################################
# Downstream CMake3 compatibility
ament_export_targets(${PROJECT_NAME})
# Downstream CMake2 compatibility
ament_export_include_directories(include)
ament_package()
@@ -0,0 +1,111 @@
/**
\mainpage
\htmlinclude manifest.html
\section packageSummary Package Summary
Provides a templatised c++ parser for handling command line arguments.
The templates provide a very flexible manner for handling any type
of input argument.
The code for the command line parser is a simple wrapper around another
template header library called <a href="http://tclap.sourceforge.net/">TCLAP</a>.
Since it is relatively small, its
bundled here in the command_line subdirectory and namespaced
in a convenient manner. Licensing terms (MIT) are included in the
command_line subdirectory (also included as an install target).
@subsection Alternatives
A more complicated, but more flexible alternative
(it allows argument parsing from both command line and configuration
file simultaneously) is the boost::program_options library.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit which
requires this library:
@code
#include <ecl/command_line.hpp>
// Interface classes
using ecl::CmdLine;
using ecl::ArgException
// Argument classes
using ecl::SwitchArg;
using ecl::ValueArg;
using ecl::MultiArg;
using ecl::UnlabeledValueArg;
using ecl::UnlabeledMultiArg; // there are more - see tclap docs
@endcode
Since it is a template header library, no linking is required if you are
only using these classes.
\section usage Usage
@subsection Initialisation
A single object is used to parse the command line. Initialise it with
a few default properties. These will be used to automatically
generate a --help argument.
@code
// Supply a program description, argument separator (optional) and version number (optional).
CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.");
// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01");
@endcode
@subsection ArgumentsSection Adding Arguments
@code
// Add a boolean (flag, name, description, default)
SwitchArg debug("d","debug","Enable debugging.", false);
cmd.add(debug);
// Add an int (flag,name,description,compulsory flag,default value,help description of the type")
ValueArg<int> intArg("i","integer","An integer argument for testing.",false,5,"integer");
// Not a regular option (name,description,compulsory flag,default value,help description of the type")
UnlabeledValueArg<std::string> outputDirArg("output_dir","Output directory for rectified images.",true,"./rectified","string");
cmd.add(intArg);
@endcode
Valid argument types include
- @ref ecl::SwitchArg "SwitchArg" : simple boolean.
- @ref ecl::ValueArg "ValueArg" : expect some value on the command line.
- @ref ecl::MultiArg "MultiArg" : permit multiple values for an argument which get stored in a vector.
- @ref ecl::MultiSwitchArg "MultiSwitchArg" : as above, but for booleans, not often used so see TCLAP for more instructions.
- @ref ecl::UnlabeledValueArg "UnlabeledValueArg" : does not use a flag (like the arguments for copy), order is important!
- @ref ecl::UnlabeledMultiArg "UnlabeledMultiArg" : reads in all remaining unlabelled args (like rm file1.txt file2.txt etc.)
@subsection customArgumentsSection Custom Arguments
Custom ValueArg types can be used so long as they implement the >> operator.
@section extraHelp Further Help (TCLAP)
Most of tclap's doxygen is generated automatically inside the ecl. For more detailed
documentation, read the <a href="http://tclap.sourceforge.net/manual.html">manual</a> at
tclap's home page.
\section unitTests Unit Tests
- src/test/command_line.cpp
\section examples Examples
- src/examples/command_line.cpp
\section ChangeLog
- <b>May 09</b> : wrapper for the tclap headers written.
- <b>May 09</b> : initial import of the tclap headers.
@section Errata
Now it's in the ros, at some point in the future I will unwind this back to the original package since it no longer needs
to be embedded in the ecl.
*/
@@ -0,0 +1,22 @@
/**
* @namespace ecl::command_line
*
* @brief Command line parsing classes.
*
* Cross-platform collection of tools for command line parsing. It has been
* built as a wrapper around the TCLAP template library.
**/
/*
* @namespace ecl::command_line::MultiArgHelper
*
* @brief Collection of utilities and tools for multiple argument handling in tclap.
*
* Collection of utilities and tools for multiple argument handling in tclap.
*/
/*
* @namespace ecl::command_line::ValueArgHelper
*
* @brief Collection of utilities and tools for value argument handling in tclap.
*
* Collection of utilities and tools for value argument handling in tclap.
*/
@@ -0,0 +1,5 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(ecl)
@@ -0,0 +1,14 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(command_line)
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl)
@@ -0,0 +1,25 @@
/**
* @file /include/ecl/command_line.hpp
*
* @brief Parsing command line arguments.
*
* Uses a c++ library called TCLAP (MIT license) to provide command
* line parsing for the ECL.
*
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CMD_LINE_HPP_
#define ECL_CMD_LINE_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "command_line/cmd_line.hpp"
#endif /*ECL_CMD_LINE_HPP_*/
@@ -0,0 +1,7 @@
###############################################################################
# FILES
###############################################################################
FILE(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
INSTALL(FILES ${HEADERS} DESTINATION include/ecl/command_line)
@@ -0,0 +1,580 @@
/**
* @file /include/ecl/command_line/arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_ARGUMENT_H
#define TCLAP_ARGUMENT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include "arg_exception.hpp"
#include "visitor.hpp"
#include "cmd_line_interface.hpp"
namespace ecl {
/**
* @brief Virtual parent for all the different argument classes.
*
* A virtual base class that defines the essential data for all arguments.
* This class, or one of its existing children, must be subclassed to do
* anything.
*/
class Arg
{
private:
/**
* Indicates whether the rest of the arguments should be ignored.
*/
static bool& ignoreRestRef() { static bool ign = false; return ign; }
/**
* The delimiter that separates an argument flag/name from the
* value.
*/
static char& delimiterRef() { static char delim = ' '; return delim; }
protected:
/**
* The single char flag used to identify the argument.
* This value (preceded by a dash {-}), can be used to identify
* an argument on the command line. The _flag can be blank,
* in fact this is how unlabeled args work. Unlabeled args must
* override appropriate functions to get correct handling. Note
* that the _flag does NOT include the dash as part of the flag.
*/
std::string _flag;
/**
* A single work namd indentifying the argument.
* This value (preceded by two dashed {--}) can also be used
* to identify an argument on the command line. Note that the
* _name does NOT include the two dashes as part of the _name. The
* _name cannot be blank.
*/
std::string _name;
/**
* Description of the argument.
*/
std::string _description;
/**
* Indicating whether the argument is required.
*/
bool _required;
/**
* Label to be used in usage description. Normally set to
* "required", but can be changed when necessary.
*/
std::string _requireLabel;
/**
* Indicates whether a value is required for the argument.
* Note that the value may be required but the argument/value
* combination may not be, as specified by _required.
*/
bool _valueRequired;
/**
* Indicates whether the argument has been set.
* Indicates that a value on the command line has matched the
* name/flag of this argument and the values have been set accordingly.
*/
bool _alreadySet;
/**
* A pointer to a vistitor object.
* The visitor allows special handling to occur as soon as the
* argument is matched. This defaults to NULL and should not
* be used unless absolutely necessary.
*/
Visitor* _visitor;
/**
* Whether this argument can be ignored, if desired.
*/
bool _ignoreable;
/**
* Indicates that the arg was set as part of an XOR and not on the
* command line.
*/
bool _xorSet;
bool _acceptsMultipleValues;
/**
* Performs the special handling described by the Vistitor.
*/
void _checkWithVisitor() const;
/**
* Primary constructor. YOU (yes you) should NEVER construct an Arg
* directly, this is a base class that is extended by various children
* that are meant to be used. Use SwitchArg, ValueArg, MultiArg,
* UnlabeledValueArg, or UnlabeledMultiArg instead.
*
* \param flag - The flag identifying the argument.
* \param name - The name identifying the argument.
* \param desc - The description of the argument, used in the usage.
* \param req - Whether the argument is required.
* \param valreq - Whether the a value is required for the argument.
* \param v - The visitor checked by the argument. Defaults to NULL.
*/
Arg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v = NULL );
public:
/**
* Destructor.
*/
virtual ~Arg();
/**
* Adds this to the specified list of Args.
* \param argList - The list to add this to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
/**
* Begin ignoring arguments since the "--" argument was specified.
*/
static void beginIgnoring() { ignoreRestRef() = true; }
/**
* Whether to ignore the rest.
*/
static bool ignoreRest() { return ignoreRestRef(); }
/**
* The delimiter that separates an argument flag/name from the
* value.
*/
static char delimiter() { return delimiterRef(); }
/**
* The char used as a place holder when SwitchArgs are combined.
* Currently set to '*', which shouldn't cause many problems since
* *'s are expanded by most shells on the command line.
*/
static char blankChar() { return '*'; }
/**
* The char that indicates the beginning of a flag. Currently '-'.
*/
static char flagStartChar() { return '-'; }
/**
* The sting that indicates the beginning of a flag. Currently "-".
* Should be identical to flagStartChar.
*/
static std::string flagStartString() { return "-"; }
/**
* The sting that indicates the beginning of a name. Currently "--".
* Should be flagStartChar twice.
*/
static std::string nameStartString() { return "--"; }
/**
* The name used to identify the ignore rest argument.
*/
static std::string ignoreNameString() { return "ignore_rest"; }
/**
* Sets the delimiter for all arguments.
* \param c - The character that delimits flags/names from values.
*/
static void setDelimiter( char c ) { delimiterRef() = c; }
/**
* Pure virtual method meant to handle the parsing and value assignment
* of the string on the command line.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. What is
* passed in from main.
*/
virtual bool processArg(int *i, std::vector<std::string>& args) = 0;
/**
* Operator ==.
* Equality operator. Must be virtual to handle unlabeled args.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg& a) const;
/**
* Returns the argument flag.
*/
const std::string& getFlag() const;
/**
* Returns the argument name.
*/
const std::string& getName() const;
/**
* Returns the argument description.
*/
std::string getDescription() const;
/**
* Indicates whether the argument is required.
*/
virtual bool isRequired() const;
/**
* Sets _required to true. This is used by the XorHandler.
* You really have no reason to ever use it.
*/
void forceRequired();
/**
* Sets the _alreadySet value to true. This is used by the XorHandler.
* You really have no reason to ever use it.
*/
void xorSet();
/**
* Indicates whether a value must be specified for argument.
*/
bool isValueRequired() const;
/**
* Indicates whether the argument has already been set. Only true
* if the arg has been matched on the command line.
*/
bool isSet() const;
/**
* Indicates whether the argument can be ignored, if desired.
*/
bool isIgnoreable() const;
/**
* A method that tests whether a string matches this argument.
* This is generally called by the processArg() method. This
* method could be re-implemented by a child to change how
* arguments are specified on the command line.
* \param s - The string to be compared to the flag/name to determine
* whether the arg matches.
*/
virtual bool argMatches( const std::string& s ) const;
/**
* Returns a simple string representation of the argument.
* Primarily for debugging.
*/
virtual std::string toString() const;
/**
* Returns a short ID for the usage.
* \param valueId - The value used in the id.
*/
virtual std::string shortID( const std::string& valueId = "val" ) const;
/**
* Returns a long ID for the usage.
* \param valueId - The value used in the id.
*/
virtual std::string longID( const std::string& valueId = "val" ) const;
/**
* Trims a value off of the flag.
* \param flag - The string from which the flag and value will be
* trimmed. Contains the flag once the value has been trimmed.
* \param value - Where the value trimmed from the string will
* be stored.
*/
virtual void trimFlag( std::string& flag, std::string& value ) const;
/**
* Checks whether a given string has blank chars, indicating that
* it is a combined SwitchArg. If so, return true, otherwise return
* false.
* \param s - string to be checked.
*/
bool _hasBlanks( const std::string& s ) const;
/**
* Sets the requireLabel. Used by XorHandler. You shouldn't ever
* use this.
* \param s - Set the requireLabel to this value.
*/
void setRequireLabel( const std::string& s );
virtual bool allowMore();
virtual bool acceptsMultipleValues();
};
/**
* Typedef of an Arg list iterator.
*/
typedef std::list<Arg*>::iterator ArgListIterator;
/**
* Typedef of an Arg vector iterator.
*/
typedef std::vector<Arg*>::iterator ArgVectorIterator;
/**
* Typedef of a Visitor list iterator.
*/
typedef std::list<Visitor*>::iterator VisitorListIterator;
//////////////////////////////////////////////////////////////////////
//BEGIN Arg.cpp
//////////////////////////////////////////////////////////////////////
inline Arg::Arg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
bool valreq,
Visitor* v) :
_flag(flag),
_name(name),
_description(desc),
_required(req),
_requireLabel("required"),
_valueRequired(valreq),
_alreadySet(false),
_visitor( v ),
_ignoreable(true),
_xorSet(false),
_acceptsMultipleValues(false)
{
if ( _flag.length() > 1 )
throw(SpecificationException(
"Argument flag can only be one character long", toString() ) );
if ( _name != ignoreNameString() &&
( _flag == Arg::flagStartString() ||
_flag == Arg::nameStartString() ||
_flag == " " ) )
throw(SpecificationException("Argument flag cannot be either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or a space.",
toString() ) );
if ( ( _name.find( Arg::flagStartString(), 0 ) != std::string::npos ) ||
( _name.find( Arg::nameStartString(), 0 ) != std::string::npos ) ||
( _name.find( " ", 0 ) != std::string::npos ) )
throw(SpecificationException("Argument name cannot contain either '" +
Arg::flagStartString() + "' or '" +
Arg::nameStartString() + "' or space.",
toString() ) );
}
inline Arg::~Arg() { }
inline std::string Arg::shortID( const std::string& valueId ) const
{
std::string id = "";
if ( _flag != "" )
id = Arg::flagStartString() + _flag;
else
id = Arg::nameStartString() + _name;
std::string delim = " ";
delim[0] = Arg::delimiter(); // ugly!!!
if ( _valueRequired )
id += delim + "<" + valueId + ">";
if ( !_required )
id = "[" + id + "]";
return id;
}
inline std::string Arg::longID( const std::string& valueId ) const
{
std::string id = "";
if ( _flag != "" )
{
id += Arg::flagStartString() + _flag;
if ( _valueRequired )
id += " <" + valueId + ">";
id += ", ";
}
id += Arg::nameStartString() + _name;
if ( _valueRequired )
id += " <" + valueId + ">";
return id;
}
inline bool Arg::operator==(const Arg& a) const
{
if ( ( _flag != "" && _flag == a._flag ) || _name == a._name)
return true;
else
return false;
}
inline std::string Arg::getDescription() const
{
std::string desc = "";
if ( _required )
desc = "(" + _requireLabel + ") ";
// if ( _valueRequired )
// desc += "(value required) ";
desc += _description;
return desc;
}
inline const std::string& Arg::getFlag() const { return _flag; }
inline const std::string& Arg::getName() const { return _name; }
inline bool Arg::isRequired() const { return _required; }
inline bool Arg::isValueRequired() const { return _valueRequired; }
inline bool Arg::isSet() const
{
if ( _alreadySet && !_xorSet )
return true;
else
return false;
}
inline bool Arg::isIgnoreable() const { return _ignoreable; }
inline void Arg::setRequireLabel( const std::string& s)
{
_requireLabel = s;
}
inline bool Arg::argMatches( const std::string& argFlag ) const
{
if ( ( argFlag == Arg::flagStartString() + _flag && _flag != "" ) ||
argFlag == Arg::nameStartString() + _name )
return true;
else
return false;
}
inline std::string Arg::toString() const
{
std::string s = "";
if ( _flag != "" )
s += Arg::flagStartString() + _flag + " ";
s += "(" + Arg::nameStartString() + _name + ")";
return s;
}
inline void Arg::_checkWithVisitor() const
{
if ( _visitor != NULL )
_visitor->visit();
}
/**
* Implementation of trimFlag.
*/
inline void Arg::trimFlag(std::string& flag, std::string& value) const
{
int stop = 0;
for ( int i = 0; static_cast<unsigned int>(i) < flag.length(); i++ )
if ( flag[i] == Arg::delimiter() )
{
stop = i;
break;
}
if ( stop > 1 )
{
value = flag.substr(stop+1);
flag = flag.substr(0,stop);
}
}
/**
* Implementation of _hasBlanks.
*/
inline bool Arg::_hasBlanks( const std::string& s ) const
{
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
if ( s[i] == Arg::blankChar() )
return true;
return false;
}
inline void Arg::forceRequired()
{
_required = true;
}
inline void Arg::xorSet()
{
_alreadySet = true;
_xorSet = true;
}
/**
* Overridden by Args that need to added to the end of the list.
*/
inline void Arg::addToList( std::list<Arg*>& argList ) const
{
argList.push_front( const_cast<Arg*>(this) );
}
inline bool Arg::allowMore()
{
return false;
}
inline bool Arg::acceptsMultipleValues()
{
return _acceptsMultipleValues;
}
//////////////////////////////////////////////////////////////////////
//END Arg.cpp
//////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,191 @@
/**
* @file /include/ecl/command_line/arg_exception.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_ARG_EXCEPTION_H
#define TCLAP_ARG_EXCEPTION_H
#include <string>
#include <exception>
namespace ecl {
/**
* @brief Defines the exception that is thrown whenever a command line is created and parsed.
*
* A simple class that defines an argument exception. Should be caught
* whenever a CmdLine is created and parsed.
*/
class ArgException : public std::exception
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source.
* \param td - Text describing the type of ArgException it is.
* of the exception.
*/
ArgException( const std::string& text = "undefined exception",
const std::string& id = "undefined",
const std::string& td = "Generic ArgException")
: std::exception(),
_errorText(text),
_argId( id ),
_typeDescription(td)
{ }
/**
* Destructor.
*/
virtual ~ArgException() throw() { }
/**
* Returns the error text.
*/
std::string error() const { return ( _errorText ); }
/**
* Returns the argument id.
*/
std::string argId() const
{
if ( _argId == "undefined" )
return " ";
else
return ( "Argument: " + _argId );
}
/**
* Returns the arg id and error text.
*/
const char* what() const throw()
{
static std::string ex;
ex = _argId + " -- " + _errorText;
return ex.c_str();
}
/**
* Returns the type of the exception. Used to explain and distinguish
* between different child exceptions.
*/
std::string typeDescription() const
{
return _typeDescription;
}
private:
/**
* The text of the exception message.
*/
std::string _errorText;
/**
* The argument related to this exception.
*/
std::string _argId;
/**
* Describes the type of the exception. Used to distinguish
* between different child exceptions.
*/
std::string _typeDescription;
};
/**
* @brief Defines the exception that is thrown when an argument is improperly parsed.
*
* Thrown from within the child Arg classes when it fails to properly
* parse the argument it has been passed.
*/
class ArgParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
ArgParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found while parsing " ) +
std::string( "the value the Arg has been passed." ))
{ }
};
/**
* @brief Defines the exception when an argument is improperly specified.
*
* Thrown from CmdLine when the arguments on the command line are not
* properly specified, e.g. too many arguments, required argument missing, etc.
*/
class CmdLineParseException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
CmdLineParseException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string( "Exception found when the values ") +
std::string( "on the command line do not meet ") +
std::string( "the requirements of the defined ") +
std::string( "Args." ))
{ }
};
/**
* @brief Defines the exception that is thrown whenever a conflict in arguments occurs.
*
* Thrown from Arg and CmdLine when an Arg is improperly specified, e.g.
* same flag as another Arg, same name, etc.
*/
class SpecificationException : public ArgException
{
public:
/**
* Constructor.
* \param text - The text of the exception.
* \param id - The text identifying the argument source
* of the exception.
*/
SpecificationException( const std::string& text = "undefined exception",
const std::string& id = "undefined" )
: ArgException( text,
id,
std::string("Exception found when an Arg object ")+
std::string("is improperly defined by the ") +
std::string("developer." ))
{ }
};
} // namespace ecl
#endif
@@ -0,0 +1,489 @@
/**
* @file /include/ecl/command_line/cmd_line.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CMDLINE_H
#define TCLAP_CMDLINE_H
#include "switch_arg.hpp"
#include "multi_switch_arg.hpp"
#include "unlabeled_value_arg.hpp"
#include "unlabeled_multi_arg.hpp"
#include "xor_handler.hpp"
#include "help_visitor.hpp"
#include "version_visitor.hpp"
#include "ignore_rest_visitor.hpp"
#include "cmd_line_output.hpp"
#include "std_output.hpp"
#include "constraint.hpp"
#include "values_constraint.hpp"
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
/**
* @brief Manages the command line parsing object.
*
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLine : public CmdLineInterface
{
protected:
/**
* The list of arguments that will be tested against the
* command line.
*/
std::list<Arg*> _argList;
/**
* The name of the program. Set to argv[0].
*/
std::string _progName;
/**
* A message used to describe the program. Used in the usage output.
*/
std::string _message;
/**
* The version to be displayed with the --version switch.
*/
std::string _version;
/**
* The number of arguments that are required to be present on
* the command line. This is set dynamically, based on the
* Args added to the CmdLine object.
*/
int _numRequired;
/**
* The character that is used to separate the argument flag/name
* from the value. Defaults to ' ' (space).
*/
char _delimiter;
/**
* The handler that manages xoring lists of args.
*/
XorHandler _xorHandler;
/**
* A list of Args to be explicitly deleted when the destructor
* is called. At the moment, this only includes the three default
* Args.
*/
std::list<Arg*> _argDeleteOnExitList;
/**
* A list of Visitors to be explicitly deleted when the destructor
* is called. At the moment, these are the Vistors created for the
* default Args.
*/
std::list<Visitor*> _visitorDeleteOnExitList;
/**
* Object that handles all output for the CmdLine.
*/
CmdLineOutput* _output;
/**
* Checks whether a name/flag string matches entirely matches
* the Arg::blankChar. Used when multiple switches are combined
* into a single argument.
* \param s - The message to be used in the usage.
*/
bool _emptyCombined(const std::string& s);
/**
* Perform a delete ptr; operation on ptr when this object is deleted.
*/
void deleteOnExit(Arg* ptr);
/**
* Perform a delete ptr; operation on ptr when this object is deleted.
*/
void deleteOnExit(Visitor* ptr);
private:
/**
* Encapsulates the code common to the constructors (which is all
* of it).
*/
void _constructor();
/**
* Is set to true when a user sets the output object. We use this so
* that we don't delete objects that are created outside of this lib.
*/
bool _userSetOutput;
/**
* Whether or not to automatically create help and version switches.
*/
bool _helpAndVersion;
public:
/**
* Command line constructor. Defines how the arguments will be
* parsed.
* \param message - The message to be used in the usage
* output.
* \param delimiter - The character that is used to separate
* the argument flag/name from the value. Defaults to ' ' (space).
* \param version - The version number to be used in the
* --version switch.
* \param helpAndVersion - Whether or not to create the Help and
* Version switches. Defaults to true.
*/
CmdLine(const std::string& message,
const char delimiter = ' ',
const std::string& version = "none",
bool helpAndVersion = true);
/**
* Deletes any resources allocated by a CmdLine object.
*/
virtual ~CmdLine();
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
void add( Arg& a );
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
void add( Arg* a );
/**
* Add two Args that will be xor'd. If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
void xorAdd( Arg& a, Arg& b );
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
void xorAdd( std::vector<Arg*>& xors );
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
void parse(int argc, char** argv);
/**
*
*/
CmdLineOutput* getOutput();
/**
*
*/
void setOutput(CmdLineOutput* co);
/**
*
*/
std::string& getVersion();
/**
*
*/
std::string& getProgramName();
/**
*
*/
std::list<Arg*>& getArgList();
/**
*
*/
XorHandler& getXorHandler();
/**
*
*/
char getDelimiter();
/**
*
*/
std::string& getMessage();
/**
*
*/
bool hasHelpAndVersion();
};
///////////////////////////////////////////////////////////////////////////////
//Begin CmdLine.cpp
///////////////////////////////////////////////////////////////////////////////
inline CmdLine::CmdLine(const std::string& m,
char delim,
const std::string& v,
bool help )
: _progName("not_set_yet"),
_message(m),
_version(v),
_numRequired(0),
_delimiter(delim),
_userSetOutput(false),
_helpAndVersion(help)
{
_constructor();
}
inline CmdLine::~CmdLine()
{
ArgListIterator argIter;
VisitorListIterator visIter;
for( argIter = _argDeleteOnExitList.begin();
argIter != _argDeleteOnExitList.end();
++argIter)
delete *argIter;
for( visIter = _visitorDeleteOnExitList.begin();
visIter != _visitorDeleteOnExitList.end();
++visIter)
delete *visIter;
if ( !_userSetOutput )
delete _output;
}
inline void CmdLine::_constructor()
{
_output = new StdOutput;
Arg::setDelimiter( _delimiter );
Visitor* v;
if ( _helpAndVersion )
{
v = new HelpVisitor( this, &_output );
SwitchArg* help = new SwitchArg("h","help",
"Displays usage information and exits.",
false, v);
add( help );
deleteOnExit(help);
deleteOnExit(v);
v = new VersionVisitor( this, &_output );
SwitchArg* vers = new SwitchArg("","version",
"Displays version information and exits.",
false, v);
add( vers );
deleteOnExit(vers);
deleteOnExit(v);
}
v = new IgnoreRestVisitor();
SwitchArg* ignore = new SwitchArg(Arg::flagStartString(),
Arg::ignoreNameString(),
"Ignores the rest of the labeled arguments following this flag.",
false, v);
add( ignore );
deleteOnExit(ignore);
deleteOnExit(v);
}
inline void CmdLine::xorAdd( std::vector<Arg*>& ors )
{
_xorHandler.add( ors );
for (ArgVectorIterator it = ors.begin(); it != ors.end(); it++)
{
(*it)->forceRequired();
(*it)->setRequireLabel( "OR required" );
add( *it );
}
}
inline void CmdLine::xorAdd( Arg& a, Arg& b )
{
std::vector<Arg*> ors;
ors.push_back( &a );
ors.push_back( &b );
xorAdd( ors );
}
inline void CmdLine::add( Arg& a )
{
add( &a );
}
inline void CmdLine::add( Arg* a )
{
for( ArgListIterator it = _argList.begin(); it != _argList.end(); it++ )
if ( *a == *(*it) )
throw( SpecificationException(
"Argument with same flag/name already exists!",
a->longID() ) );
a->addToList( _argList );
if ( a->isRequired() )
_numRequired++;
}
inline void CmdLine::parse(int argc, char** argv)
{
try {
_progName = argv[0];
// this step is necessary so that we have easy access to mutable strings.
std::vector<std::string> args;
for (int i = 1; i < argc; i++)
args.push_back(argv[i]);
int requiredCount = 0;
for (int i = 0; static_cast<unsigned int>(i) < args.size(); i++)
{
bool matched = false;
for (ArgListIterator it = _argList.begin(); it != _argList.end(); it++)
{
if ( (*it)->processArg( &i, args ) )
{
requiredCount += _xorHandler.check( *it );
matched = true;
break;
}
}
// checks to see if the argument is an empty combined switch ...
// and if so, then we've actually matched it
if ( !matched && _emptyCombined( args[i] ) )
matched = true;
if ( !matched && !Arg::ignoreRest() )
throw(CmdLineParseException("Couldn't find match for argument",
args[i]));
}
if ( requiredCount < _numRequired )
throw(CmdLineParseException("One or more required arguments missing!"));
if ( requiredCount > _numRequired )
throw(CmdLineParseException("Too many arguments!"));
} catch ( ArgException &e ) {
_output->failure(*this, e); exit(1);
}
}
inline bool CmdLine::_emptyCombined(const std::string& s)
{
if ( s[0] != Arg::flagStartChar() )
return false;
for ( int i = 1; static_cast<unsigned int>(i) < s.length(); i++ )
if ( s[i] != Arg::blankChar() )
return false;
return true;
}
inline void CmdLine::deleteOnExit(Arg* ptr)
{
_argDeleteOnExitList.push_back(ptr);
}
inline void CmdLine::deleteOnExit(Visitor* ptr)
{
_visitorDeleteOnExitList.push_back(ptr);
}
inline CmdLineOutput* CmdLine::getOutput()
{
return _output;
}
inline void CmdLine::setOutput(CmdLineOutput* co)
{
_userSetOutput = true;
_output = co;
}
inline std::string& CmdLine::getVersion()
{
return _version;
}
inline std::string& CmdLine::getProgramName()
{
return _progName;
}
inline std::list<Arg*>& CmdLine::getArgList()
{
return _argList;
}
inline XorHandler& CmdLine::getXorHandler()
{
return _xorHandler;
}
inline char CmdLine::getDelimiter()
{
return _delimiter;
}
inline std::string& CmdLine::getMessage()
{
return _message;
}
inline bool CmdLine::hasHelpAndVersion()
{
return _helpAndVersion;
}
///////////////////////////////////////////////////////////////////////////////
//End CmdLine.cpp
///////////////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,130 @@
/**
* @file /include/ecl/command_line/cmd_line_interface.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_COMMANDLINE_INTERFACE_H
#define TCLAP_COMMANDLINE_INTERFACE_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
namespace ecl {
class Arg;
class CmdLineOutput;
class XorHandler;
/**
* @brief Managing interface for
* The base class that manages the command line definition and passes
* along the parsing to the appropriate Arg classes.
*/
class CmdLineInterface
{
public:
/**
* Destructor
*/
virtual ~CmdLineInterface() {}
/**
* Adds an argument to the list of arguments to be parsed.
* \param a - Argument to be added.
*/
virtual void add( Arg& a )=0;
/**
* An alternative add. Functionally identical.
* \param a - Argument to be added.
*/
virtual void add( Arg* a )=0;
/**
* Add two Args that will be xor'd.
* If this method is used, add does
* not need to be called.
* \param a - Argument to be added and xor'd.
* \param b - Argument to be added and xor'd.
*/
virtual void xorAdd( Arg& a, Arg& b )=0;
/**
* Add a list of Args that will be xor'd. If this method is used,
* add does not need to be called.
* \param xors - List of Args to be added and xor'd.
*/
virtual void xorAdd( std::vector<Arg*>& xors )=0;
/**
* Parses the command line.
* \param argc - Number of arguments.
* \param argv - Array of arguments.
*/
virtual void parse(int argc, char** argv)=0;
/**
* Returns the CmdLineOutput object.
*/
virtual CmdLineOutput* getOutput()=0;
/**
* \param co - CmdLineOutput object that we want to use instead.
*/
virtual void setOutput(CmdLineOutput* co)=0;
/**
* Returns the version string.
*/
virtual std::string& getVersion()=0;
/**
* Returns the program name string.
*/
virtual std::string& getProgramName()=0;
/**
* Returns the argList.
*/
virtual std::list<Arg*>& getArgList()=0;
/**
* Returns the XorHandler.
*/
virtual XorHandler& getXorHandler()=0;
/**
* Returns the delimiter string.
*/
virtual char getDelimiter()=0;
/**
* Returns the message string.
*/
virtual std::string& getMessage()=0;
/**
* Indicates whether or not the help and version switches were created
* automatically.
*/
virtual bool hasHelpAndVersion()=0;
};
} // namespace ecl
#endif
@@ -0,0 +1,69 @@
/**
* @file /include/ecl/command_line/cmd_line_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CMDLINEOUTPUT_H
#define TCLAP_CMDLINEOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
class CmdLineInterface;
class ArgException;
/**
* @brief Tclap class indirectly used by children for standardising outputs.
*
* The interface that any output object must implement.
*/
class CmdLineOutput
{
public:
/**
* Virtual destructor.
*/
virtual ~CmdLineOutput() {}
/**
* Generates some sort of output for the USAGE.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c)=0;
/**
* Generates some sort of output for the version.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c)=0;
/**
* Generates some sort of output for a failure.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure( CmdLineInterface& c,
ArgException& e )=0;
};
} // namespace ecl
#endif
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/command_line/constraint.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_CONSTRAINT_H
#define TCLAP_CONSTRAINT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <iomanip>
#include <algorithm>
namespace ecl {
/**
* @brief Defines the interaction between an argument and a constraint.
*
* The interface that defines the interaction between the Arg and Constraint.
*/
template<class T>
class Constraint
{
public:
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const =0;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const =0;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T& value) const =0;
/**
* Destructor.
* Silences warnings about Constraint being a base class with virtual
* functions but without a virtual destructor.
*/
virtual ~Constraint() { ; }
};
} // namespace ecl
#endif
@@ -0,0 +1,270 @@
/**
* @file /include/ecl/command_line/docbook_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_DOCBOOKOUTPUT_H
#define TCLAP_DOCBOOKOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "xor_handler.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class used for generating docbook output.
*
* A class that generates DocBook output for usage() method for the
* given CmdLine and its Args.
*/
class DocBookOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Substitutes the char r for string x in string s.
* \param s - The string to operate on.
* \param r - The char to replace.
* \param x - What to replace r with.
*/
void substituteSpecialChars( std::string& s, char r, std::string& x );
void removeChar( std::string& s, char r);
void printShortArg(Arg* it);
void printLongArg(Arg* it);
};
inline void DocBookOutput::version(CmdLineInterface& _cmd)
{
std::cout << _cmd.getVersion() << std::endl;
}
inline void DocBookOutput::usage(CmdLineInterface& _cmd )
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
std::string version = _cmd.getVersion();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
std::cout << "<?xml version='1.0'?>" << std::endl;
std::cout << "<!DOCTYPE book PUBLIC \"-//Norman Walsh//DTD DocBk XML V4.2//EN\"" << std::endl;
std::cout << "\t\"http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd\">" << std::endl << std::endl;
std::cout << "<book>" << std::endl;
std::cout << "<refentry>" << std::endl;
std::cout << "<refmeta>" << std::endl;
std::cout << "<refentrytitle>" << std::endl;
std::cout << progName << std::endl;
std::cout << "</refentrytitle>" << std::endl;
std::cout << "<manvolnum>1</manvolnum>" << std::endl;
std::cout << "</refmeta>" << std::endl;
std::cout << "<refnamediv>" << std::endl;
std::cout << "<refname>" << std::endl;
std::cout << progName << std::endl;
std::cout << "</refname>" << std::endl;
std::cout << "</refnamediv>" << std::endl;
std::cout << "<cmdsynopsis>" << std::endl;
std::cout << "<command>" << progName << "</command>" << std::endl;
// xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
{
std::cout << "<group choice='req'>" << std::endl;
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
printShortArg((*it));
std::cout << "</group>" << std::endl;
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
printShortArg((*it));
std::cout << "</cmdsynopsis>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Description</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << _cmd.getMessage() << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Options</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << "<itemizedlist>" << std::endl;
// xor
for ( int i = 0; (unsigned int)i < xorList.size(); i++ )
{
std::cout << "<itemizedlist>" << std::endl;
size_t xlen = xorList.size() - 1;
size_t xcount = 0;
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++, xcount++ )
{
printLongArg((*it));
if ( xcount < xlen )
std::cout << "<listitem>OR</listitem>" << std::endl;
}
std::cout << "</itemizedlist>" << std::endl;
}
// rest of args
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
printLongArg((*it));
std::cout << "</itemizedlist>" << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "<refsect1>" << std::endl;
std::cout << "<title>Version</title>" << std::endl;
std::cout << "<para>" << std::endl;
std::cout << version << std::endl;
std::cout << "</para>" << std::endl;
std::cout << "</refsect1>" << std::endl;
std::cout << "</refentry>" << std::endl;
std::cout << "</book>" << std::endl;
}
inline void DocBookOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
std::cout << e.what() << std::endl;
}
inline void DocBookOutput::substituteSpecialChars( std::string& s,
char r,
std::string& x )
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
{
s.erase(p,1);
s.insert(p,x);
}
}
inline void DocBookOutput::removeChar( std::string& s, char r)
{
size_t p;
while ( (p = s.find_first_of(r)) != std::string::npos )
{
s.erase(p,1);
}
}
inline void DocBookOutput::printShortArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->shortID();
substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'>',gt);
removeChar(id,'[');
removeChar(id,']');
std::string choice = "opt";
if ( a->isRequired() )
choice = "req";
std::string repeat = "norepeat";
if ( a->acceptsMultipleValues() )
repeat = "repeat";
std::cout << "<arg choice='" << choice
<< "' repeat='" << repeat << "'>"
<< id << "</arg>" << std::endl;
}
inline void DocBookOutput::printLongArg(Arg* a)
{
std::string lt = "&lt;";
std::string gt = "&gt;";
std::string id = a->longID();
substituteSpecialChars(id,'<',lt);
substituteSpecialChars(id,'>',gt);
removeChar(id,'[');
removeChar(id,']');
std::string desc = a->getDescription();
substituteSpecialChars(desc,'<',lt);
substituteSpecialChars(desc,'>',gt);
std::cout << "<simplelist>" << std::endl;
std::cout << "<member>" << std::endl;
std::cout << id << std::endl;
std::cout << "</member>" << std::endl;
std::cout << "<member>" << std::endl;
std::cout << desc << std::endl;
std::cout << "</member>" << std::endl;
std::cout << "</simplelist>" << std::endl;
}
} // namespace ecl
#endif
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/command_line/help_visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_HELP_VISITOR_H
#define TCLAP_HELP_VISITOR_H
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "visitor.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A Visitor object that calls the usage method of the given CmdLineOutput
* object for the specified CmdLine object.
*/
class HelpVisitor: public Visitor
{
protected:
/**
* The CmdLine the output will be generated for.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* Constructor.
* \param cmd - The CmdLine the output will be generated for.
* \param out - The type of output.
*/
HelpVisitor(CmdLineInterface* cmd, CmdLineOutput** out)
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* Calls the usage method of the CmdLineOutput for the
* specified CmdLine.
*/
void visit() { (*_out)->usage(*_cmd); exit(0); }
};
} // namespace ecl
#endif
@@ -0,0 +1,48 @@
/**
* @file /include/ecl/command_line/ignore_rest_visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_IGNORE_REST_VISITOR_H
#define TCLAP_IGNORE_REST_VISITOR_H
#include "visitor.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A Vistor that tells the CmdLine to begin ignoring arguments after
* this one is parsed.
*/
class IgnoreRestVisitor: public Visitor
{
public:
/**
* Constructor.
*/
IgnoreRestVisitor() : Visitor() {}
/**
* Sets Arg::_ignoreRest.
*/
void visit() { Arg::beginIgnoring(); }
};
} // namespace ecl
#endif
@@ -0,0 +1,520 @@
/**
* @file /include/ecl/command_line/multi_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_MULTIPLE_ARGUMENT_H
#define TCLAP_MULTIPLE_ARGUMENT_H
#include <string>
#include <vector>
#include <cstdio>
#include "arg.hpp"
#include "constraint.hpp"
#define HAVE_SSTREAM
#if defined(HAVE_SSTREAM)
#include <sstream>
#elif defined(HAVE_STRSTREAM)
#include <strstream>
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
namespace ecl {
template<class T> class MultiArg;
namespace MultiArgHelper {
enum Error_e { EXTRACT_FAILURE = 1000, EXTRACT_TOO_MANY };
/**
* @brief TClap class internally used for extracting value args.
*
* This class is used to extract a value from an argument.
* It is used because we need a special implementation to
* deal with std::string and making a specialiced function
* puts it in the T segment, thus generating link errors.
* Having a specialiced class makes the symbols weak.
* This is not pretty but I don't know how to make it
* work any other way.
*/
template<class T>
class ValueExtractor
{
friend class MultiArg<T>;
private:
/**
* Reference to the vector of values where the result of the
* extraction will be put.
*/
std::vector<T> &_values;
/**
* Constructor.
* \param values - Where the values extracted will be put.
*/
ValueExtractor(std::vector<T> &values) : _values(values) {}
/**
* Method that will attempt to parse the input stream for values
* of type T.
* \param val - Where the values parsed will be put.
*/
int extractValue( const std::string& val )
{
T temp;
#if defined(HAVE_SSTREAM)
std::istringstream is(val);
#elif defined(HAVE_STRSTREAM)
std::istrstream is(val.c_str());
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
int valuesRead = 0;
while ( is.good() )
{
if ( is.peek() != EOF )
is >> temp;
else
break;
valuesRead++;
}
if ( is.fail() )
return EXTRACT_FAILURE;
if ( valuesRead > 1 )
return EXTRACT_TOO_MANY;
_values.push_back(temp);
return 0;
}
};
/**
* @brief TClap class internally used for string handling.
*
* Specialization for string. This is necessary because istringstream
* operator>> is not able to ignore spaces... meaning -x "X Y" will only
* read 'X'... and thus the specialization.
*/
template<>
class ValueExtractor<std::string>
{
friend class MultiArg<std::string>;
private:
/**
* Reference to the vector of strings where the result of the
* extraction will be put.
*/
std::vector<std::string> &_values;
/**
* Constructor.
* \param values - Where the strings extracted will be put.
*/
ValueExtractor(std::vector<std::string> &values) : _values(values) {}
/**
* Method that will attempt to parse the input stream for values
* of type std::string.
* \param val - Where the values parsed will be put.
*/
int extractValue( const std::string& val )
{
_values.push_back( val );
return 0;
}
};
} //namespace MultiArgHelper
/**
* An argument that allows multiple values of type T to be specified. Very
* similar to a ValueArg, except a vector of values will be returned
* instead of just one.
*/
template<class T>
class MultiArg : public Arg
{
protected:
/**
* The list of values parsed from the CmdLine.
*/
std::vector<T> _values;
/**
* The description of type T to be used in the usage.
*/
std::string _typeDesc;
/**
* A list of constraint on this Arg.
*/
Constraint<T>* _constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - The string to be read.
*/
void _extractValue( const std::string& val );
bool _allowMore;
public:
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v = NULL);
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v = NULL );
/**
* Constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns a vector of type T containing the values parsed from
* the command line.
*/
const std::vector<T>& getValue();
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
virtual bool isRequired() const;
virtual bool allowMore();
};
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( typeDesc ),
_constraint( NULL ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
/**
*
*/
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
_acceptsMultipleValues = true;
}
template<class T>
MultiArg<T>::MultiArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg( flag, name, desc, req, true, v ),
_typeDesc( constraint->shortID() ),
_constraint( constraint ),
_allowMore(false)
{
parser.add( this );
_acceptsMultipleValues = true;
}
template<class T>
const std::vector<T>& MultiArg<T>::getValue() { return _values; }
template<class T>
bool MultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
std::string flag = args[*i];
std::string value = "";
trimFlag( flag, value );
if ( argMatches( flag ) )
{
if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
"Couldn't find delimiter for this argument!",
toString() ) );
// always take the first one, regardless of start string
if ( value == "" )
{
(*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
_extractValue( args[*i] );
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
else
_extractValue( value );
/*
// continuing taking the args until we hit one with a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
}
/**
*
*/
template<class T>
std::string MultiArg<T>::shortID(const std::string& /*val*/) const
{
std::string id = Arg::shortID(_typeDesc) + " ... ";
return id;
}
/**
*
*/
template<class T>
std::string MultiArg<T>::longID(const std::string& /*val*/) const
{
std::string id = Arg::longID(_typeDesc) + " (accepted multiple times)";
return id;
}
/**
* Once we've matched the first value, then the arg is no longer
* required.
*/
template<class T>
bool MultiArg<T>::isRequired() const
{
if ( _required )
{
if ( _values.size() > 1 )
return false;
else
return true;
}
else
return false;
}
template<class T>
void MultiArg<T>::_extractValue( const std::string& val )
{
MultiArgHelper::ValueExtractor<T> ve(_values);
int err = ve.extractValue(val);
if ( err == MultiArgHelper::EXTRACT_FAILURE )
throw( ArgParseException("Couldn't read argument value "
"from string '" + val + "'", toString() ) );
if(err == MultiArgHelper::EXTRACT_TOO_MANY)
throw( ArgParseException("More than one valid value "
"parsed from string '" + val + "'",
toString() ) );
if ( _constraint != NULL )
if ( ! _constraint->check( _values.back() ) )
throw( CmdLineParseException( "Value '" + val +
"' does not meet constraint: " +
_constraint->description(),
toString() ) );
}
template<class T>
bool MultiArg<T>::allowMore()
{
bool am = _allowMore;
_allowMore = true;
return am;
}
} // namespace ecl
#endif
@@ -0,0 +1,192 @@
/**
* @file /include/ecl/command_line/multi_switch_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_MULTI_SWITCH_ARG_H
#define TCLAP_MULTI_SWITCH_ARG_H
#include <string>
#include <vector>
#include "switch_arg.hpp"
namespace ecl {
/**
* A multiple switch argument. If the switch is set on the command line, then
* the getValue method will return the number of times the switch appears.
*/
class MultiSwitchArg : public SwitchArg
{
protected:
/**
* The value of the switch.
*/
int _value;
public:
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init = 0,
Visitor* v = NULL);
/**
* MultiSwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param init - Optional. The initial/default value of this Arg.
* Defaults to 0.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init = 0,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the SwitchArg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns int, the number of times the switch has been set.
*/
int getValue();
/**
* Returns the shortID for this Arg.
*/
std::string shortID(const std::string& val) const;
/**
* Returns the longID for this Arg.
*/
std::string longID(const std::string& val) const;
};
//////////////////////////////////////////////////////////////////////
//BEGIN MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init )
{ }
inline MultiSwitchArg::MultiSwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
int init,
Visitor* v )
: SwitchArg(flag, name, desc, false, v),
_value( init )
{
parser.add( this );
}
inline int MultiSwitchArg::getValue() { return _value; }
inline bool MultiSwitchArg::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( argMatches( args[*i] ))
{
// so the isSet() method will work
_alreadySet = true;
// Matched argument: increment value.
++_value;
_checkWithVisitor();
return true;
}
else if ( combinedSwitchesMatch( args[*i] ) )
{
// so the isSet() method will work
_alreadySet = true;
// Matched argument: increment value.
++_value;
// Check for more in argument and increment value.
while ( combinedSwitchesMatch( args[*i] ) )
++_value;
_checkWithVisitor();
return false;
}
else
return false;
}
inline std::string MultiSwitchArg::shortID(const std::string& val) const
{
std::string id = Arg::shortID() + " ... " + val;
return id;
}
inline std::string MultiSwitchArg::longID(const std::string& val) const
{
std::string id = Arg::longID() + " (accepted multiple times) " + val;
return id;
}
//////////////////////////////////////////////////////////////////////
//END MultiSwitchArg.cpp
//////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,53 @@
/**
* @file /include/ecl/command_line/optional_unlabeled_tracker.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_OPTIONAL_UNLABELED_TRACKER_H
#define TCLAP_OPTIONAL_UNLABELED_TRACKER_H
#include <string>
namespace ecl {
class OptionalUnlabeledTracker
{
public:
static void check( bool req, const std::string& argName );
static void gotOptional() { alreadyOptionalRef() = true; }
static bool& alreadyOptional() { return alreadyOptionalRef(); }
private:
static bool& alreadyOptionalRef() { static bool ct = false; return ct; }
};
inline void OptionalUnlabeledTracker::check( bool req, const std::string& argName )
{
if ( OptionalUnlabeledTracker::alreadyOptional() )
throw( SpecificationException(
"You can't specify ANY Unlabeled Arg following an optional Unlabeled Arg",
argName ) );
if ( !req )
OptionalUnlabeledTracker::gotOptional();
}
} // namespace ecl
#endif
@@ -0,0 +1,288 @@
/**
* @file /include/ecl/command_line/std_output.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_STDCMDLINEOUTPUT_H
#define TCLAP_STDCMDLINEOUTPUT_H
#include <string>
#include <vector>
#include <list>
#include <iostream>
#include <algorithm>
#include <cmath>
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "xor_handler.hpp"
#include "arg.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to handle CmdLine arguments.
*
* A class that isolates any output from the CmdLine object so that it
* may be easily modified.
*/
class StdOutput : public CmdLineOutput
{
public:
/**
* Prints the usage to stdout. Can be overridden to
* produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void usage(CmdLineInterface& c);
/**
* Prints the version to stdout. Can be overridden
* to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
*/
virtual void version(CmdLineInterface& c);
/**
* Prints (to stderr) an error message, short usage
* Can be overridden to produce alternative behavior.
* \param c - The CmdLine object the output is generated for.
* \param e - The ArgException that caused the failure.
*/
virtual void failure(CmdLineInterface& c,
ArgException& e );
protected:
/**
* Writes a brief usage message with short args.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _shortUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* Writes a longer usage message with long and short args,
* provides descriptions and prints message.
* \param c - The CmdLine object the output is generated for.
* \param os - The stream to write the message to.
*/
void _longUsage( CmdLineInterface& c, std::ostream& os ) const;
/**
* This function inserts line breaks and indents long strings
* according the params input. It will only break lines at spaces,
* commas and pipes.
* \param os - The stream to be printed to.
* \param s - The string to be printed.
* \param maxWidth - The maxWidth allowed for the output line.
* \param indentSpaces - The number of spaces to indent the first line.
* \param secondLineOffset - The number of spaces to indent the second
* and all subsequent lines in addition to indentSpaces.
*/
void spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const;
};
inline void StdOutput::version(CmdLineInterface& _cmd)
{
std::string progName = _cmd.getProgramName();
std::string interface_version = _cmd.getVersion();
std::cout << std::endl << progName << " version: "
<< interface_version << std::endl << std::endl;
}
inline void StdOutput::usage(CmdLineInterface& _cmd )
{
std::cout << std::endl << "USAGE: " << std::endl << std::endl;
_shortUsage( _cmd, std::cout );
std::cout << std::endl << std::endl << "Where: " << std::endl << std::endl;
_longUsage( _cmd, std::cout );
std::cout << std::endl;
}
inline void StdOutput::failure( CmdLineInterface& _cmd,
ArgException& e )
{
std::string progName = _cmd.getProgramName();
std::cerr << "PARSE ERROR: " << e.argId() << std::endl
<< " " << e.error() << std::endl << std::endl;
if ( _cmd.hasHelpAndVersion() )
{
std::cerr << "Brief USAGE: " << std::endl;
_shortUsage( _cmd, std::cerr );
std::cerr << std::endl << "For complete USAGE and HELP type: "
<< std::endl << " " << progName << " --help"
<< std::endl << std::endl;
}
else
usage(_cmd);
}
inline void StdOutput::_shortUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string progName = _cmd.getProgramName();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
std::string s = progName + " ";
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
{
s += " {";
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end(); it++ )
s += (*it)->shortID() + "|";
s[s.length()-1] = '}';
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
s += " " + (*it)->shortID();
// if the program name is too long, then adjust the second line offset
int secondLineOffset = static_cast<int>(progName.length()) + 2;
if ( secondLineOffset > 75/2 )
secondLineOffset = static_cast<int>(75/2);
spacePrint( os, s, 75, 3, secondLineOffset );
//spacePrint( std::cout, s, 75, 3, secondLineOffset );
}
inline void StdOutput::_longUsage( CmdLineInterface& _cmd,
std::ostream& os ) const
{
std::list<Arg*> argList = _cmd.getArgList();
std::string message = _cmd.getMessage();
XorHandler xorHandler = _cmd.getXorHandler();
std::vector< std::vector<Arg*> > xorList = xorHandler.getXorList();
// first the xor
for ( int i = 0; static_cast<unsigned int>(i) < xorList.size(); i++ )
{
for ( ArgVectorIterator it = xorList[i].begin();
it != xorList[i].end();
it++ )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
if ( it+1 != xorList[i].end() )
spacePrint(os, "-- OR --", 75, 9, 0);
}
os << std::endl << std::endl;
}
// then the rest
for (ArgListIterator it = argList.begin(); it != argList.end(); it++)
if ( !xorHandler.contains( (*it) ) )
{
spacePrint( os, (*it)->longID(), 75, 3, 3 );
spacePrint( os, (*it)->getDescription(), 75, 5, 0 );
os << std::endl;
}
os << std::endl;
spacePrint( os, message, 75, 3, 0 );
}
inline void StdOutput::spacePrint( std::ostream& os,
const std::string& s,
int maxWidth,
int indentSpaces,
int secondLineOffset ) const
{
int len = static_cast<int>(s.length());
if ( (len + indentSpaces > maxWidth) && maxWidth > 0 )
{
int allowedLen = maxWidth - indentSpaces;
int start = 0;
while ( start < len )
{
// find the substring length
int stringLen = std::min<int>( len - start, allowedLen );
// trim the length so it doesn't end in middle of a word
if ( stringLen == allowedLen )
while ( s[stringLen+start] != ' ' &&
s[stringLen+start] != ',' &&
s[stringLen+start] != '|' &&
stringLen >= 0 )
stringLen--;
// ok, the word is longer than the line, so just split
// wherever the line ends
if ( stringLen <= 0 )
stringLen = allowedLen;
// check for newlines
for ( int i = 0; i < stringLen; i++ )
if ( s[start+i] == '\n' )
stringLen = i+1;
// print the indent
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
if ( start == 0 )
{
// handle second line offsets
indentSpaces += secondLineOffset;
// adjust allowed len
allowedLen -= secondLineOffset;
}
os << s.substr(start,stringLen) << std::endl;
// so we don't start a line with a space
while ( s[stringLen+start] == ' ' && start < len )
start++;
start += stringLen;
}
}
else
{
for ( int i = 0; i < indentSpaces; i++ )
os << " ";
os << s << std::endl;
}
}
} // namespace ecl
#endif
@@ -0,0 +1,199 @@
/**
* @file /include/ecl/command_line/switch_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_SWITCH_ARG_H
#define TCLAP_SWITCH_ARG_H
#include <string>
#include <vector>
#include "arg.hpp"
namespace ecl {
/**
* A simple switch argument. If the switch is set on the command line, then
* the getValue method will return the opposite of the default value for the
* switch.
*/
class SwitchArg : public Arg
{
protected:
/**
* The value of the switch.
*/
bool _value;
public:
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool def = false,
Visitor* v = NULL);
/**
* SwitchArg constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param parser - A CmdLine parser object to add this Arg to
* \param def - The default value for this Switch.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
bool def = false,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Checks a string to see if any of the chars in the string
* match the flag for this Switch.
*/
bool combinedSwitchesMatch(std::string& combined);
/**
* Returns bool, whether or not the switch has been set.
*/
bool getValue();
};
//////////////////////////////////////////////////////////////////////
//BEGIN SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
inline SwitchArg::SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool _default,
Visitor* v )
: Arg(flag, name, desc, false, false, v),
_value( _default )
{ }
inline SwitchArg::SwitchArg(const std::string& flag,
const std::string& name,
const std::string& desc,
CmdLineInterface& parser,
bool _default,
Visitor* v )
: Arg(flag, name, desc, false, false, v),
_value( _default )
{
parser.add( this );
}
inline bool SwitchArg::getValue() { return _value; }
inline bool SwitchArg::combinedSwitchesMatch(std::string& combinedSwitches )
{
// make sure this is actually a combined switch
if ( combinedSwitches[0] != Arg::flagStartString()[0] )
return false;
// make sure it isn't a long name
if ( combinedSwitches.substr( 0, Arg::nameStartString().length() ) ==
Arg::nameStartString() )
return false;
// ok, we're not specifying a ValueArg, so we know that we have
// a combined switch list.
for ( unsigned int i = 1; i < combinedSwitches.length(); i++ )
if ( combinedSwitches[i] == _flag[0] )
{
// update the combined switches so this one is no longer present
// this is necessary so that no unlabeled args are matched
// later in the processing.
//combinedSwitches.erase(i,1);
combinedSwitches[i] = Arg::blankChar();
return true;
}
// none of the switches passed in the list match.
return false;
}
inline bool SwitchArg::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( argMatches( args[*i] ) || combinedSwitchesMatch( args[*i] ) )
{
// If we match on a combined switch, then we want to return false
// so that other switches in the combination will also have a
// chance to match.
bool ret = false;
if ( argMatches( args[*i] ) )
ret = true;
if ( _alreadySet || ( !ret && combinedSwitchesMatch( args[*i] ) ) )
throw(CmdLineParseException("Argument already set!", toString()));
_alreadySet = true;
if ( _value == true )
_value = false;
else
_value = true;
_checkWithVisitor();
return ret;
}
else
return false;
}
//////////////////////////////////////////////////////////////////////
//End SwitchArg.cpp
//////////////////////////////////////////////////////////////////////
} // namespace ecl
#endif
@@ -0,0 +1,295 @@
/**
* @file /include/ecl/command_line/unlabeled_multi_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H
#define TCLAP_MULTIPLE_UNLABELED_ARGUMENT_H
#include <string>
#include <vector>
#include "multi_arg.hpp"
#include "optional_unlabeled_tracker.hpp"
namespace ecl {
/**
* Just like a MultiArg, except that the arguments are unlabeled. Basically,
* this Arg will slurp up everything that hasn't been matched to another
* Arg.
*/
template<class T>
class UnlabeledMultiArg : public MultiArg<T>
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using MultiArg<T>::_ignoreable;
using MultiArg<T>::_hasBlanks;
using MultiArg<T>::_extractValue;
using MultiArg<T>::_typeDesc;
using MultiArg<T>::_name;
using MultiArg<T>::_description;
using MultiArg<T>::_alreadySet;
using MultiArg<T>::toString;
public:
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Constructor.
* \param name - The name of the Arg. Note that this is used for
* identification, not as a long flag.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Whether or not this argument can be ignored
* using the "--" flag.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
UnlabeledMultiArg( const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns the a short id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Returns the a long id string. Used in the usage.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Opertor ==.
* \param a - The Arg to be compared to this.
*/
virtual bool operator==(const Arg& a) const;
/**
* Pushes this to back of list rather than front.
* \param argList - The list this should be added to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
};
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add( this );
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
}
template<class T>
UnlabeledMultiArg<T>::UnlabeledMultiArg(const std::string& name,
const std::string& desc,
bool req,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: MultiArg<T>("", name, desc, req, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(true, toString());
parser.add( this );
}
template<class T>
bool UnlabeledMultiArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _hasBlanks( args[*i] ) )
return false;
// never ignore an unlabeled multi arg
// always take the first value, regardless of the start string
_extractValue( args[(*i)] );
/*
// continue taking args until we hit the end or a start string
while ( (unsigned int)(*i)+1 < args.size() &&
args[(*i)+1].find_first_of( Arg::flagStartString() ) != 0 &&
args[(*i)+1].find_first_of( Arg::nameStartString() ) != 0 )
_extractValue( args[++(*i)] );
*/
_alreadySet = true;
return true;
}
template<class T>
std::string UnlabeledMultiArg<T>::shortID(const std::string& /*val*/) const
{
std::string id = "<" + _typeDesc + "> ...";
return id;
}
template<class T>
std::string UnlabeledMultiArg<T>::longID(const std::string& /*val*/) const
{
std::string id = "<" + _typeDesc + "> (accepted multiple times)";
return id;
}
template<class T>
bool UnlabeledMultiArg<T>::operator==(const Arg& a) const
{
if ( _name == a.getName() || _description == a.getDescription() )
return true;
else
return false;
}
template<class T>
void UnlabeledMultiArg<T>::addToList( std::list<Arg*>& argList ) const
{
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
}
} // namespace ecl
#endif
@@ -0,0 +1,335 @@
/**
* @file /include/ecl/command_line/unlabeled_value_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_UNLABELED_VALUE_ARGUMENT_H
#define TCLAP_UNLABELED_VALUE_ARGUMENT_H
#include <string>
#include <vector>
#include "value_arg.hpp"
#include "optional_unlabeled_tracker.hpp"
namespace ecl {
/**
* The basic unlabeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when an UnlabeledValueArg
* is reached in the list of args that the CmdLine iterates over.
*/
template<class T>
class UnlabeledValueArg : public ValueArg<T>
{
// If compiler has two stage name lookup (as gcc >= 3.4 does)
// this is requried to prevent undef. symbols
using ValueArg<T>::_ignoreable;
using ValueArg<T>::_hasBlanks;
using ValueArg<T>::_extractValue;
using ValueArg<T>::_typeDesc;
using ValueArg<T>::_name;
using ValueArg<T>::_description;
using ValueArg<T>::_alreadySet;
using ValueArg<T>::toString;
public:
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
bool ignoreable = false,
Visitor* v = NULL);
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL );
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
bool ignoreable = false,
Visitor* v = NULL );
/**
* UnlabeledValueArg constructor.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to
* \param ignoreable - Allows you to specify that this argument can be
* ignored if the '--' flag is set. This defaults to false (cannot
* be ignored) and should generally stay that way unless you have
* some special need for certain arguments to be ignored.
* \param v - Optional Vistor. You should leave this blank unless
* you have a very good reason.
*/
UnlabeledValueArg( const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable = false,
Visitor* v = NULL);
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. Handling specific to
* unlabled arguments.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings.
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Overrides shortID for specific behavior.
*/
virtual std::string shortID(const std::string& val="val") const;
/**
* Overrides longID for specific behavior.
*/
virtual std::string longID(const std::string& val="val") const;
/**
* Overrides operator== for specific behavior.
*/
virtual bool operator==(const Arg& a ) const;
/**
* Instead of pushing to the front of list, push to the back.
* \param argList - The list to add this to.
*/
virtual void addToList( std::list<Arg*>& argList ) const;
};
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, value, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, value, typeDesc, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add( this );
}
/**
* Constructor implemenation.
*/
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, value, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
}
template<class T>
UnlabeledValueArg<T>::UnlabeledValueArg(const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
bool ignoreable,
Visitor* v)
: ValueArg<T>("", name, desc, req, value, constraint, v)
{
_ignoreable = ignoreable;
OptionalUnlabeledTracker::check(req, toString());
parser.add( this );
}
/**
* Implementation of processArg().
*/
template<class T>
bool UnlabeledValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _alreadySet )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
// never ignore an unlabeled arg
_extractValue( args[*i] );
_alreadySet = true;
return true;
}
/**
* Overriding shortID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::shortID(const std::string& val) const
{
(void)val;
std::string id = "<" + _typeDesc + ">";
return id;
}
/**
* Overriding longID for specific output.
*/
template<class T>
std::string UnlabeledValueArg<T>::longID(const std::string& val) const
{
(void)val;
// Ideally we would like to be able to use RTTI to return the name
// of the type required for this argument. However, g++ at least,
// doesn't appear to return terribly useful "names" of the types.
std::string id = "<" + _typeDesc + ">";
return id;
}
/**
* Overriding operator== for specific behavior.
*/
template<class T>
bool UnlabeledValueArg<T>::operator==(const Arg& a ) const
{
if ( _name == a.getName() || _description == a.getDescription() )
return true;
else
return false;
}
template<class T>
void UnlabeledValueArg<T>::addToList( std::list<Arg*>& argList ) const
{
argList.push_back( const_cast<Arg*>(static_cast<const Arg* const>(this)) );
}
} // namespace ecl
#endif
@@ -0,0 +1,512 @@
/**
* @file /include/ecl/command_line/value_arg.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_VALUE_ARGUMENT_H
#define TCLAP_VALUE_ARGUMENT_H
#include <string>
#include <vector>
#include <cstdio>
#include "arg.hpp"
#include "constraint.hpp"
#define HAVE_SSTREAM
#if defined(HAVE_SSTREAM)
#include <sstream>
#elif defined(HAVE_STRSTREAM)
#include <strstream>
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
namespace ecl {
template<class T> class ValueArg;
namespace ValueArgHelper {
enum Error_e { EXTRACT_FAILURE = 1000, EXTRACT_TOO_MANY };
/**
* @brief TClap class internally used for extracting value args.
*
* This class is used to extract a value from an argument.
* It is used because we need a special implementation to
* deal with std::string and making a specialised function
* puts it in the T segment, thus generating link errors.
* Having a specialised class makes the symbols weak.
* This is not pretty but I don't know how to make it
* work any other way.
*/
template<class T> class ValueExtractor
{
friend class ValueArg<T>;
private:
/**
* Reference to the value where the result of the extraction will
* be put.
*/
T &_value;
/**
* Constructor.
* \param value - Where the value extracted will be put.
*/
ValueExtractor(T &value) : _value(value) { }
/**
* Method that will attempt to parse the input stream for a value
* of type T.
* \param val - Where the value parsed will be put.
*/
int extractValue( const std::string& val )
{
#if defined(HAVE_SSTREAM)
std::istringstream is(val);
#elif defined(HAVE_STRSTREAM)
std::istrstream is(val.c_str());
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
int valuesRead = 0;
while ( is.good() )
{
if ( is.peek() != EOF )
is >> _value;
else
break;
valuesRead++;
}
if ( is.fail() )
return EXTRACT_FAILURE;
if ( valuesRead > 1 )
return EXTRACT_TOO_MANY;
return 0;
}
};
/**
* @brief TClap class internally used for string handling.
*
* Specialization for string. This is necessary because istringstream
* operator>> is not able to ignore spaces... meaning -x "X Y" will only
* read 'X'... and thus the specialization.
*/
template<> class ValueExtractor<std::string>
{
friend class ValueArg<std::string>;
private:
/**
* Reference to the value where the result of the extraction will
* be put.
*/
std::string &_value;
/**
* Constructor.
* \param value - Where the value extracted will be put.
*/
ValueExtractor(std::string &value) : _value(value) {}
/**
* Method that will attempt to parse the input stream for a value
* of type std::string.
* \param val - Where the string parsed will be put.
*/
int extractValue( const std::string& val )
{
_value = val;
return 0;
}
};
} //namespace ValueArgHelper
/**
* The basic labeled argument that parses a value.
* This is a template class, which means the type T defines the type
* that a given object will attempt to parse when the flag/name is matched
* on the command line. While there is nothing stopping you from creating
* an unflagged ValueArg, it is unwise and would cause significant problems.
* Instead use an UnlabeledValueArg.
*/
template<class T>
class ValueArg : public Arg
{
protected:
/**
* The value parsed from the command line.
* Can be of any type, as long as the >> operator for the type
* is defined.
*/
T _value;
/**
* A human readable description of the type to be parsed.
* This is a hack, plain and simple. Ideally we would use RTTI to
* return the name of type T, but until there is some sort of
* consistent support for human readable names, we are left to our
* own devices.
*/
std::string _typeDesc;
/**
* A Constraint this Arg must conform to.
*/
Constraint<T>* _constraint;
/**
* Extracts the value from the string.
* Attempts to parse string as type T, if this fails an exception
* is thrown.
* \param val - value to be parsed.
*/
void _extractValue( const std::string& val );
public:
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
Visitor* v = NULL);
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param typeDesc - A short, human readable description of the
* type that this object expects. This is used in the generation
* of the USAGE statement. The goal is to be helpful to the end user
* of the program.
* \param parser - A CmdLine parser object to add this Arg to
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param parser - A CmdLine parser object to add this Arg to.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v = NULL );
/**
* Labeled ValueArg constructor.
* You could conceivably call this constructor with a blank flag,
* but that would make you a bad person. It would also cause
* an exception to be thrown. If you want an unlabeled argument,
* use the other constructor.
* \param flag - The one character flag that identifies this
* argument on the command line.
* \param name - A one word name for the argument. Can be
* used as a long flag on the command line.
* \param desc - A description of what the argument is for or
* does.
* \param req - Whether the argument is required on the command
* line.
* \param value - The default value assigned to this argument if it
* is not present on the command line.
* \param constraint - A pointer to a Constraint object used
* to constrain this Arg.
* \param v - An optional visitor. You probably should not
* use this unless you have a very good reason.
*/
ValueArg( const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
Constraint<T>* constraint,
Visitor* v = NULL );
/**
* Handles the processing of the argument.
* This re-implements the Arg version of this method to set the
* _value of the argument appropriately. It knows the difference
* between labeled and unlabeled.
* \param i - Pointer the the current argument in the list.
* \param args - Mutable list of strings. Passed
* in from main().
*/
virtual bool processArg(int* i, std::vector<std::string>& args);
/**
* Returns the value of the argument.
*/
T& getValue() ;
/**
* Specialization of shortID.
* \param val - value to be used.
*/
virtual std::string shortID(const std::string& val = "val") const;
/**
* Specialization of longID.
* \param val - value to be used.
*/
virtual std::string longID(const std::string& val = "val") const;
};
/**
* Constructor implementation.
*/
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T value,
const std::string& typeDesc,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( value ),
_typeDesc( typeDesc ),
_constraint( NULL )
{ }
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
const std::string& typeDesc,
CmdLineInterface& parser,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_typeDesc( typeDesc ),
_constraint( NULL )
{
parser.add( this );
}
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_typeDesc( constraint->shortID() ),
_constraint( constraint )
{ }
template<class T>
ValueArg<T>::ValueArg(const std::string& flag,
const std::string& name,
const std::string& desc,
bool req,
T val,
Constraint<T>* constraint,
CmdLineInterface& parser,
Visitor* v)
: Arg(flag, name, desc, req, true, v),
_value( val ),
_typeDesc( constraint->shortID() ),
_constraint( constraint )
{
parser.add( this );
}
/**
* Implementation of getValue().
*/
template<class T>
T& ValueArg<T>::getValue() { return _value; }
/**
* Implementation of processArg().
*/
template<class T>
bool ValueArg<T>::processArg(int *i, std::vector<std::string>& args)
{
if ( _ignoreable && Arg::ignoreRest() )
return false;
if ( _hasBlanks( args[*i] ) )
return false;
std::string flag = args[*i];
std::string value = "";
trimFlag( flag, value );
if ( argMatches( flag ) )
{
if ( _alreadySet )
throw( CmdLineParseException("Argument already set!", toString()) );
if ( Arg::delimiter() != ' ' && value == "" )
throw( ArgParseException(
"Couldn't find delimiter for this argument!",
toString() ) );
if ( value == "" )
{
(*i)++;
if ( static_cast<unsigned int>(*i) < args.size() )
_extractValue( args[*i] );
else
throw( ArgParseException("Missing a value for this argument!",
toString() ) );
}
else
_extractValue( value );
_alreadySet = true;
_checkWithVisitor();
return true;
}
else
return false;
}
/**
* Implementation of shortID.
*/
template<class T>
std::string ValueArg<T>::shortID(const std::string& val) const
{
std::string stop_warnings = val; // Only to stop annoying warning messages, I dont think it slows things down
return Arg::shortID( _typeDesc );
}
/**
* Implementation of longID.
*/
template<class T>
std::string ValueArg<T>::longID(const std::string& val) const
{
std::string stop_warnings = val; // Only to stop annoying warning messages, I dont think it slows things down
return Arg::longID( _typeDesc );
}
template<class T> // Just to stop the warnings.
void ValueArg<T>::_extractValue( const std::string& val )
{
ValueArgHelper::ValueExtractor<T> ve(_value);
int err = ve.extractValue(val);
if ( err == ValueArgHelper::EXTRACT_FAILURE )
throw( ArgParseException("Couldn't read argument value from string '" +
val + "'", toString() ) );
if ( err == ValueArgHelper::EXTRACT_TOO_MANY )
throw( ArgParseException(
"More than one valid value parsed from string '" +
val + "'", toString() ) );
if ( _constraint != NULL )
if ( ! _constraint->check( _value ) )
throw( CmdLineParseException( "Value '" + val +
"' does not meet constraint: " +
_constraint->description(),
toString() ) );
}
} // namespace ecl
#endif
@@ -0,0 +1,135 @@
/**
* @file /include/ecl/command_line/values_constraint.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_VALUESCONSTRAINT_H
#define TCLAP_VALUESCONSTRAINT_H
#include <string>
#include <vector>
#include "constraint.hpp"
#define HAVE_SSTREAM
#if defined(HAVE_SSTREAM)
#include <sstream>
#elif defined(HAVE_STRSTREAM)
#include <strstream>
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
namespace ecl {
/**
* A Constraint that constrains the Arg to only those values specified
* in the constraint.
*/
template<class T>
class ValuesConstraint : public Constraint<T>
{
public:
/**
* Constructor.
* \param allowed - vector of allowed values.
*/
ValuesConstraint(std::vector<T>& allowed);
/**
* Virtual destructor.
*/
virtual ~ValuesConstraint() {}
/**
* Returns a description of the Constraint.
*/
virtual std::string description() const;
/**
* Returns the short ID for the Constraint.
*/
virtual std::string shortID() const;
/**
* The method used to verify that the value parsed from the command
* line meets the constraint.
* \param value - The value that will be checked.
*/
virtual bool check(const T& value) const;
protected:
/**
* The list of valid values.
*/
std::vector<T> _allowed;
/**
* The string used to describe the allowed values of this constraint.
*/
std::string _typeDesc;
};
template<class T>
ValuesConstraint<T>::ValuesConstraint(std::vector<T>& allowed)
: _allowed(allowed)
{
for ( unsigned int i = 0; i < _allowed.size(); i++ )
{
#if defined(HAVE_SSTREAM)
std::ostringstream os;
#elif defined(HAVE_STRSTREAM)
std::ostrstream os;
#else
#error "Need a stringstream (sstream or strstream) to compile!"
#endif
os << _allowed[i];
std::string temp( os.str() );
if ( i > 0 )
_typeDesc += "|";
_typeDesc += temp;
}
}
template<class T>
bool ValuesConstraint<T>::check( const T& val ) const
{
if ( std::find(_allowed.begin(),_allowed.end(),val) == _allowed.end() )
return false;
else
return true;
}
template<class T>
std::string ValuesConstraint<T>::shortID() const
{
return _typeDesc;
}
template<class T>
std::string ValuesConstraint<T>::description() const
{
return _typeDesc;
}
} // namespace ecl
#endif
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/command_line/version_visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_VERSION_VISITOR_H
#define TCLAP_VERSION_VISITOR_H
#include "cmd_line_interface.hpp"
#include "cmd_line_output.hpp"
#include "visitor.hpp"
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A Vistor that will call the version method of the given CmdLineOutput
* for the specified CmdLine object and then exit.
*/
class VersionVisitor: public Visitor
{
protected:
/**
* The CmdLine of interest.
*/
CmdLineInterface* _cmd;
/**
* The output object.
*/
CmdLineOutput** _out;
public:
/**
* Constructor.
* \param cmd - The CmdLine the output is generated for.
* \param out - The type of output.
*/
VersionVisitor( CmdLineInterface* cmd, CmdLineOutput** out )
: Visitor(), _cmd( cmd ), _out( out ) { }
/**
* Calls the version method of the output object using the
* specified CmdLine.
*/
void visit() { (*_out)->version(*_cmd); exit(0); }
};
} // namespace ecl
#endif
@@ -0,0 +1,47 @@
/**
* @file /include/ecl/command_line/visitor.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_VISITOR_H
#define TCLAP_VISITOR_H
namespace ecl {
/**
* @brief TClap class indirectly used to define the interface for visitors.
*
* A base class that defines the interface for visitors.
*/
class Visitor
{
public:
/**
* Constructor. Does nothing.
*/
Visitor() { }
/**
* Destructor. Does nothing.
*/
virtual ~Visitor() { }
/**
* Does nothing. Should be overridden by child.
*/
virtual void visit() { }
};
} // namespace ecl
#endif
@@ -0,0 +1,145 @@
/**
* @file /include/ecl/command_line/xor_handler.hpp
*
* @brief TCLAP command line argument parser classes.
*
* TCLAP command line argument parser classes.
*
* @author Michael E. Smoot, Daniel J. Stonier
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef TCLAP_XORHANDLER_H
#define TCLAP_XORHANDLER_H
#include "arg.hpp"
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
namespace ecl {
/**
* @brief TClap class indirectly used by CmdLine for handling xor'd arguments.
*
* This class handles lists of Arg's that are to be XOR'd on the command
* line. This is used by CmdLine and you shouldn't ever use it.
*/
class XorHandler
{
protected:
/**
* The list of of lists of Arg's to be or'd together.
*/
std::vector< std::vector<Arg*> > _orList;
public:
/**
* Constructor. Does nothing.
*/
XorHandler( ) {}
/**
* Add a list of Arg*'s that will be orred together.
* \param ors - list of Arg* that will be xor'd.
*/
void add( std::vector<Arg*>& ors );
/**
* Checks whether the specified Arg is in one of the xor lists and
* if it does match one, returns the size of the xor list that the
* Arg matched. If the Arg matches, then it also sets the rest of
* the Arg's in the list. You shouldn't use this.
* \param a - The Arg to be checked.
*/
int check( const Arg* a );
/**
* Returns the XOR specific short usage.
*/
std::string shortUsage();
/**
* Prints the XOR specific long usage.
* \param os - Stream to print to.
*/
void printLongUsage(std::ostream& os);
/**
* Simply checks whether the Arg is contained in one of the arg
* lists.
* \param a - The Arg to be checked.
*/
bool contains( const Arg* a );
std::vector< std::vector<Arg*> >& getXorList();
};
//////////////////////////////////////////////////////////////////////
//BEGIN XOR.cpp
//////////////////////////////////////////////////////////////////////
inline void XorHandler::add( std::vector<Arg*>& ors )
{
_orList.push_back( ors );
}
inline int XorHandler::check( const Arg* a )
{
// iterate over each XOR list
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
{
// if the XOR list contains the arg..
ArgVectorIterator ait = std::find( _orList[i].begin(),
_orList[i].end(), a );
if ( ait != _orList[i].end() )
{
// go through and set each arg that is not a
for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++ )
if ( a != (*it) )
(*it)->xorSet();
// return the number of required args that have now been set
if ( (*ait)->allowMore() )
return 0;
else
return static_cast<int>(_orList[i].size());
}
}
if ( a->isRequired() )
return 1;
else
return 0;
}
inline bool XorHandler::contains( const Arg* a )
{
for ( int i = 0; static_cast<unsigned int>(i) < _orList.size(); i++ )
for ( ArgVectorIterator it = _orList[i].begin();
it != _orList[i].end();
it++ )
if ( a == (*it) )
return true;
return false;
}
inline std::vector< std::vector<Arg*> >& XorHandler::getXorList()
{
return _orList;
}
} // namespace ecl
#endif
@@ -0,0 +1,6 @@
original author: Michael E. Smoot
invaluable contributions: Daniel Aarno
more contributions: Erik Zeek
outstanding editing: Carol Smoot
modifications for ecl: Daniel Stonier
@@ -0,0 +1,8 @@
###############################################################################
# FILES
###############################################################################
set(LICENSES COPYING AUTHORS)
install(FILES ${LICENSES} DESTINATION share/ecl/licenses/tclap)
@@ -0,0 +1,25 @@
Copyright (c) 2003 Michael E. Smoot
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.
@@ -0,0 +1,32 @@
<?xml version="1.0"?>
<package format="2">
<name>ecl_command_line</name>
<version>1.2.1</version>
<description>
Embeds the TCLAP library inside the ecl. This is a very convenient
command line parser in templatised c++.
</description>
<maintainer email="d.stonier@gmail.com">Daniel Stonier</maintainer>
<license>BSD-3-Clause</license>
<url type="website">http://wiki.ros.org/ecl_command_line</url>
<url type="repository">https://github.com/stonier/ecl_core</url>
<url type="bugtracker">https://github.com/stonier/ecl_core/issues</url>
<author email="d.stonier@gmail.com">Daniel Stonier</author> -->
<buildtool_depend>ament_cmake_ros</buildtool_depend>
<build_depend>ecl_license</build_depend>
<build_depend>ecl_build</build_depend>
<exec_depend>ecl_license</exec_depend>
<test_depend>ament_cmake_gtest</test_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,12 @@
###############################################################################
# Subdirectories
###############################################################################
add_subdirectory(examples)
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
add_subdirectory(test)
endif()
@@ -0,0 +1,16 @@
###############################################################################
# Macros
###############################################################################
macro(ecl_command_line_add_demo name)
add_executable(ecl_demo_${name} ${name}.cpp)
set_target_properties(ecl_demo_${name} PROPERTIES OUTPUT_NAME demo_${name})
install(TARGETS ecl_demo_${name} RUNTIME DESTINATION lib/${PROJECT_NAME})
endmacro()
###############################################################################
# Examples
###############################################################################
ecl_command_line_add_demo(command_line)
@@ -0,0 +1,92 @@
/**
* @file /src/examples/command_line.cpp
*
* @brief Demo program for the tclap header library.
*
* @date May, 2009
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <iostream>
#include <string>
#include "../../include/ecl/command_line.hpp"
/*****************************************************************************
** Using
*****************************************************************************/
using std::cout;
using std::cerr;
using std::endl;
using std::string;
using ecl::CmdLine;
using ecl::SwitchArg;
using ecl::ValueArg;
using ecl::UnlabeledValueArg;
using ecl::ArgException;
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char** argv) {
int test(0);
bool debug(false);
string nolabel;
std::cout << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << " Command Line Parsing" << std::endl;
std::cout << "***********************************************************" << std::endl;
std::cout << std::endl;
try {
// Supply a program description, argument separator (optional) and version number (optional).
CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.");
// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01");
// Add a boolean (flag, name, description), sets the default state to false unless it is found on the command line.
SwitchArg debugSwitch("d","debug","Enable debugging.");
// Add a boolean (flag, name, description, default)
// SwitchArg debug("d","debug","Enable debugging.", false);
cmd.add(debugSwitch);
// Add an int (flag,name,description,compulsory flag?,default value,help description of the type")
ValueArg<int> intArg("i","integer","An integer argument for testing.",false,5,"integer");
cmd.add(intArg);
// (one word argument name, long description, req/not req, default value, type)
UnlabeledValueArg<string> nolabelArg( "echo", "An unlabeled argument", false, "dude", "string" );
cmd.add(nolabelArg);
/*********************
** Parse
**********************/
cmd.parse(argc,argv);
debug = debugSwitch.getValue();
test = intArg.getValue();
nolabel = nolabelArg.getValue();
} catch ( ArgException &e )
{
cerr << "error: " << e.error() << " for arg " << e.argId() << endl;
}
cout << "Test Integer: " << test << endl;
if ( debug ) {
cout << "Debug Switch (bool): true" << endl;
} else {
cout << "Debug Switch (bool): false" << endl;
}
std::cout << "Echoing unlabelled arg: " << nolabel << std::endl;
std::cout << std::endl;
return 0;
}
@@ -0,0 +1,6 @@
###############################################################################
# Tests
###############################################################################
# currently broken
# ament_add_gtest(test_command_line command_line.cpp)
@@ -0,0 +1,82 @@
/**
* @file /src/test/command_line.cpp
*
* @brief Unit Test for the tclap header library.
*
* Unit Test for the tclap header library (ecl/command_line.hpp).
*
* @date May, 2009
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <gtest/gtest.h>
#include "../../include/ecl/command_line.hpp"
/*****************************************************************************
** Using
*****************************************************************************/
using ecl::CmdLine;
using ecl::SwitchArg;
using ecl::ValueArg;
using ecl::ArgException;
/*****************************************************************************
** Globals
*****************************************************************************/
static int myargc;
static char **myargv;
/*****************************************************************************
** Tests
*****************************************************************************/
TEST(CommandLineTests,verify) {
try {
// Supply a program description, argument separator (optional) and version number (optional).
CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.");
// CmdLine cmd("This is a test program to test the command line parsing facilities provided by TCLAP.", ' ', "0.01");
// Add a boolean (flag, name, description), sets the default state to false unless it is found on the command line.
SwitchArg debugSwitch("d","debug","Enable debugging.");
// Add a boolean (flag, name, description, default)
// SwitchArg debug("d","debug","Enable debugging.", false);
cmd.add(debugSwitch);
// Add an int (flag,name,description,compulsory flag?,default value,help description of the type")
ValueArg<int> intArg("i","integer","An integer argument for testing.",false,5,"integer");
cmd.add(intArg);
/*********************
** Parse
**********************/
cmd.parse(myargc, myargv); // RoS gtest 'make test' breaks here.
bool debug = debugSwitch.getValue();
int test = intArg.getValue();
EXPECT_EQ(5,test);
EXPECT_FALSE(debug);
} catch ( ArgException &e ) {
ADD_FAILURE() << "Failed to parse command line arguments";
}
}
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char **argv) {
myargc = argc;
myargv = argv;
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
+341
View File
@@ -0,0 +1,341 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1603023315">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1603023315" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="concepts" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1603023315" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1603023315.1844601879" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.381056006" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.2005115934" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder id="cdt.managedbuild.target.gnu.builder.base.162064148" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.233265941" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1816798423" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.1040357285" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1573831356" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.39590967" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.221822447" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.455255638" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.335430062" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.408196465" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.199938168" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/ecl/concepts"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src/test"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="concepts.null.746906967" name="concepts"/>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1603023315;cdt.managedbuild.toolchain.gnu.base.1603023315.1844601879;cdt.managedbuild.tool.gnu.c.compiler.base.1573831356;cdt.managedbuild.tool.gnu.c.compiler.input.39590967">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1603023315;cdt.managedbuild.toolchain.gnu.base.1603023315.1844601879;cdt.managedbuild.tool.gnu.cpp.compiler.base.1816798423;cdt.managedbuild.tool.gnu.cpp.compiler.input.1040357285">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="tests" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>tests</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="all" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>all</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="test" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments/>
<buildTarget>test</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
</cproject>
@@ -0,0 +1,78 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ecl_concepts</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>make</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>true</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,11 @@
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Changelog for package ecl_concepts
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1.0.6 (2020-01-11)
------------------
* bugfix a warning-as-error on a throw in a method declaration`#99 <https://github.com/stonier/ecl_core/pull/99>`_
0.61.13 (2016-05-03)
--------------------
* drop unused typedefs
@@ -0,0 +1,75 @@
##############################################################################
# Cmake
##############################################################################
cmake_minimum_required(VERSION 3.5)
project(ecl_concepts)
##############################################################################
# Find Packages
##############################################################################
# Turn -isystem off. Actually like to see warnings from underlying packages
# and regardless, have run into trouble because of the ordering it induces.
set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE)
find_package(ament_cmake_ros REQUIRED)
find_package(ecl_build REQUIRED)
find_package(ecl_config REQUIRED)
find_package(ecl_type_traits REQUIRED)
##############################################################################
# Project configuration
##############################################################################
ament_package_xml()
ecl_enable_cxx14_compiler()
ecl_enable_cxx_warnings()
##############################################################################
# Header Library Targets
##############################################################################
add_library(${PROJECT_NAME} INTERFACE)
target_link_libraries(
${PROJECT_NAME}
INTERFACE
ecl_config::ecl_config
ecl_type_traits::ecl_type_traits
)
target_include_directories(
${PROJECT_NAME}
INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
##############################################################################
# Sources
##############################################################################
add_subdirectory(include)
add_subdirectory(src)
##############################################################################
# Exports
##############################################################################
# Downstream CMake3 compatibility
ament_export_targets(${PROJECT_NAME})
# Downstream CMake2 compatibility
ament_export_include_directories(include)
ament_export_dependencies(
ecl_config
ecl_type_traits
)
ament_package()
@@ -0,0 +1,19 @@
/**
@page changelogConcepts ChangeLog
@section Changes
- <b> Feb 11</b> : Testing class for dynamic containers.
- <b> Oct 10</b> : Testing class added for ecl compatible input, output and input-output devices.
- <b> Jul 09</b> : Testing class for nullary funciton objects.
- <b> Jul 09</b> : Testing class for ecl and std streams.
- <b> May 09</b> : Testing class for blueprint instantiation.
- <b> May 09</b> : Testing class for simple containers and byte containers.
- <b> May 09</b> : Macros : tools for simple concept checking finalised.
@section Bugs
- <b> Feb 11</b> : Fixed the byte tests in the container concept to handle platform dependant typedef'ing of char.
- <b> Jul 09</b> : Non-uniqueness problem when using the concept check twice in a program. Added a unique macro to fix.
**/
@@ -0,0 +1,155 @@
/**
@page blueprintsConcept Blueprints
@section overviewSection Overview
Blueprints store a minimal ruleset for instantiating or configuring
specialised representations of a class such as a uniformly filled
array, or the unit vectors of each dimension. This can of course,
be done inside a class, but via the blueprints, we introduce
an extra layer of indirection that helps get around two issues.
@subsection whySection Problems with Constructor Overloading
Overloading the constructor can become difficult when you cannot find a
unique signature for one of many constructor calls. For example,
@code
A(double x, double y);
A(double r, double angle);
@endcode
Traditionally, the way around it would be to define
a static function within the class. However, this runs into difficulty
when incorporating a 3rd party library - you cannot add static functions
to pre-existing classes. This is often very desirable if you want to create
your own pre-defined instantiations of things like matrices. So in these cases,
an externally applied method is necessary.
@subsection whyAssignment Problems with Assignment
Even when there are static methods available to generate specialised instances,
operator assignment will usually result in a construction followed by a
full copy, which is expensive.
@code
Array<int,4> array;
//...
array = Array<int,4>::ConstantArray(3);
@endcode
@subsection whatSection How BluePrints Work
By generating a minimal blueprint and then passing to a class's assignment operator,
or forcing the blueprint to generate an instance externally, we resolve the two
problems above. In some cases we also get a speedup if we need to repeatedly use
a blueprint, in sofar as the blueprint can save and store the state required
to generate the class from the blueprint.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit for which you are
running compile time checks on your blueprint classes.
@code
#include <ecl/concepts.hpp>
using ecl::BluePrintConcept;
@endcode
Since it only uses macros and templatised objects, no linking is required for just this feature.
@section creation Concept Definition
Creating a blueprint class can be done in any namespace, it just has to satisfy the
three conditions outlined below:
- base_type : a typedef for the target class for which they generate instances/configurations.
- base_type instantiate() : they must be able to instantiate a base_type object.
- void apply(base_type&) : they must be able to apply this configuration to an existing object.
A simple example for a blueprint related to the Foo class:
@code
class Foo {
public:
Foo(std::string &id) : name(id) {}
void changeName(std::string &new_name) { name = new_name; }
// ...
private:
std::string name;
};
class SimpleFoo {
public:
typdef Foo base_type;
base_type instantiate() { return Foo("simpleton"); }
void apply(base_type& foo) {
foo.changeName("simpleton");
}
@endcode
That, of course, was complicating a redundantly trivial situation.
A better, practicial example is the ConstantArray blueprint for array containers in ecl_containers.
@section Usage
@subsection check Convenient BluePrint Class Handling
While its possible to simply use the blueprint class in the following manner (in this
example, ConstrantArray is a blueprint):
@code
Array<int,4> array = ConstantArray<int,4>()(3).instantiate();
ConstantArray<int,4>()(3).apply(array);
@endcode
It's not very convenient. I usually wrap them in a factory class which possesses static methods
that will either result in instantiations or blueprints. A direct implementation of such a factory might like like this:
@code
Array<int,4> array = ArrayFactory<int,4>::ConstantArray(3); // Construction
ArrayFactory<int,4>::ConstantArray(array,3); // Assignment
@endcode
This is about as far as you can go with a factory class working for a 3rd party class that you
cannot modify. If however, you can modify the base_type class, then it is possible to
insert a constructor and assignment operator to directly handle blueprints, e.g. in the
Array container class (ecl_containers), we have the following declarations:
@code
template<typename T>
Array(const T& blueprint) {
compile_time_concept_check(BluePrintConcept<T>);
blueprint.apply(*this);
}
template<typename T>
void operator=(const T& blueprint) {
compile_time_concept_check(BluePrintConcept<T>);
blueprint.apply(*this);
}
@endcode
Then we can handle both construction and assignment equivalently:
@code
Array<int,4> array = ArrayFactory<int,4>::ConstantArray(3); // Construction
array = ArrayFactory<int,4>::ConstantArray(3); // Assignment (no costly copy)
@endcode
Furthermore, if our base class inherits the factory, then we can simplify this further:
@code
Array<int,4> array = Array<int,4>::ConstantArray(3); // Construction
array = Array<int,4>::ConstantArray(3); // Assignment (no costly copy)
@endcode
@section Examples
These are the relevant components for array type blueprints which can be found in ecl_containers.
- ecl::Array
- ecl::blueprints::ArrayFactory
- ecl::blueprints::ConstantArray
@section Changelog
- Blueprint testing class added [May 09].
**/
@@ -0,0 +1,67 @@
/**
@page containersConcept Containers
@section overviewSection Overview
Containers have a few properties in common that can simplify the
passing of or the development of methods that use generic containers. Rather
than having a suite of overloaded functions, a simple template argument with
a concept check will suffice for all variants.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit for which you are
running compile time checks on your blueprint classes.
@code
#include <ecl/concepts.hpp>
using ecl::ContainerConcept;
using ecl::DynamicContainerConcept;
using ecl::UnsignedByteContainerConcept;
using ecl::SignedByteContainerConcept;
@endcode
Since it only uses macros and templatised objects, no linking is required for just this feature.
@section creation Container Concept Definition
Classes passing the ContainerConcept must satisfy:
- begin() : a method for retrieving a pointer/iterator to the start of the container.
- end() : a method for retrieving a pointer/iterator to the end of the container.
- size() : a method for retrieving the number of elements stored in the container.
@subsection dynamic Dynamic Containers
Classes passing the DynamicContainerConcept must additionally satisfy:
- resize(int) : a method for resizing the number of elements managed by the container.
@subsection byte Byte Containers
In addition, if it is testing for a byte container, then it will do a check on the value type
in the container and fail if it is not a char (uses a trick via specialisations and private
constructors to ensure a compile time failure).
@section Usage
Use with the compile time concept check whenever you wish to check for a container template class.
@code
template<typename T>
void f(const T& container) {
compile_time_concept_check(ContainerConcept<T>);
unsigned int size = container.size();
//...
}
template<typename T>
void g(const T& byte_container) {
compile_time_concept_check(SignedByteContainerConcept<T>);
unsigned int size = container.size();
char c = container[0];
//...
}
@endcode
**/
@@ -0,0 +1,77 @@
/**
@page devicesConcept Devices
@section overviewSection Overview
Rather than provide a complex inheritable family of classes with super-imposed mixins
to represent the varying degrees of generic device functionalities
(e.g. source, sink, seekable...) a rather more simpler (and faster) concept
based method is used for the devices in ecl's input-output library. The concepts
are required to validate the classes for use by higher level structures such as streams.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit for which you are
running compile time checks on your blueprint classes.
@code
#include <ecl/concepts.hpp>
using ecl::InputCharDeviceConcept;
using ecl::OutputCharDeviceConcept;
using ecl::InputOutputCharDeviceConcept;
using ecl::InputByteDeviceConcept;
using ecl::OutputByteDeviceConcept;
using ecl::InputOutputByteDeviceConcept;
@endcode
Since it only uses macros and templatised objects, no linking is required for just this feature.
@section creation Concept Definitions
@subsection InputCharDevice
An input device class has to satisfy the following conditions:
- long read(char &c) : read a single character from the device buffer.
- long read(char *s, unsigned long n) : read a char buffer from the device buffer.
@subsection OutputCharDevice
An output device class has to satisfy the following conditions:
- long write(char &c) : write a single character from the device buffer.
- long write(char *s, unsigned long n) : write a char buffer from the device buffer.
- void flush() : a method for flushing the output device buffer to the device.
@subsection InputOutputCharDevice
An input-output device class has to satisfy the conditions required by both input and output devices
simultaneously.
@subsection ByteDevice
The three byte device concepts are similar except they add additional read/write capabilities for the other
is_byte types (refer to ecl_mpl's type traits). Namely char, signed char and unsigned char.
@section Usage
Generally, you won't need to use these directly. Rather they're embedded in other ecl objects
such as streams. However, a simple example of a device function definition and the concept check usage is outlined below.
@code
#include <ecl/concepts/devices.hpp>
using ecl::InputCharDevice;
template <typename Device>
class MyStream {
public:
MyStream(Device *device) {
compile_time_concept_check(InputCharDeviceConcept<Device>);
}
};
@endcode
**/
@@ -0,0 +1,42 @@
/**
@page nullaryFunctionConcept Nullary Functions
@section overviewSection Overview
Nullary functions are defined as an object (c++ class/struct) that is
sometimes otherwise known as callable without any argument passing.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit for which you are
running compile time checks on your blueprint classes.
@code
#include <ecl/concepts.hpp>
using ecl::NullaryFunctionConcept;
@endcode
Since it only uses macros and templatised objects, no linking is required for just this feature.
@section creation Concept Definition
Creating a class can be done in any namespace, it just has to satisfy the
conditions outlined below:
- operator()() : a method for executing the nullary function object.
- typedef result_type : a typedef to the return type of the operator.
@section Usage
Use with the compile time concept check whenever you wish to check for a nullary function object input.
For example, the Thread class (ecl_threads) utilises this in a similar way to that outlined
below:
@code
template<typename F>
Thread(F function) {
compile_time_concept_check(NullaryFunctionConcept<F>);
}
@endcode
**/
@@ -0,0 +1,65 @@
/**
@page streamsConcept Streams
@section overviewSection Overview
Many of the ecl classes are streamable, in order to provide quick visual
debugging of its contents. Typically in c++ the default streaming object
is the ostream object, however the io module here extends streaming
functionalities to almost every device. The important caveat though, is
they do not use the c++ iostream overheads (these are very costly).
In order to accomodate both (and also perhaps third party streams), the
streams concept has been defined so streaming with a generalised template
function is convenient.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit for which you are
running compile time checks on your blueprint classes.
@code
#include <ecl/concepts.hpp>
using ecl::StreamsConcept;
@endcode
Since it only uses macros and templatised objects, no linking is required for just this feature.
@section creation Concept Definition
A streaming class just has to satisfy the following conditions:
- operator << : can stream characters.
- flush() : a method which writes the stream to an underlying device or object.
Note that the object instance <i>cout</i> automatically satisfies these.
@section Usage
A simple example of a streaming function definition and the concept check usage is outlined below.
@code
#include <ecl/concepts/streams.hpp>
using ecl::Stream;
class MyMatrix {
public:
template <typename OutputStream>
friend OutputStream& operator << (OutputStream &ostream, MyMatrix &matrix);
};
template <typename OutputStream>
OutputStream& operator << (OutputStream &ostream, MyMatrix &matrix) {
compile_time_concept_check(StreamConcept<OutputStream>);
ostream << "Hello Dudes, this is a matrix\n";
ostream.flush();
return ostream;
}
@endcode
**/
@@ -0,0 +1,116 @@
/**
\mainpage
\htmlinclude manifest.html
\section packageSummary Package Summary
One of the problem with template usage occurs occurs in the following scenario.
For templatised functions and classes, the input template arguments
usually have little or no restriction on the class that can be used, e.g.
@code
template <typename T>
void f(T input) {
// use some aspect of T's interface
}
@endcode
Of course the compile will fail if you try to use an input type, T, that doesn't have the
specialised interface you want, but the compile time error message is often very verbose
and its difficult to find the error. An idea which is merging into the c++ mainstream as
well as that used by the boost concept checking library is to characterise common
behaviours into <i>Concepts</i>. A simplified version of this is utilised here.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit that requires
compilation of signals and/or slots.
@code
#include <ecl/concepts.hpp>
// The concept definition/validation classes.
using ecl::BluePrintConcept;
using ecl::ContainerConcept;
using ecl::SignedByteContainerConcept;
using ecl::UnsignedByteContainerConcept;
using ecl::NullaryFunctionConcept;
using ecl::StreamConcept;
using ecl::InputCharDeviceConcept;
using ecl::OutputCharDeviceConcept;
using ecl::InputOutputCharDeviceConcept;
using ecl::InputByteDeviceConcept;
using ecl::OutputByteDeviceConcept;
using ecl::InputOutputByteDeviceConcept;
@endcode
Since it is a collection of macros and template functions/classes, no linking
is required if you are only utilising this functionality.
@section Usage
Usage is fairly simple. There are two steps:
- <i>Concept Test</i> : must be hand crafted to check all the characteristic behaviours of a concept.
- <i>Concept Check</i> : whenever required, call the concept check which runs the concept test to verify compliance.
@subsection conceptTestSection Concept Test
If you are using an existing concept (see below), skip through to the concept check. Otherwise:
- Decide on a name for the concept.
- Create a templatised class of that name with a single arbitrary template argument (the class to be tested).
- Hand craft the testing function within that class using compile_time_concept_test().
The example here is the same as that used in src/tests/concepts.cpp:
@code
template <typename T>
class MyConcept {
public:
compile_time_concept_test(MyConcept) {
T t;
t.apply(); // This is the characteristic function required by this concept.
}
};
@endcode
Hand-crafting the concept testing function will often require a little care to ensure the concept
is appropriately covered.
@subsection conceptCheckSection Concept Check
Once you have a test in place, you only need to insert compile_time_concept_check() calls wherever you need them.
Keep in mind, the sole purpose of these is to provide convenient error logs when something
goes wrong.
@code
class A { // This class has the MyConcept functionality.
public:
// The following function characterises the MyConcept concept.
// Comment this line and any MyConcept concept assertion
// check will fail in compile time.
void apply() {};
};
int main() {
compile_time_concept_check(MyConcept<A>); // Checks A for compliance to the MyConcept concept.
return 0;
}
@endcode
@section conceptsList Existing Concepts
- @ref blueprintsConcept "BluePrints" - checks for blueprint functionality as defined in ecl_utilities.
- @ref containersConcept "Containers" - also bytecontainer, simple checks for basic prerequisite container methods.
- @ref nullaryFunctionConcept "NullaryFunctions" - function objects which require no arguments in execution.
- @ref streamsConcept "Streams" - any class with basic char streaming capabilities.
- @ref devicesConcept "Devices" - device functionalities compatible to those in ecl_devices.
@section Examples
- src/test/concepts.cpp
@section ChangeLog
- @ref changelogConcepts "ChangeLog"
*/
@@ -0,0 +1,22 @@
/**
* @namespace ecl
*
* @brief Embedded control libraries.
*
* Various core libraries useful for embedded control systems.
**/
/**
* @namespace ecl::concepts
*
* @brief Supporting elements and interfaces.
*
* These provide support for the elements in this package. They are not
* intended to be directly visible to the user.
**/
/**
* @namespace ecl::concepts::tests
*
* @brief Frameworks created for the unit tests.
*
* Includes everything that was also added for compiling the unit tests.
**/
@@ -0,0 +1,5 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(ecl)
@@ -0,0 +1,14 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(concepts)
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl)
@@ -0,0 +1,28 @@
/**
* @file /include/ecl/concepts.hpp
*
* @brief Compile time meta-programming concepts.
*
* Compile time meta-programming concepts.
*
* @date May, 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_HPP_
#define ECL_CONCEPTS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "concepts/macros.hpp"
#include "concepts/blueprints.hpp"
#include "concepts/containers.hpp"
#include "concepts/devices.hpp"
#include "concepts/nullary_function.hpp"
#include "concepts/streams.hpp"
#endif /* ECL_CONCEPTS_HPP_ */
@@ -0,0 +1,7 @@
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl/concepts)
@@ -0,0 +1,58 @@
/**
* @file /include/ecl/concepts/blueprints.hpp
*
* @brief Lightweight objects used for custom class instantiation and assignment.
*
* @date May, 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_BLUEPRINTS_HPP_
#define ECL_CONCEPTS_BLUEPRINTS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "macros.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Concept [BluePrint]
*****************************************************************************/
/**
* @brief Defines validating functionality for the @ref blueprintsConcept "blueprint concept".
**/
template <typename Implementation>
class BluePrintConcept {
public:
/**
* @brief Implements a concept test for blueprints.
*
* There are three conditions required by blueprints:
* - base_type : a typedef for the target class for which they generate instances/configurations.
* - base_type instantiate() : they must be able to instantiate a base_type object.
* - void apply(base_type&) : they must be able to apply this configuration to an existing object.
*/
ecl_compile_time_concept_test(BluePrintConcept)
{
target = blue_print.instantiate();
blue_print.apply(target);
}
private:
typename Implementation::base_type target;
Implementation blue_print;
};
} // namespace ecl
#endif /* ECL_CONCEPTS_BLUEPRINTS_HPP_ */
@@ -0,0 +1,342 @@
/**
* @file /include/ecl/concepts/containers.hpp
*
* @brief Defines and validates the functionality for the <i>container</i> concept.
*
* @date May 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_
#define ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <ecl/config/ecl.hpp>
#include <ecl/type_traits/fundamental_types.hpp>
#include "macros.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Concept [Container]
*****************************************************************************/
/**
* @brief Defines validating functionality for the @ref containersConcept "container concept".
**/
template <typename Implementation>
class ContainerConcept {
public:
/**
* @brief Implements a concept test for containers.
*
* The following conditions are required by containers:
*
* - begin() : a method for retrieving a pointer/iterator to the start of the container.
* - end() : a method for retrieving a pointer/iterator to the end of the container.
* - size() : a method for retrieving the number of elements stored in the container.
* - value_type : a typedef for the element type stored in the container.
*/
ecl_compile_time_concept_test(ContainerConcept)
{
iter = container.begin();
iter = container.end();
unsigned int n;
n = container.size();
(void) n; // remove set but not used warnings.
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation container;
typename Implementation::iterator iter;
};
/**
* @brief Defines validating functionality for the dynamic @ref containersConcept "container concept".
**/
template <typename Implementation>
class DynamicContainerConcept {
public:
/**
* @brief Implements a concept test for containers.
*
* The following conditions are required by containers:
*
* - begin() : a method for retrieving a pointer/iterator to the start of the container.
* - end() : a method for retrieving a pointer/iterator to the end of the container.
* - size() : a method for retrieving the number of elements stored in the container.
* - resize(int) : a method for resizing the container.
* - value_type : a typedef for the element type stored in the container.
*/
ecl_compile_time_concept_test(DynamicContainerConcept)
{
iter = container.begin();
iter = container.end();
unsigned int n;
n = container.size();
container.resize(1);
(void) n; // remove set but not used warnings.
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation container;
typename Implementation::iterator iter;
};
/**
* @cond DO_NOT_DOXYGEN
*/
namespace concepts {
/**
* @brief Back end to the signed byte test check.
*
* Used to invalidate with a private constructor when the condition is right.
* This is the one that will show up in the printout for a compile time
* error.
*
* Do not use this one directly, use SignedByteTestCheck to make use of it.
*/
template <typename T, bool Result=false>
class SignedByteTest {
private:
SignedByteTest() {}
};
/**
* @brief Back end to the signed byte test check.
*
* Used to toggle a valid public constructor when the condition is right.
* This is the one that will show up in the printout for a compile time
* error.
*
* Do not use this one directly, use SignedByteTestCheck to make use of it.
*/
template <typename T>
class SignedByteTest<T,true> {
public:
SignedByteTest() {}
};
/**
* @brief Back end to the unsigned byte test check.
*
* Used to invalidate with a private constructor when the condition is right.
* This is the one that will show up in the printout for a compile time
* error.
*
* Do not use this one directly, use UnsignedByteTestCheck to make use of it.
*/
template <typename T, bool Result=false>
class UnsignedByteTest {
private:
UnsignedByteTest() {}
};
/**
* @brief Back end to the unsigned byte test check.
*
* Used to toggle a valid public constructor when the condition is right.
* This is the one that will show up in the printout for a compile time
* error.
*
* Do not use this one directly, use UnsignedByteTestCheck to make use of it.
*/
template <typename T>
class UnsignedByteTest<T,true> {
public:
UnsignedByteTest() {}
};
/**
* @brief Front end to the signed byte test check.
*
* Forces it to throw a compile time error if the check fails because
* the parent implementation will have a private constructor.
*/
template <typename T>
class SignedByteTestCheck : public SignedByteTest<T, ecl::is_signed_byte<T>::value > {};
/**
* @brief Front end to the unsigned byte test check.
*
* Forces it to throw a compile time error if the check fails because
* the parent implementation will have a private constructor.
*/
template <typename T>
class UnsignedByteTestCheck : public UnsignedByteTest<T, ecl::is_unsigned_byte<T>::value > {};
/**
* @brief Used to invalidate non char types storage.
*
* This is the default template class for the unsigned character test - if the
* specialisation from the byte container element type being tested is
* not a char type, it will use this and result in a compile time error
* since the constructor is private!
*/
template <typename T>
class ByteTest {
private:
ByteTest() {}
};
/**
* @brief Used to validate char types storage.
*
* Containers with a unsigned char storage element will use this specialisation
* when doing the byte container concept check. This results in no
* compile time error as the constructor is public (as opposed to
* the generalised instance which has a private constructor).
*/
template <>
class ByteTest<unsigned char> {
public:
ByteTest() {}
};
/**
* @brief Used to validate char types storage as byte storage.
*/
template <>
class ByteTest<char> {
public:
ByteTest() {}
};
/**
* @brief Used to validate signed char types storage as byte storage.
*/
template <>
class ByteTest<signed char> {
public:
ByteTest() {}
};
} // namespace concepts
/**
* @endcond
*/
/**
* @brief Defines validating functionality for the <i>byte container</i> concept.
**/
template <typename Implementation>
class UnsignedByteContainerConcept {
public:
/**
* @brief Implements a concept test for byte containers.
*
* The following conditions are required by byte containers:
* - begin() : a method for retrieving a pointer/iterator to the start of the container.
* - end() : a method for retrieving a pointer/iterator to the end of the container.
* - size() : a method for retrieving the number of elements stored in the container.
* - value_type : a typedef for the element type stored in the container, must be unsigned char.
*/
ecl_compile_time_concept_test(UnsignedByteContainerConcept)
{
typedef typename Implementation::value_type element_type;
iter = container.begin();
iter = container.end();
unsigned int n;
n = container.size();
// If not a char, this results in a private call -> compile time error!
concepts::UnsignedByteTestCheck<element_type> char_test;
(void) n; // remove set but unused warnings.
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation container;
typename Implementation::iterator iter;
};
/**
* @brief Defines validating functionality for the <i>signed byte container</i> concept.
**/
template <typename Implementation>
class SignedByteContainerConcept {
public:
/**
* @brief Implements a concept test for byte containers.
*
* The following conditions are required by byte containers:
* - begin() : a method for retrieving a pointer/iterator to the start of the container.
* - end() : a method for retrieving a pointer/iterator to the end of the container.
* - size() : a method for retrieving the number of elements stored in the container.
* - value_type : a typedef for the element type stored in the container, must be signed char.
*/
ecl_compile_time_concept_test(SignedByteContainerConcept)
{
typedef typename Implementation::value_type element_type;
iter = container.begin();
iter = container.end();
unsigned int n;
n = container.size();
// If not a char, this results in a private call -> compile time error!
concepts::SignedByteTestCheck<element_type> char_test;
(void) n;
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation container;
typename Implementation::iterator iter;
};
/**
* @brief Defines validating functionality for the <i>byte container</i> concept.
*
* Elements stored in this container can be either signed, unsigned or char type.
**/
template <typename Implementation>
class ByteContainerConcept {
public:
/**
* @brief Implements a concept test for byte containers.
*
* The following conditions are required by byte containers:
* - begin() : a method for retrieving a pointer/iterator to the start of the container.
* - end() : a method for retrieving a pointer/iterator to the end of the container.
* - size() : a method for retrieving the number of elements stored in the container.
* - value_type : a typedef for the element type stored in the container, must be char, signed char or unsigned char.
*/
ecl_compile_time_concept_test(ByteContainerConcept)
{
typedef typename Implementation::value_type element_type;
iter = container.begin();
iter = container.end();
unsigned int n;
n = container.size();
// If not a char, this results in a private call -> compile time error!
concepts::ByteTest<element_type> char_test;
(void) n; // remove set but unused warnings.
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation container;
typename Implementation::iterator iter;
};
} // namespace ecl
#endif /* ECL_CONCEPTS_CONCEPTS_CONTAINERS_HPP_ */
@@ -0,0 +1,320 @@
/**
* @file /include/ecl/concepts/devices.hpp
*
* @brief Defines validating functionality for the <i>device</i> concepts.
*
* Defines validating functionality for the <i>device</i> concepts.
*
* @date October 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_DEVICES_HPP_
#define ECL_CONCEPTS_DEVICES_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "macros.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Concept [InputCharDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "input char device concept".
*
* This checks if a device can handle input of char types.
**/
template <typename Implementation>
class InputCharDeviceConcept {
public:
/**
* @brief Implements a concept test for input devices.
*
* The following conditions are required by input devices:
*
* - long read(char &c) : read a single character from the device buffer.
* - long read(char *s, unsigned long n) : read a char buffer from the device buffer.
*/
ecl_compile_time_concept_test(InputCharDeviceConcept) {
char c;
char buffer[10];
long no_read;
bool result;
result = input_char_device.open();
no_read = input_char_device.read(c);
no_read = input_char_device.read(buffer,10);
(void) no_read; // remove set but unused warnings
(void) result; // remove set but unused warnings
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation input_char_device;
};
/*****************************************************************************
** Concept [OutputCharDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "output char device concept".
*
* This checks if a device can handle output of char types.
**/
template <typename Implementation>
class OutputCharDeviceConcept {
public:
/**
* @brief Implements a concept test for output char devices.
*
* The following conditions are required by output char devices:
*
* - long write(char &c) : write a single character to the device buffer.
* - long write(char *s, unsigned long n) : write a char buffer to the device buffer.
* - void flush() : a method for flushing the output device buffer to the device.
*/
ecl_compile_time_concept_test(OutputCharDeviceConcept)
{
long no_written;
char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
bool result;
result = output_char_device.open();
no_written = output_char_device.write('\n');
no_written = output_char_device.write(write_buffer,5);
output_char_device.flush();
(void) no_written; // remove set but unused warnings
(void) result; // remove set but unused warnings
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation output_char_device;
};
/*****************************************************************************
** Concept [InputOutputByteDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "input-output char device concept".
*
* This checks if a device can handle input-output of char types.
**/
template <typename Implementation>
class InputOutputCharDeviceConcept {
public:
/**
* @brief Implements a concept test for input-output byte devices.
*
* The following conditions are required by input-output byte devices:
*
* - long read(char &c) : read a single character from the device buffer.
* - long read(char *s, unsigned long n) : read a char buffer from the device buffer.
* - long write(char &c) : write a single character to the device buffer.
* - long write(char *s, unsigned long n) : write a char buffer to the device buffer.
* - void flush() : a method for flushing the output device buffer to the device.
*/
ecl_compile_time_concept_test(InputOutputCharDeviceConcept)
{
char c;
char read_buffer[10];
long no_read;
no_read = input_output_char_device.read(c);
no_read = input_output_char_device.read(read_buffer,10);
long no_written;
char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
no_written = input_output_char_device.write('\n');
no_written = input_output_char_device.write(write_buffer,5);
input_output_char_device.flush();
(void) no_written;
(void) no_read;
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation input_output_char_device;
};
/*****************************************************************************
** Concept [InputByteDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "input byte device concept".
*
* This checks if a device can handle input of all char types
* (char, signed char, unsigned char).
**/
template <typename Implementation>
class InputByteDeviceConcept {
public:
/**
* @brief Implements a concept test for input devices.
*
* The following conditions are required by input devices:
*
* - long read(char &c) : read a single character from the device buffer.
* - long read(char *s, unsigned long n) : read a char buffer from the device buffer.
*
* Along with the same function implemented for signed and unsigned char types.
*/
ecl_compile_time_concept_test(InputByteDeviceConcept) {
signed char sc;
signed char sbuffer[10];
char c;
char buffer[10];
unsigned char usc;
unsigned char usbuffer[10];
long no_read;
bool result;
result = input_byte_device.isOpen();
no_read = input_byte_device.read(sc);
no_read = input_byte_device.read(sbuffer,10);
no_read = input_byte_device.read(c);
no_read = input_byte_device.read(buffer,10);
no_read = input_byte_device.read(usc);
no_read = input_byte_device.read(usbuffer,10);
(void) result;
(void) no_read;
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation input_byte_device;
};
/*****************************************************************************
** Concept [OutputByteDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "output byte device concept".
*
* This checks if a device can handle output of all char types
* (char, signed char, unsigned char).
**/
template <typename Implementation>
class OutputByteDeviceConcept {
public:
/**
* @brief Implements a concept test for output byte devices.
*
* The following conditions are required by output byte devices:
*
* - long write(char &c) : write a single character to the device buffer.
* - long write(char *s, unsigned long n) : write a char buffer to the device buffer.
* - void flush() : a method for flushing the output device buffer to the device.
*
* Along with the write function implemented for signed and unsigned char types.
*/
ecl_compile_time_concept_test(OutputByteDeviceConcept)
{
long no_written;
signed char sc = '\n';
char c = '\n';
unsigned char usc = 0x01;
signed char s_write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
unsigned char us_write_buffer[] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
bool result;
result = output_byte_device.isOpen();
no_written = output_byte_device.write(sc);
no_written = output_byte_device.write(c);
no_written = output_byte_device.write(usc);
no_written = output_byte_device.write(s_write_buffer,5);
no_written = output_byte_device.write(write_buffer,5);
no_written = output_byte_device.write(us_write_buffer,5);
output_byte_device.flush();
(void) no_written;
(void) result;
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation output_byte_device;
};
/*****************************************************************************
** Concept [InputOutputByteDevice]
*****************************************************************************/
/**
* @brief Validates functionality for the @ref devicesConcept "input-output byte device concept".
*
* This checks if a device can handle input-output of all char types
* (char, signed char, unsigned char).
**/
template <typename Implementation>
class InputOutputByteDeviceConcept {
public:
/**
* @brief Implements a concept test for input-output byte devices.
*
* The following conditions are required by input-output byte devices:
*
* - long read(char &c) : read a single character from the device buffer.
* - long read(char *s, unsigned long n) : read a char buffer from the device buffer.
* - long write(char &c) : write a single character to the device buffer.
* - long write(char *s, unsigned long n) : write a char buffer to the device buffer.
* - void flush() : a method for flushing the output device buffer to the device.
*
* Along with the read/write functions implemented for signed and unsigned char types.
*/
ecl_compile_time_concept_test(InputOutputByteDeviceConcept)
{
signed char sc;
signed char sbuffer[10];
char c;
char buffer[10];
unsigned char usc;
unsigned char usbuffer[10];
long no_read;
bool result;
result = input_output_byte_device.isOpen();
no_read = input_output_byte_device.read(sc);
no_read = input_output_byte_device.read(sbuffer,10);
no_read = input_output_byte_device.read(c);
no_read = input_output_byte_device.read(buffer,10);
no_read = input_output_byte_device.read(usc);
no_read = input_output_byte_device.read(usbuffer,10);
long no_written;
sc = '\n';
c = '\n';
usc = 0x01;
signed char s_write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
char write_buffer[] = { 'd', 'u', 'd', 'e', '\n' };
unsigned char us_write_buffer[] = { 0x01, 0x02, 0x03, 0x04, 0x05 };
no_written = input_output_byte_device.write(sc);
no_written = input_output_byte_device.write(c);
no_written = input_output_byte_device.write(usc);
no_written = input_output_byte_device.write(s_write_buffer,5);
no_written = input_output_byte_device.write(write_buffer,5);
no_written = input_output_byte_device.write(us_write_buffer,5);
input_output_byte_device.flush();
(void) no_read;
(void) no_written;
(void) result;
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation input_output_byte_device;
};
} // namespace ecl
#endif /* ECL_CONCEPTS_DEVICES_HPP_ */
@@ -0,0 +1,126 @@
/**
* @file /include/ecl/concepts/macros.hpp
*
* @brief Mechanisms enabling compile time checking of metaprogramming concepts.
*
* @date May, 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_MACROS_HPP_
#define ECL_CONCEPTS_MACROS_HPP_
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
namespace concepts {
/*****************************************************************************
** Classes
*****************************************************************************/
/**
* @cond DO_NOT_DOXYGEN
*/
/**
* @brief Initiates the concept checking function test.
*
* The function test resides in the void function pointer argument. When
* this class gets instantiated, the code in the void function pointer will
* compile.
*/
template <void(*)()> struct InstantiateConceptCheck {};
/**
* This function runs the concept check, and if it fails, the compile time
* error will be reported as having come from here by including the name
* of this function (hence the use of caps and the appropriate naming of the
* function) in the error output message.
*/
template <class Model>
void CONCEPT_CHECK_FAILED()
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnonnull"
((Model*)0)->~Model();
#pragma GCC diagnostic pop
}
/**
* @brief Instantiates the compile time concept error checking process.
*
* Instantiates the compile time error checking process. If it ultimately
* fails, then there will be an error message emitted by this class (hence
* the use of caps and the appropriate naming of the class).
*/
template <class Model>
struct CONCEPT_CHECK
{
InstantiateConceptCheck< CONCEPT_CHECK_FAILED<Model> > x; /**< @brief Instantiates the compile time concept checking code. **/
enum { instantiate = 1 /**< @brief Simple flag to report success of the concept check. **/ };
};
/**
* @endcond
*/
} // namespace concepts
} // namespace ecl
#define ecl_concept_check_name_expand(Name) ConceptCheck ## Name
#define ecl_concept_check_name(Name) ecl_concept_check_name_expand(Name)
/**
* @addtogroup Macros
* @{
**/
/**
* @def ecl_compile_time_concept_check
*
* @brief Compile time concept checking assertion.
*
* This macro checks a class to verify if it conforms to a compile time metaprogramming
* concept.
*
* <b>Usage:</b>
*
* The input argument to this macro function is the concept class type with
* the testing class as its template parameter.
* @code
* ecl_compile_time_concept_check(MyConcept<A>);
* @endcode
*/
#define ecl_compile_time_concept_check( Model ) \
enum { ecl_concept_check_name(__LINE__) = ecl::concepts::CONCEPT_CHECK< Model >::instantiate }
/**
* @def ecl_compile_time_concept_test
*
* @brief Convenient notational macro for setting up a concept testing function.
*
* The actual mechanics of concept testing has to be implemented in the concept class' destructor.
* This macro is purely just a notational convenience that makes it clear when programming
* the precise meaning of what is intended for your concept class.
*
* <b>Usage:</b>
*
* @code
* class MyConcept {
* public:
* ecl_compile_time_concept_test(MyConcept)
* {
* // compile time concept checks here.
* }
* };
* @endcode
*/
#define ecl_compile_time_concept_test( Model ) \
ecl_compile_time_concept_check( Model ); \
~Model()
/**
* @}
**/
#endif /* ECL_CONCEPTS_MACROS_HPP_ */
@@ -0,0 +1,65 @@
/**
* @file /include/ecl/concepts/nullary_function.hpp
*
* @brief Defines validating the functionality for the <i>nullary function</i> concept.
*
* @date July 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_NULLARY_FUNCTION_HPP_
#define ECL_CONCEPTS_NULLARY_FUNCTION_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include <ecl/config/macros.hpp>
#include "macros.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Concept [Container]
*****************************************************************************/
/**
* @brief Defines validating functionality for the @ref nullaryFunctionConcept "nullary function concept".
**/
template <typename Implementation>
class NullaryFunctionConcept {
public:
/**
* @brief Implements a concept test for nullary functions.
*
* The following conditions are required by nullary functions:
*
* - operator()() : a method which calls the nullary function.
* - result_type : a typedef for the return type of the nullary function.
*/
ecl_compile_time_concept_test(NullaryFunctionConcept)
{
typedef typename Implementation::result_type ECL_UNUSED return_type;
function();
// Unfortunately we can't test for the result type to match a certain value here
// as this would then have 2 template arguments with a separating comma. That throws
// the compile_time_concept_check macro into thinking it has two macro arguments.
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation function;
};
} // namespace ecl
#endif /* ECL_CONCEPTS_NULLARY_FUNCTION_HPP_ */
@@ -0,0 +1,63 @@
/**
* @file /include/ecl/concepts/streams.hpp
*
* @brief Defines and validates functionality for the <i>streams</i> concept.
*
* @date July 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONCEPTS_STREAMS_HPP_
#define ECL_CONCEPTS_STREAMS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "macros.hpp"
/*****************************************************************************
** Namespaces
*****************************************************************************/
namespace ecl {
/*****************************************************************************
** Concept [Stream]
*****************************************************************************/
/**
* @brief Defines validating functionality for the @ref streamsConcept "streams concept".
*
* This only requires very minimal level functionality for streams, most std
* io streams as well as the ecl streams will work with it.
**/
template <typename Implementation>
class StreamConcept {
public:
/**
* @brief Implements a concept test for streams.
*
* The following conditions are required by streams:
*
* - operator<< : a streaming operator which works on at least, chars.
* - flush() : a method for flushing the stream to the underlying device.
*/
ecl_compile_time_concept_test(StreamConcept)
{
stream << 'a';
stream.flush();
}
private:
// Putting instantiations here actually saves instantiation (which can cause a
// problem if there is no default constructor).
Implementation stream;
};
} // namespace ecl
#endif /* ECL_CONCEPTS_STREAMS_HPP_ */
@@ -0,0 +1,37 @@
<?xml version="1.0"?>
<package format="2">
<name>ecl_concepts</name>
<version>1.2.1</version>
<description>
Introduces a compile time concept checking mechanism that can be used
most commonly to check for required functionality when passing
template arguments.
</description>
<maintainer email="d.stonier@gmail.com">Daniel Stonier</maintainer>
<license>BSD-3-Clause</license>
<url type="website">http://wiki.ros.org/ecl_concepts</url>
<url type="repository">https://github.com/stonier/ecl_core</url>
<url type="bugtracker">https://github.com/stonier/ecl_core/issues</url>
<author email="d.stonier@gmail.com">Daniel Stonier</author> -->
<buildtool_depend>ament_cmake_ros</buildtool_depend>
<build_depend>ecl_license</build_depend>
<build_depend>ecl_build</build_depend>
<build_depend>ecl_config</build_depend>
<build_depend>ecl_type_traits</build_depend>
<exec_depend>ecl_license</exec_depend>
<exec_depend>ecl_config</exec_depend>
<exec_depend>ecl_type_traits</exec_depend>
<test_depend>ament_cmake_gtest</test_depend>
<test_depend>ament_lint_auto</test_depend>
<test_depend>ament_lint_common</test_depend>
<export>
<build_type>ament_cmake</build_type>
</export>
</package>
@@ -0,0 +1,9 @@
###############################################################################
# Subdirectories
###############################################################################
if(BUILD_TESTING)
find_package(ament_lint_auto REQUIRED)
ament_lint_auto_find_test_dependencies()
add_subdirectory(test)
endif()
@@ -0,0 +1,17 @@
###############################################################################
# Macro
###############################################################################
macro(ecl_concepts_add_gtest test_name)
ament_add_gtest(ecl_test_${test_name} ${test_name}.cpp)
# If we don't have gtest installed, then the target doesn't get made - check!
if(TARGET ecl_test_${test_name})
target_link_libraries(ecl_test_${test_name} ${PROJECT_NAME})
endif()
endmacro()
###############################################################################
# Tests
###############################################################################
ecl_concepts_add_gtest(concepts)
@@ -0,0 +1,102 @@
/**
* @file /src/test/concepts.cpp
*
* @brief Unit Test for concept checking.
*
* @date May 2009
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <iostream>
#include <gtest/gtest.h>
#include <vector>
#include "../../include/ecl/concepts/blueprints.hpp"
#include "../../include/ecl/concepts/containers.hpp"
#include "../../include/ecl/concepts/macros.hpp"
#include "../../include/ecl/concepts/streams.hpp"
/**
* @cond DO_NOT_DOXYGEN
*/
/*****************************************************************************
** Classes
*****************************************************************************/
namespace ecl {
namespace concepts {
namespace tests {
template <typename T>
class Concept {
public:
ecl_compile_time_concept_test(Concept)
{
T t;
t.apply(); // This is the characteristic function required by this concept.
}
};
class A {
public:
void apply() {}; // Comment this line to cause the compile to fail.
};
class BluePrintCandidate {
public:
typedef int base_type;
base_type instantiate();
void apply(base_type dude);
};
} // namespace tests
} // namespace concepts
} // namespace ecl
/*****************************************************************************
** Tests
*****************************************************************************/
using namespace ecl::concepts::tests;
// By default, the concept tests will pass. To cause it to fail
// comment the concept test functions and rebuild.
TEST(CompileTimeTests,macro) {
ecl_compile_time_concept_check(Concept<A>);
EXPECT_TRUE(true); // Should only fall over if compile time check is triggered.
}
TEST(CompileTimeTests,stream) {
ecl_compile_time_concept_check(ecl::StreamConcept<std::ostream>);
EXPECT_TRUE(true); // Should only fall over if compile time check is triggered.
}
TEST(CompileTimeTests,blueprint) {
ecl_compile_time_concept_check(ecl::BluePrintConcept<BluePrintCandidate>);
EXPECT_TRUE(true); // Should only fall over if compile time check is triggered.
}
TEST(CompileTimeTests,container) {
ecl_compile_time_concept_check(ecl::DynamicContainerConcept< std::vector<int> >);
EXPECT_TRUE(true); // Should only fall over if compile time check is triggered.
}
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
/**
* @endcond
*/
@@ -0,0 +1,338 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<?fileVersion 4.0.0?><cproject storage_type_id="org.eclipse.cdt.core.XmlProjectDescriptionStorage">
<storageModule moduleId="org.eclipse.cdt.core.settings">
<cconfiguration id="cdt.managedbuild.toolchain.gnu.base.1630154874">
<storageModule buildSystemId="org.eclipse.cdt.managedbuilder.core.configurationDataProvider" id="cdt.managedbuild.toolchain.gnu.base.1630154874" moduleId="org.eclipse.cdt.core.settings" name="Default">
<externalSettings/>
<extensions>
<extension id="org.eclipse.cdt.core.ELF" point="org.eclipse.cdt.core.BinaryParser"/>
<extension id="org.eclipse.cdt.core.GCCErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GASErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GLDErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.GmakeErrorParser" point="org.eclipse.cdt.core.ErrorParser"/>
<extension id="org.eclipse.cdt.core.CWDLocator" point="org.eclipse.cdt.core.ErrorParser"/>
</extensions>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<configuration artifactName="containers" buildProperties="" description="" id="cdt.managedbuild.toolchain.gnu.base.1630154874" name="Default" parent="org.eclipse.cdt.build.core.emptycfg">
<folderInfo id="cdt.managedbuild.toolchain.gnu.base.1630154874.824460430" name="/" resourcePath="">
<toolChain id="cdt.managedbuild.toolchain.gnu.base.1468040929" name="cdt.managedbuild.toolchain.gnu.base" superClass="cdt.managedbuild.toolchain.gnu.base">
<targetPlatform archList="all" binaryParser="org.eclipse.cdt.core.ELF" id="cdt.managedbuild.target.gnu.platform.base.1799158257" name="Debug Platform" osList="linux,hpux,aix,qnx" superClass="cdt.managedbuild.target.gnu.platform.base"/>
<builder buildPath="${workspace_loc:ecl_containers}/../../../build/${ProjName}" id="cdt.managedbuild.target.gnu.builder.base.438737021" incrementalBuildTarget="-L" keepEnvironmentInBuildfile="false" managedBuildOn="false" name="Gnu Make Builder" parallelBuildOn="true" parallelizationNumber="optimal" superClass="cdt.managedbuild.target.gnu.builder.base"/>
<tool id="cdt.managedbuild.tool.gnu.archiver.base.1091538337" name="GCC Archiver" superClass="cdt.managedbuild.tool.gnu.archiver.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.compiler.base.1026514213" name="GCC C++ Compiler" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.compiler.input.919246615" superClass="cdt.managedbuild.tool.gnu.cpp.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.compiler.base.1581719447" name="GCC C Compiler" superClass="cdt.managedbuild.tool.gnu.c.compiler.base">
<inputType id="cdt.managedbuild.tool.gnu.c.compiler.input.897239772" superClass="cdt.managedbuild.tool.gnu.c.compiler.input"/>
</tool>
<tool id="cdt.managedbuild.tool.gnu.c.linker.base.552412686" name="GCC C Linker" superClass="cdt.managedbuild.tool.gnu.c.linker.base"/>
<tool id="cdt.managedbuild.tool.gnu.cpp.linker.base.536735664" name="GCC C++ Linker" superClass="cdt.managedbuild.tool.gnu.cpp.linker.base">
<inputType id="cdt.managedbuild.tool.gnu.cpp.linker.input.1948704452" superClass="cdt.managedbuild.tool.gnu.cpp.linker.input">
<additionalInput kind="additionalinputdependency" paths="$(USER_OBJS)"/>
<additionalInput kind="additionalinput" paths="$(LIBS)"/>
</inputType>
</tool>
<tool id="cdt.managedbuild.tool.gnu.assembler.base.556942749" name="GCC Assembler" superClass="cdt.managedbuild.tool.gnu.assembler.base">
<inputType id="cdt.managedbuild.tool.gnu.assembler.input.323092790" superClass="cdt.managedbuild.tool.gnu.assembler.input"/>
</tool>
</toolChain>
</folderInfo>
<sourceEntries>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="include/ecl"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="src"/>
</sourceEntries>
</configuration>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.externalSettings"/>
<storageModule moduleId="org.eclipse.cdt.core.language.mapping"/>
<storageModule moduleId="org.eclipse.cdt.internal.ui.text.commentOwnerProjectMappings"/>
</cconfiguration>
</storageModule>
<storageModule moduleId="cdtBuildSystem" version="4.0.0">
<project id="containers.null.748553564" name="containers"/>
</storageModule>
<storageModule moduleId="refreshScope" versionNumber="2">
<configuration configurationName="Default">
<resource resourceType="PROJECT" workspacePath="/ecl_containers"/>
</configuration>
</storageModule>
<storageModule moduleId="scannerConfiguration">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1630154874;cdt.managedbuild.toolchain.gnu.base.1630154874.824460430;cdt.managedbuild.tool.gnu.c.compiler.base.1581719447;cdt.managedbuild.tool.gnu.c.compiler.input.897239772">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
<scannerConfigBuildInfo instanceId="cdt.managedbuild.toolchain.gnu.base.1630154874;cdt.managedbuild.toolchain.gnu.base.1630154874.824460430;cdt.managedbuild.tool.gnu.cpp.compiler.base.1026514213;cdt.managedbuild.tool.gnu.cpp.compiler.input.919246615">
<autodiscovery enabled="true" problemReportingEnabled="true" selectedProfileId="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP"/>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.make.core.GCCStandardMakePerFileProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="makefileGenerator">
<runAction arguments="-f ${project_name}_scd.mk" command="make" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/${specs_file}" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.cpp" command="g++" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-E -P -v -dD ${plugin_state_location}/specs.c" command="gcc" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfile">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/${specs_file}&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileCPP">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'g++ -E -P -v -dD &quot;${plugin_state_location}/specs.cpp&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
<profile id="org.eclipse.cdt.managedbuilder.core.GCCWinManagedMakePerProjectProfileC">
<buildOutputProvider>
<openAction enabled="true" filePath=""/>
<parser enabled="true"/>
</buildOutputProvider>
<scannerInfoProvider id="specsFile">
<runAction arguments="-c 'gcc -E -P -v -dD &quot;${plugin_state_location}/specs.c&quot;'" command="sh" useDefault="true"/>
<parser enabled="true"/>
</scannerInfoProvider>
</profile>
</scannerConfigBuildInfo>
</storageModule>
<storageModule moduleId="org.eclipse.cdt.core.LanguageSettingsProviders"/>
<storageModule moduleId="org.eclipse.cdt.make.core.buildtargets">
<buildTargets>
<target name="all" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments>-f ../../${ProjName}/Makefile -j8</buildArguments>
<buildTarget>all</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="clean" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments>-j8</buildArguments>
<buildTarget>clean</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
<target name="test" path="" targetID="org.eclipse.cdt.build.MakeTargetBuilder">
<buildCommand>make</buildCommand>
<buildArguments>-j8</buildArguments>
<buildTarget>test</buildTarget>
<stopOnError>true</stopOnError>
<useDefaultCommand>true</useDefaultCommand>
<runAllBuilders>true</runAllBuilders>
</target>
</buildTargets>
</storageModule>
</cproject>
@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>ecl_containers</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.genmakebuilder</name>
<triggers>clean,full,incremental,</triggers>
<arguments>
<dictionary>
<key>?name?</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.append_environment</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.autoBuildTarget</key>
<value>all</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildArguments</key>
<value></value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildCommand</key>
<value>pwd</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.buildLocation</key>
<value>${workspace_loc:ecl_containers}</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.cleanBuildTarget</key>
<value>clean</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.contents</key>
<value>org.eclipse.cdt.make.core.activeConfigSettings</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableAutoBuild</key>
<value>false</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableCleanBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.enableFullBuild</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.fullBuildTarget</key>
<value>-L</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.stopOnError</key>
<value>true</value>
</dictionary>
<dictionary>
<key>org.eclipse.cdt.make.core.useDefaultBuildCmd</key>
<value>false</value>
</dictionary>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.cdt.managedbuilder.core.ScannerConfigBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.cdt.core.cnature</nature>
<nature>org.eclipse.cdt.core.ccnature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.managedBuildNature</nature>
<nature>org.eclipse.cdt.managedbuilder.core.ScannerConfigNature</nature>
</natures>
</projectDescription>
@@ -0,0 +1,16 @@
^^^^^^^^^
Changelog
^^^^^^^^^
0.61.18 (2017-06-26)
--------------------
* bugfix trivial gcc7.1 error
0.61.2 (2015-08-12)
-------------------
* byte array converters for long long
0.61.0 (2014-09-12)
-------------------
* stencil for unsigned char* arrays.
* byte array converters for vector based stencils.
@@ -0,0 +1,93 @@
##############################################################################
# Cmake
##############################################################################
cmake_minimum_required(VERSION 3.5)
project(ecl_containers)
##############################################################################
# Find Packages
##############################################################################
# Turn -isystem off. Actually like to see warnings from underlying packages
# and regardless, have run into trouble because of the ordering it induces.
set(CMAKE_NO_SYSTEM_FROM_IMPORTED TRUE)
find_package(ament_cmake_ros REQUIRED)
find_package(ecl_build REQUIRED)
find_package(ecl_config REQUIRED)
find_package(ecl_converters REQUIRED)
find_package(ecl_errors REQUIRED)
find_package(ecl_exceptions REQUIRED)
find_package(ecl_formatters REQUIRED)
find_package(ecl_mpl REQUIRED)
find_package(ecl_type_traits REQUIRED)
find_package(ecl_utilities REQUIRED)
##############################################################################
# Project Configuration
##############################################################################
ament_package_xml()
ecl_enable_cxx14_compiler()
ecl_enable_cxx_warnings()
##############################################################################
# Header Library Targets
##############################################################################
add_library(${PROJECT_NAME} INTERFACE)
target_link_libraries(
${PROJECT_NAME}
INTERFACE
ecl_config::ecl_config
ecl_converters::ecl_converters
ecl_errors::ecl_errors
ecl_exceptions::ecl_exceptions
ecl_formatters::ecl_formatters
ecl_mpl::ecl_mpl
ecl_type_traits::ecl_type_traits
ecl_utilities::ecl_utilities
)
target_include_directories(
${PROJECT_NAME}
INTERFACE
$<BUILD_INTERFACE:${PROJECT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
)
install(TARGETS ${PROJECT_NAME} EXPORT ${PROJECT_NAME}
RUNTIME DESTINATION bin
ARCHIVE DESTINATION lib
LIBRARY DESTINATION lib
)
##############################################################################
# Sources
##############################################################################
add_subdirectory(include)
add_subdirectory(src)
##############################################################################
# Exports
##############################################################################
# Downstream CMake3 compatibility
ament_export_targets(${PROJECT_NAME})
# Downstream CMake2 compatibility
ament_export_include_directories(include)
ament_export_dependencies(
ecl_config
ecl_converters
ecl_errors
ecl_exceptions
ecl_formatters
ecl_mpl
ecl_type_traits
ecl_utilities
)
ament_package()
@@ -0,0 +1,232 @@
/**
\mainpage
\htmlinclude manifest.html
\section packageSummary Package Summary
The containers included here are intended to extend the stl containers
in a way that provides features not included in the stl
or to provide alternatives for stl containers that have
been designed for convenience, not speed. Here the emphasis is on
speed first, and c++ conveniences second.
@section CompilingLinking Compiling & Linking
Include the following at the top of any translation unit which
requires this library:
@code
#include <ecl/containers.hpp>
// The container types
using ecl::Array;
using ecl::Stencil;
using ecl::FiFo
using ecl::PushAndPop;
@endcode
These classes are template classes, so no linking is required for these interfaces.
\section usage Usage
@subsection fixedArrays Fixed Arrays
Arrays provide a fixed size container (enabled via a template parameter)
that can be saved as contiguous memory on the stack. This is in contrast to
typical stl containers that are dynamic and thus use the heap for storage, which
is much slower (on my dual-core, often about 10% slower for access methods and
up to 500% slower for construction).
It provides all the usual stl iterators associated with the object, as well
as many of the access methods excepting the size-changing ones. There are, however
a couple of features of arrays that stand out from stl containers.
<b>Comma Initialisation</b>
This concept is brought in (with slightly modified form) from Blitz++ and Eigen.
It enables initialisation via the comma operator.
@code
ecl::Array<int,5> array; // be careful, at this point, the contents are uninitialised.
array << 1,2,3,4,5; // comma initialisation
@endcode
Comman initialisers will throw an exception if the range is exceeded in debug mode
(beware release mode!).
<b>BluePrint Instantiations</b>
These provide an efficient means of instantiating array classes without a costly
copy-on-the-fly slowdown. It uses a blueprint coupled with what is referred to as a
blueprint factory to do this (refer to ecl_concepts for more details.).
However, the construction makes the usage of this transparent.
@code
Array<int,5> array = Array<int,5>::Constant(3); // construction.
array = Array<int,5>::Constant(3); // assignment, no costly copy operation used.
@endcode
@subsection dynamicArrays Dynamic Arrays
These arrays are almost exactly the same as the former fixed arrays, however they
are dynamically sizeable (though not as automatically nor flexibly as vectors) with their
storage on the heap, not the stack. The lack of flexibility isn't a serious disadvantage
as a control program should generally manage vector memory careful (read, manually!)
anyway. Their other feature is again, like the fixed arrays, the comma initialiser.
@code
Array<int> array1; // Note the similarity to fixed arrays - no storage allocated with this constructor!
Array<int> array2(4); // Initialise a vector with storage space for four integers.
Array<int> array3 = Array<int>::Constant(4,3); // Initialise space for four integers filled with a value of 3.
array1.clear(); // Clear - blows away the previous contents and leaves the buffer pointing to NULL.
array1.resize(10); // Resize - blows away previous contents and leaves values uninitialised.
@endcode
@subsection bufferOverflowSection Buffer Overflow Detection
Arrays also provide a feature to allow for buffer overflow checking - for both fixed and dynamic arrays.
Often programs pull pointers to various elements on the contiguous array (especially
in really low level routines like vision routines), it is important to know when the stack or heap is
being under or over run. Such functionality can be enabled by declaring the ECL_MEM_CHECK_ARRAYS
macro when compiling (maybe later I'll bring this in as a template parameter).
Internally, this entails pre/appending some magic characters to the underlying array and then
occasionally performing manual checks to ensure that the magic chars haven't been disturbed.
@code
#define ECL_MEM_CHECK_ARRAYS
Array<int,4> array; array << 1, 2, 3, 4;
while ( control_loop_running ) {
int* istart = array[0];
// send istart off to do some work elsewhere, possibly overrunning or underrunning.
// ...
if ( array.bufferUnderRun() ) { std::cout << "WARNING! We have an underrun problem houston!" << std::endl; }
if ( array.bufferOverRun() ) { std::cout << "WARNING! We have an overrun problem houston!" << std::endl; }
if ( array.bufferOverFlow() ) { std::cout << "WARNING! We have an unknown problem houston!" << std::endl; }
}
@endcode
@subsection Stencils
Often you require a window onto a container (array) and stencils provide a safe way to do this. It
avoids the use of dangerous pointers which can cause problems if the underlying container
goes out of scope or is resized. It does this by including the underlying container as a
reference and also includes similar out of range checks that arrays perform (exception throwing
in debug mode for [] and always for at()).
@code
typedef Array<int,5> FixedArray;
typedef Stencil< FixedArray > FixedStencil;
FixedArray array;
array << 1,2,3,4,5;
FixedStencil stencil(array,1,3); // windows from index 1 to 3
std::cout << stencil[1] << std::endl; // accesses array[2];
@endcode
@subsection Fifo
During the construction of fifo, typically length of buffer may be important.
@code
FiFo<double> fifo(4); // reserved only (not filled)
fifo.push_back( data_incoming );
@endcode
An initialised buffer can be important in variaous situation. For example, if you wish
to calculate a moving average, you should wait for N (length of buffer) pieces of
incoming of data. However, if you initialise the whole buffer as above, you can
proceed immediately.
@code
FiFo<double> fifo_initialised(4, initial_value); // reserved and filled
fifo.push_back( next_data ); // set next data
// ... // calculate the average here
@endcode
@subsection converters Byte Array Converters
Some converters utilising ecl::converters::FromByteArray are enabled for arrays and stencils respectively.
These allow conversion to integers of any time from a corresponding, little endian filled
array/stencil of chars.
@code
typedef Array<char, 4> ByteArray;
ByteArray byte_array;
byte_array << 0x01, 0x02, 0x03;
ecl::Converter<int,ByteStencil> toInt;
std::cout << "Conversion: " << toInt(byte_array) << std::endl; // results in 197121
std::cout << "Conversion: " << toInt(byte_array.stencil(0,2)) << std::endl; // only first two bytes -> 513
@endcode
and going the other way, we pass it the byte array for storage when converting (works on both
arrays and stencils)...
@code
Array<char,20> byte_array = Array<char,20>::Constant(0x00);
Stencil< Array<char, 20> > stencil = byte_array.stencil(2,4);
ecl::Converter< Stencil< Array<char, 20> >, ecl::int32 > fromInt;
fromInt(stencil, ecl::int32(197121));
std::cout << byte_array << std::endl; // 0x00, 0x00, 0x01, 0x02, 0x03, 0x00, 0x00, 0x00, ...
std::cout << stencil << std::endl; // 0x01, 0x02, 0x03, 0x00
@endcode
@subsection Formatters
Currently there is only formatters for the array and stencil classes classes which do:
- precision/width formatting for float arrays.
- hex formatting for byte arrays (signed char/char/unsigned char).
- default formatting for other types of arrays (provided they have the required Format for the element type).
- formatting extends to stencils operating on the array.
@code
#include <ecl/array.hpp>
Array<unsigned char>::Formatter format;
Array<unsigned char> array;
array << 0x01, 0x02, 0x03, 0x04;
std::cout << format(array) << std::endl;
// OR
#include <ecl/array.hpp>
#include <ecl/format.hpp>
Format< Array<unsigned char> > format;
Array<unsigned char> array;
array << 0x01, 0x02, 0x03, 0x04;
std::cout << format(array) << std::endl;
@endcode
\section utilities Examples
- src/examples/array_formatters.cpp
\section unitTests Unit Tests
- src/test/arrays.cpp
- src/test/arrays_mem_check.cpp
- src/test/converters.cpp
- src/test/stencil.cpp
- src/test/fifo.cpp
\section utilities Utilities
- /ecl_benchmarks/src/bench_containers.cpp : benchmarks various container latencies.
\section ChangeLog
- <b>Mar 11</b> : finally got the byte array converters working properly.
- <b>Sep 10</b> : moved the container formatter classes here from ecl_formatters.
- <b>Aug 10</b> : Converter for a byte array (char) to integral type converter.
- <b>Aug 10</b> : @ref ecl::FiFo "FiFo" provides a simple rotating array.
- <b>Mar 10</b> : @ref ecl::Stencil "Stencils" provides a safe means to open a window on top of an underlying container.
- <b>Jan 10</b> : @ref ecl::Array "Arrays" can do buffer overflow checking using ECL_MEM_CHECK_ARRAYS.
- <b>May 09</b> : @ref ecl::Array<Type,Dynamic> "Dynamic Arrays" on the heap with a few bells and whistles.
- <b>May 09</b> : @ref ecl::blueprints::ConstantArray "Constant Array" : blueprints for arrays filled with a single value.
- <b>May 09</b> : @ref ecl::Array "Fixed Arrays" on the stack with a few bells and whistles.
*/
@@ -0,0 +1,34 @@
/**
* @namespace ecl
*
* @brief Embedded control libraries.
*
* Various core libraries useful for embedded control systems.
**/
/**
* @namespace ecl::blueprints
*
* @brief Blueprints and factories classes used to generate blueprints (do not use directly).
*
* The blueprints are used to generate lightweight classes that store the rules to
* instantiate or configure classes in this package. These are used internally by
* container classes via inheritance and typedef'd notation for convenience, so you
* should never need to directly use these classes.
**/
/**
* @namespace ecl::containers
*
* @brief Supporting elements and interfaces for ecl containers.
*
* These provide support for the elements in this package. They are not
* intended to be directly visible to the user.
**/
/**
* @namespace ecl::formatters
*
* @brief Supporting classes for container formatters (do not use directly).
*
* Do not use these directly, they are better accessed via the Container::Formatter
* or Format< Container > mechanisms.
**/
@@ -0,0 +1,5 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(ecl)
@@ -0,0 +1,14 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(containers)
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl)
@@ -0,0 +1,27 @@
/**
* @file /include/ecl/containers.hpp
*
* @brief High-performance or convenience containers not included in the stl.
*
* @date September 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONTAINERS_HPP_
#define ECL_CONTAINERS_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#include "containers/definitions.hpp"
#include "containers/initialiser.hpp"
#include "containers/array.hpp"
#include "containers/converters.hpp"
#include "containers/fifo.hpp"
#include "containers/push_and_pop.hpp"
#include "containers/stencil.hpp"
#endif /* ECL_CONTAINERS_HPP_ */
@@ -0,0 +1,17 @@
###############################################################################
# SUBDIRECTORIES
###############################################################################
add_subdirectory(common)
add_subdirectory(array)
add_subdirectory(push_and_pop)
add_subdirectory(stencil)
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl/containers)
@@ -0,0 +1,30 @@
/**
* @file /include/ecl/containers/array.hpp
*
* @brief Fixed size containers with a few bells and whistles.
*
* @date September 2009
**/
/*****************************************************************************
** Ifdefs
*****************************************************************************/
#ifndef ECL_CONTAINERS_ARRAY_HPP_
#define ECL_CONTAINERS_ARRAY_HPP_
/*****************************************************************************
** Includes
*****************************************************************************/
#ifdef ECL_MEM_CHECK_ARRAYS
#include "array/array_mem_check.hpp"
#include "array/array_dynamic_mem_check.hpp"
#else
#include "array/array_no_mem_check.hpp"
#include "array/array_dynamic_no_mem_check.hpp"
#endif
// make sure the utility classes get included.
#include "array/converters.hpp"
#include "array/formatters.hpp"
#endif /* ECL_CONTAINERS_ARRAY_HPP_ */
@@ -0,0 +1,7 @@
###############################################################################
# FILES
###############################################################################
file(GLOB HEADERS RELATIVE ${CMAKE_CURRENT_SOURCE_DIR} *.hpp)
install(FILES ${HEADERS} DESTINATION include/ecl/containers/array)

Some files were not shown because too many files have changed in this diff Show More