From 43c401058a4de4d7946bf28a6c3545667177e2c6 Mon Sep 17 00:00:00 2001 From: Davide Faconti Date: Mon, 11 Dec 2023 17:49:50 +0100 Subject: [PATCH] clanf format --- .../include/PlotJuggler/special_messages.h | 72 +- .../DataLoadCSV/dataload_csv.cpp | 156 +- .../DataLoadCSV/dataload_csv.h | 5 +- .../DataLoadCSV/datetimehelp.cpp | 76 +- .../DataLoadCSV/datetimehelp.h | 17 +- .../DataLoadMCAP/dataload_mcap.cpp | 54 +- .../DataLoadMCAP/dataload_mcap.h | 1 - .../DataLoadMCAP/dialog_mcap.cpp | 49 +- .../DataLoadMCAP/dialog_mcap.h | 12 +- .../DataLoadParquet/dataload_parquet.cpp | 142 +- .../DataLoadParquet/dataload_parquet.h | 2 - .../DataLoadULog/string_view.hpp | 1409 ++-- .../DataStreamMQTT/datastream_mqtt.cpp | 66 +- .../DataStreamMQTT/datastream_mqtt.h | 6 +- .../DataStreamMQTT/mosquitto_config.h | 29 +- .../DataStreamMQTT/mqtt_client.cpp | 73 +- .../DataStreamMQTT/mqtt_client.h | 14 +- .../DataStreamMQTT/mqtt_dialog.cpp | 191 +- .../DataStreamMQTT/mqtt_dialog.h | 7 +- .../DataStreamUDP/udp_server.cpp | 6 +- .../DataStreamWebsocket/websocket_server.cpp | 6 +- plotjuggler_plugins/DataStreamZMQ/zmq.hpp | 3337 ++++---- .../ParserDataTamer/datatamer_parser.cpp | 41 +- .../ParserDataTamer/datatamer_parser.h | 6 +- .../ParserProtobuf/error_collectors.cpp | 35 +- .../ParserProtobuf/error_collectors.h | 7 +- .../ParserProtobuf/protobuf_factory.cpp | 75 +- .../ParserProtobuf/protobuf_factory.h | 11 +- .../ParserProtobuf/protobuf_parser.cpp | 202 +- .../ParserProtobuf/protobuf_parser.h | 12 +- plotjuggler_plugins/ParserROS/ros1_parser.h | 13 +- plotjuggler_plugins/ParserROS/ros2_parser.h | 14 +- plotjuggler_plugins/ParserROS/ros_parser.cpp | 343 +- plotjuggler_plugins/ParserROS/ros_parser.h | 38 +- .../3rdparty/Fast-CDR/include/fastcdr/Cdr.h | 6750 ++++++++--------- .../Fast-CDR/include/fastcdr/FastBuffer.h | 563 +- .../Fast-CDR/include/fastcdr/FastCdr.h | 4022 +++++----- .../include/fastcdr/eProsima_auto_link.h | 58 +- .../fastcdr/exceptions/BadParamException.h | 102 +- .../include/fastcdr/exceptions/Exception.h | 111 +- .../exceptions/NotEnoughMemoryException.h | 103 +- .../Fast-CDR/include/fastcdr/fastcdr_dll.h | 32 +- .../3rdparty/Fast-CDR/src/cpp/Cdr.cpp | 4030 +++++----- .../3rdparty/Fast-CDR/src/cpp/FastBuffer.cpp | 105 +- .../3rdparty/Fast-CDR/src/cpp/FastCdr.cpp | 1060 ++- .../src/cpp/exceptions/BadParamException.cpp | 48 +- .../Fast-CDR/src/cpp/exceptions/Exception.cpp | 32 +- .../exceptions/NotEnoughMemoryException.cpp | 58 +- .../rosx_introspection/builtin_types.hpp | 275 +- .../rosx_introspection/contrib/SmallVector.h | 742 +- .../rosx_introspection/contrib/span.hpp | 2241 +++--- .../rosx_introspection/deserializer.hpp | 21 +- .../details/conversion_impl.hpp | 376 +- .../rosx_introspection/details/exceptions.hpp | 117 +- .../include/rosx_introspection/ros_field.hpp | 90 +- .../rosx_introspection/ros_message.hpp | 82 +- .../include/rosx_introspection/ros_parser.hpp | 144 +- .../include/rosx_introspection/ros_type.hpp | 150 +- .../rosx_introspection/stringtree_leaf.hpp | 91 +- .../include/rosx_introspection/tree.hpp | 244 +- .../include/rosx_introspection/variant.hpp | 416 +- .../rosx_introspection/src/deserializer.cpp | 126 +- .../rosx_introspection/src/ros_field.cpp | 123 +- .../rosx_introspection/src/ros_message.cpp | 117 +- .../rosx_introspection/src/ros_parser.cpp | 94 +- .../rosx_introspection/src/ros_type.cpp | 114 +- .../src/stringtree_leaf.cpp | 80 +- plotjuggler_plugins/PluginsZcm/config_zcm.cpp | 116 +- plotjuggler_plugins/PluginsZcm/config_zcm.h | 24 +- .../PluginsZcm/dataload_zcm.cpp | 264 +- .../PluginsZcm/datastream_zcm.cpp | 148 +- .../PluginsZcm/datastream_zcm.h | 5 +- .../ToolboxFFT/KissFFT/_kiss_fft_guts.h | 213 +- plotjuggler_plugins/ToolboxFFT/KissFFT/kfc.h | 24 +- .../ToolboxFFT/KissFFT/kiss_fft.h | 112 +- .../ToolboxFFT/KissFFT/kiss_fft_log.h | 12 +- .../ToolboxFFT/KissFFT/kiss_fftnd.h | 10 +- .../ToolboxFFT/KissFFT/kiss_fftndr.h | 23 +- .../ToolboxFFT/KissFFT/kiss_fftr.h | 24 +- .../ToolboxFFT/toolbox_FFT.cpp | 4 +- .../ToolboxLuaEditor/lua_editor.cpp | 213 +- .../ToolboxLuaEditor/lua_editor.h | 15 +- .../ToolboxQuaternion/toolbox_quaternion.cpp | 12 +- plotjuggler_plugins/VideoViewer/qoi.h | 253 +- .../VideoViewer/video_dialog.cpp | 80 +- .../VideoViewer/video_dialog.h | 30 +- .../VideoViewer/video_viewer.cpp | 43 +- .../VideoViewer/video_viewer.h | 1 - 88 files changed, 15733 insertions(+), 15137 deletions(-) diff --git a/plotjuggler_base/include/PlotJuggler/special_messages.h b/plotjuggler_base/include/PlotJuggler/special_messages.h index 8fdf5e8d0..0975b5dbe 100644 --- a/plotjuggler_base/include/PlotJuggler/special_messages.h +++ b/plotjuggler_base/include/PlotJuggler/special_messages.h @@ -19,7 +19,7 @@ struct Time double toSec() const { - return double(sec) + double(nanosec)*1e-9; + return double(sec) + double(nanosec)*1e-9; } }; @@ -61,11 +61,11 @@ struct Vector3 struct Point { - double x; - double y; - double z; + double x; + double y; + double z; - static const char* id() { return "geometry_msgs/Point"; } + static const char* id() { return "geometry_msgs/Point"; } }; struct Quaternion @@ -97,51 +97,51 @@ struct Transform struct TransformStamped { - Header header; - std::string child_frame_id; - Transform transform; + Header header; + std::string child_frame_id; + Transform transform; - static const char* id() { return "geometry_msgs/TransformStamped"; } + static const char* id() { return "geometry_msgs/TransformStamped"; } }; struct Pose { - Vector3 position; - Quaternion orientation; + Vector3 position; + Quaternion orientation; - static const char* id() { return "geometry_msgs/Pose"; } + static const char* id() { return "geometry_msgs/Pose"; } }; struct PoseStamped { - Header header; - Pose pose; + Header header; + Pose pose; - static const char* id() { return "geometry_msgs/PoseStamped"; } + static const char* id() { return "geometry_msgs/PoseStamped"; } }; struct PoseWithCovariance { - Pose pose; - std::array covariance; + Pose pose; + std::array covariance; - static const char* id() { return "geometry_msgs/PoseWithCovariance"; } + static const char* id() { return "geometry_msgs/PoseWithCovariance"; } }; struct Twist { - Vector3 linear; - Vector3 angular; + Vector3 linear; + Vector3 angular; - static const char* id() { return "geometry_msgs/Twist"; } + static const char* id() { return "geometry_msgs/Twist"; } }; struct TwistWithCovariance { - Twist twist; - std::array covariance; + Twist twist; + std::array covariance; - static const char* id() { return "geometry_msgs/TwistWithCovariance"; } + static const char* id() { return "geometry_msgs/TwistWithCovariance"; } }; struct TFMessage @@ -154,24 +154,24 @@ struct TFMessage struct Imu { - Header header; - Quaternion orientation; - std::array orientation_covariance; - Vector3 angular_velocity; - std::array angular_velocity_covariance; - Vector3 linear_acceleration; - std::array linear_acceleration_covariance; + Header header; + Quaternion orientation; + std::array orientation_covariance; + Vector3 angular_velocity; + std::array angular_velocity_covariance; + Vector3 linear_acceleration; + std::array linear_acceleration_covariance; - static const char* id() { return "sensor_msgs/Imu"; } + static const char* id() { return "sensor_msgs/Imu"; } }; //-------------------- struct Odometry { - Header header; - PoseWithCovariance pose; - TwistWithCovariance twist; + Header header; + PoseWithCovariance pose; + TwistWithCovariance twist; - static const char* id() { return "nav_msgs/Odometry"; } + static const char* id() { return "nav_msgs/Odometry"; } }; //-------------------- diff --git a/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp b/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp index a78a2d50d..ec95349d4 100644 --- a/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp +++ b/plotjuggler_plugins/DataLoadCSV/dataload_csv.cpp @@ -11,7 +11,6 @@ #include "QSyntaxStyle" #include "datetimehelp.h" - #include const int TIME_INDEX_NOT_DEFINED = -2; @@ -100,7 +99,6 @@ DataLoadCSV::DataLoadCSV() _dateTime_dialog = new DateTimeHelp(_dialog); - _ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); connect(_ui->radioButtonSelect, &QRadioButton::toggled, this, [this](bool checked) { @@ -121,9 +119,8 @@ DataLoadCSV::DataLoadCSV() connect(_ui->checkBoxDateFormat, &QCheckBox::toggled, this, [this](bool checked) { _ui->lineEditDateFormat->setEnabled(checked); }); - connect(_ui->dateTimeHelpButton,&QPushButton::clicked, this, [this](){ - _dateTime_dialog->show(); - }); + connect(_ui->dateTimeHelpButton, &QPushButton::clicked, this, + [this]() { _dateTime_dialog->show(); }); _ui->rawText->setHighlighter(&_csvHighlighter); QSizePolicy sp_retain = _ui->tableView->sizePolicy(); @@ -248,34 +245,35 @@ void DataLoadCSV::parseHeader(QFile& file, std::vector& column_name QStringList column_labels; for (const auto& name : column_names) { - auto qname = QString::fromStdString( name ); - _ui->listWidgetSeries->addItem( qname ); - column_labels.push_back( qname ); + auto qname = QString::fromStdString(name); + _ui->listWidgetSeries->addItem(qname); + column_labels.push_back(qname); } _model->setColumnCount(column_labels.size()); _model->setHorizontalHeaderLabels(column_labels); QStringList lines; - for( int row = 0; row <= 100 && !inA.atEnd(); row ++) + for (int row = 0; row <= 100 && !inA.atEnd(); row++) { auto line = inA.readLine(); preview_lines += line + "\n"; - lines.push_back( line ); + lines.push_back(line); } - _model->setRowCount( lines.count() ); - for(int row = 0; row < lines.count(); row ++) + _model->setRowCount(lines.count()); + for (int row = 0; row < lines.count(); row++) { QVector lineToken = lines[row].splitRef(_delimiter); for (int j = 0; j < lineToken.size(); j++) { QString value = lineToken[j].toString(); - if( auto item = _model->item(row, j) ) + if (auto item = _model->item(row, j)) { item->setText(value); } - else{ + else + { _model->setItem(row, j, new QStandardItem(value)); } } @@ -332,13 +330,13 @@ int DataLoadCSV::launchDialog(QFile& file, std::vector* column_name { _ui->comboBox->setCurrentIndex(3); _delimiter = '\t'; - } file.close(); + } + file.close(); } - QString theme = settings.value("StyleSheet::theme", "light").toString(); - auto style_path = (theme == "light" ) ? ":/resources/lua_style_light.xml" : - ":/resources/lua_style_dark.xml"; + auto style_path = (theme == "light") ? ":/resources/lua_style_light.xml" : + ":/resources/lua_style_dark.xml"; QFile fl(style_path); if (fl.open(QIODevice::ReadOnly)) @@ -346,7 +344,7 @@ int DataLoadCSV::launchDialog(QFile& file, std::vector* column_name auto style = new QSyntaxStyle(this); if (style->load(fl.readAll())) { - _ui->rawText->setSyntaxStyle( style ); + _ui->rawText->setSyntaxStyle(style); } } @@ -381,7 +379,7 @@ int DataLoadCSV::launchDialog(QFile& file, std::vector* column_name if (previous_index.isEmpty() == false) { auto items = _ui->listWidgetSeries->findItems(previous_index, Qt::MatchExactly); - if( items.size() > 0 ) + if (items.size() > 0) { _ui->listWidgetSeries->setCurrentItem(items.front()); } @@ -514,7 +512,7 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data QString str_trimmed = str.trimmed(); double val = str_trimmed.toDouble(&is_number); // handle numbers with comma instead of point as decimal separator - if(!is_number) + if (!is_number) { static QLocale locale_with_comma(QLocale::German); val = locale_with_comma.toDouble(str_trimmed, &is_number); @@ -549,37 +547,44 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data SplitLine(line, _delimiter, string_items); // empty line? just try skipping - if(string_items.size() == 0) + if (string_items.size() == 0) { continue; } if (string_items.size() != column_names.size()) { - QMessageBox msgBox; - msgBox.setWindowTitle(tr("Error reading file")); - msgBox.setText(tr("The number of values at line %1 is %2,\n" - "but the expected number of columns is %3.\n" - "Aborting...") + QMessageBox msgBox; + msgBox.setWindowTitle(tr("Error reading file")); + msgBox.setText(tr("The number of values at line %1 is %2,\n" + "but the expected number of columns is %3.\n" + "Aborting...") .arg(linecount + 2) .arg(string_items.size()) .arg(column_names.size())); - msgBox.setDetailedText(tr("File: \"%1\" \n\n" - "Error reading file | Mismatched field count\n" - "Delimiter: [%2]\n" - "Header fields: %6\n" - "Fields on line [%4]: %7\n\n" - "File Preview:\n" - "[1]%3\n" - "[...]\n" - "[%4]%5\n").arg(_fileInfo->filename).arg(_delimiter).arg(header_str).arg(linecount+2).arg(line).arg(column_names.size()).arg(string_items.size())); - - QPushButton *abortButton = msgBox.addButton(QMessageBox::Ok); - - msgBox.setIcon(QMessageBox::Warning); - - msgBox.exec(); + msgBox.setDetailedText(tr("File: \"%1\" \n\n" + "Error reading file | Mismatched field count\n" + "Delimiter: [%2]\n" + "Header fields: %6\n" + "Fields on line [%4]: %7\n\n" + "File Preview:\n" + "[1]%3\n" + "[...]\n" + "[%4]%5\n") + .arg(_fileInfo->filename) + .arg(_delimiter) + .arg(header_str) + .arg(linecount + 2) + .arg(line) + .arg(column_names.size()) + .arg(string_items.size())); + + QPushButton* abortButton = msgBox.addButton(QMessageBox::Ok); + + msgBox.setIcon(QMessageBox::Warning); + + msgBox.exec(); return false; } @@ -597,14 +602,23 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { QMessageBox msgBox; msgBox.setWindowTitle(tr("Error reading file")); - msgBox.setText(tr("Couldn't parse timestamp on line %1 with string \"%2\" . Aborting.\n").arg(linecount+1).arg(t_str)); + msgBox.setText(tr("Couldn't parse timestamp on line %1 with string \"%2\" . " + "Aborting.\n") + .arg(linecount + 1) + .arg(t_str)); msgBox.setDetailedText(tr("File: \"%1\" \n\n" - "Error reading file | Couldn't parse timestamp\n" - "Parsing format: [%4]\n" - "Time at line %2 : [%3]\n").arg(_fileInfo->filename).arg(linecount + 1).arg(t_str).arg((parse_date_format && !format_string.isEmpty())? format_string: "None")); - - QPushButton *abortButton = msgBox.addButton(QMessageBox::Ok); + "Error reading file | Couldn't parse timestamp\n" + "Parsing format: [%4]\n" + "Time at line %2 : [%3]\n") + .arg(_fileInfo->filename) + .arg(linecount + 1) + .arg(t_str) + .arg((parse_date_format && !format_string.isEmpty()) ? + format_string : + "None")); + + QPushButton* abortButton = msgBox.addButton(QMessageBox::Ok); msgBox.setIcon(QMessageBox::Warning); @@ -617,39 +631,48 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { QMessageBox msgBox; QString timeName; - timeName = time_header_str; + timeName = time_header_str; msgBox.setWindowTitle(tr("Selected time is not monotonic")); - msgBox.setText(tr("PlotJuggler detected that the time in this file is non-monotonic. This may indicate an issue with the input data. Continue? (Input file will not be modified but data will be sorted by PlotJuggler)")); + msgBox.setText(tr("PlotJuggler detected that the time in this file is " + "non-monotonic. This may indicate an issue with the input " + "data. Continue? (Input file will not be modified but data " + "will be sorted by PlotJuggler)")); msgBox.setDetailedText(tr("File: \"%1\" \n\n" - "Selected time is not monotonic\n" - "Time Index: %6 [%7]\n" - "Time at line %2 : %3\n" - "Time at line %4 : %5").arg(_fileInfo->filename).arg(linecount + 1).arg(prev_t_str).arg(linecount + 2).arg(t_str).arg(time_index).arg(timeName)); - - QPushButton *sortButton = msgBox.addButton(tr("Continue"), QMessageBox::ActionRole); - QPushButton *abortButton = msgBox.addButton(QMessageBox::Abort); + "Selected time is not monotonic\n" + "Time Index: %6 [%7]\n" + "Time at line %2 : %3\n" + "Time at line %4 : %5") + .arg(_fileInfo->filename) + .arg(linecount + 1) + .arg(prev_t_str) + .arg(linecount + 2) + .arg(t_str) + .arg(time_index) + .arg(timeName)); + + QPushButton* sortButton = + msgBox.addButton(tr("Continue"), QMessageBox::ActionRole); + QPushButton* abortButton = msgBox.addButton(QMessageBox::Abort); msgBox.setIcon(QMessageBox::Warning); msgBox.exec(); - if(msgBox.clickedButton() == abortButton) + if (msgBox.clickedButton() == abortButton) { - return false; + return false; } else if (msgBox.clickedButton() == sortButton) { - sortRequired = true; + sortRequired = true; } else { - return false; + return false; } - } prev_time = t; prev_t_str = t_str; - } for (unsigned i = 0; i < string_items.size(); i++) @@ -689,7 +712,8 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data if (time_index >= 0) { _default_time_axis = column_names[time_index]; - } else if (time_index == TIME_INDEX_GENERATED) + } + else if (time_index == TIME_INDEX_GENERATED) { _default_time_axis = "__TIME_INDEX_GENERATED__"; } @@ -705,11 +729,11 @@ bool DataLoadCSV::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data } if (is_numeric) { - plot_data.strings.erase(plot_data.strings.find(name)); + plot_data.strings.erase(plot_data.strings.find(name)); } else { - plot_data.numeric.erase(plot_data.numeric.find(name)); + plot_data.numeric.erase(plot_data.numeric.find(name)); } } return true; diff --git a/plotjuggler_plugins/DataLoadCSV/dataload_csv.h b/plotjuggler_plugins/DataLoadCSV/dataload_csv.h index 5251e69e3..db4055e0a 100644 --- a/plotjuggler_plugins/DataLoadCSV/dataload_csv.h +++ b/plotjuggler_plugins/DataLoadCSV/dataload_csv.h @@ -54,10 +54,9 @@ class DataLoadCSV : public DataLoader QDialog* _dialog; Ui::DialogCSV* _ui; - DateTimeHelp *_dateTime_dialog; + DateTimeHelp* _dateTime_dialog; - QStandardItemModel *_model; + QStandardItemModel* _model; bool multiple_columns_warning_ = true; - }; diff --git a/plotjuggler_plugins/DataLoadCSV/datetimehelp.cpp b/plotjuggler_plugins/DataLoadCSV/datetimehelp.cpp index 8d6afad71..8c054fd7b 100644 --- a/plotjuggler_plugins/DataLoadCSV/datetimehelp.cpp +++ b/plotjuggler_plugins/DataLoadCSV/datetimehelp.cpp @@ -3,62 +3,60 @@ #include -//Source: https://stackoverflow.com/a/42458736 -void verticalResizeTableViewToContents(QTableView *tableView) +// Source: https://stackoverflow.com/a/42458736 +void verticalResizeTableViewToContents(QTableView* tableView) { - int count=tableView->verticalHeader()->count(); - int scrollBarHeight = 0; - if(tableView->horizontalScrollBar()->isVisible()) + int count = tableView->verticalHeader()->count(); + int scrollBarHeight = 0; + if (tableView->horizontalScrollBar()->isVisible()) + { + scrollBarHeight = tableView->horizontalScrollBar()->height(); + } + int horizontalHeaderHeight = tableView->horizontalHeader()->height(); + int rowTotalHeight = 0; + for (int i = 0; i < count; ++i) + { + // 2018-03 edit: only account for row if it is visible + if (!tableView->verticalHeader()->isSectionHidden(i)) { - scrollBarHeight=tableView->horizontalScrollBar()->height(); + rowTotalHeight += tableView->verticalHeader()->sectionSize(i); } - int horizontalHeaderHeight=tableView->horizontalHeader()->height(); - int rowTotalHeight=0; - for (int i = 0; i < count; ++i) { - // 2018-03 edit: only account for row if it is visible - if (!tableView->verticalHeader()->isSectionHidden(i)) { - rowTotalHeight+=tableView->verticalHeader()->sectionSize(i); - } - } - tableView->setMinimumHeight(horizontalHeaderHeight+rowTotalHeight+scrollBarHeight); + } + tableView->setMinimumHeight(horizontalHeaderHeight + rowTotalHeight + scrollBarHeight); } -DateTimeHelp::DateTimeHelp(QDialog *parent) : - QDialog(parent), ui(new Ui::DateTimeHelp), _parent(parent) +DateTimeHelp::DateTimeHelp(QDialog* parent) + : QDialog(parent), ui(new Ui::DateTimeHelp), _parent(parent) { - ui->setupUi(this); - - verticalResizeTableViewToContents(ui->dateFormatTable); - verticalResizeTableViewToContents(ui->timeFormatTable); - - refreshExample(); + ui->setupUi(this); - connect(ui->exampleDateTimeDateTimeEdit,&QDateTimeEdit::dateTimeChanged,this, [this](){ - refreshExample(); - }); + verticalResizeTableViewToContents(ui->dateFormatTable); + verticalResizeTableViewToContents(ui->timeFormatTable); - connect(ui->exampleFormatStringLineEdit,&QLineEdit::textChanged,this, [this](){ - refreshExample(); - }); + refreshExample(); - connect(_parent,&QDialog::finished,this,[this](){ - if(ui->autoCloseCheckBox->isChecked()) - { - accept(); - } + connect(ui->exampleDateTimeDateTimeEdit, &QDateTimeEdit::dateTimeChanged, this, + [this]() { refreshExample(); }); - }); + connect(ui->exampleFormatStringLineEdit, &QLineEdit::textChanged, this, + [this]() { refreshExample(); }); + connect(_parent, &QDialog::finished, this, [this]() { + if (ui->autoCloseCheckBox->isChecked()) + { + accept(); + } + }); } DateTimeHelp::~DateTimeHelp() { - delete ui; + delete ui; } void DateTimeHelp::refreshExample() { - auto dateTime = ui->exampleDateTimeDateTimeEdit->dateTime(); - auto formatString = ui->exampleFormatStringLineEdit->text(); - ui->resultLineEdit->setText(dateTime.toString(formatString)); + auto dateTime = ui->exampleDateTimeDateTimeEdit->dateTime(); + auto formatString = ui->exampleFormatStringLineEdit->text(); + ui->resultLineEdit->setText(dateTime.toString(formatString)); } diff --git a/plotjuggler_plugins/DataLoadCSV/datetimehelp.h b/plotjuggler_plugins/DataLoadCSV/datetimehelp.h index fe6641c8e..a54824379 100644 --- a/plotjuggler_plugins/DataLoadCSV/datetimehelp.h +++ b/plotjuggler_plugins/DataLoadCSV/datetimehelp.h @@ -3,24 +3,25 @@ #include -namespace Ui { +namespace Ui +{ class DateTimeHelp; } class DateTimeHelp : public QDialog { - Q_OBJECT + Q_OBJECT public: - explicit DateTimeHelp(QDialog *parent = nullptr); - ~DateTimeHelp(); + explicit DateTimeHelp(QDialog* parent = nullptr); + ~DateTimeHelp(); - void refreshExample(); + void refreshExample(); private: - Ui::DateTimeHelp *ui; + Ui::DateTimeHelp* ui; - QDialog* _parent; + QDialog* _parent; }; -#endif // DATETIMEHELP_H +#endif // DATETIMEHELP_H diff --git a/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.cpp b/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.cpp index 0fa508f07..8defbeb14 100644 --- a/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.cpp +++ b/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.cpp @@ -19,24 +19,21 @@ DataLoadMCAP::DataLoadMCAP() { - } DataLoadMCAP::~DataLoadMCAP() { - } const std::vector& DataLoadMCAP::compatibleFileExtensions() const { - static std::vector ext = {"mcap", "MCAP"}; + static std::vector ext = { "mcap", "MCAP" }; return ext; } - bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data) { - if( !parserFactories() ) + if (!parserFactories()) { throw std::runtime_error("No parsing available"); } @@ -64,9 +61,9 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat } auto statistics = reader.statistics(); - std::unordered_map mcap_schemas; // schema_id - std::unordered_map channels; // channel_id - std::unordered_map parsers_by_channel; // channel_id + std::unordered_map mcap_schemas; // schema_id + std::unordered_map channels; // channel_id + std::unordered_map parsers_by_channel; // channel_id std::unordered_map dt_schames; int total_dt_schemas = 0; @@ -76,29 +73,28 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat for (const auto& [schema_id, schema_ptr] : reader.schemas()) { - mcap_schemas.insert( {schema_id, schema_ptr} ); + mcap_schemas.insert({ schema_id, schema_ptr }); } std::set notified_encoding_problem; - QElapsedTimer timer; timer.start(); for (const auto& [channel_id, channel_ptr] : reader.channels()) { - channels.insert( {channel_id, channel_ptr} ); + channels.insert({ channel_id, channel_ptr }); const auto& schema = mcap_schemas.at(channel_ptr->schemaId); const auto& topic_name = channel_ptr->topic; std::string definition(reinterpret_cast(schema->data.data()), schema->data.size()); - if(schema->name == "data_tamer_msgs/msg/Schemas") + if (schema->name == "data_tamer_msgs/msg/Schemas") { channels_containing_datatamer_schema.insert(channel_id); total_dt_schemas += statistics->channelMessageCounts.at(channel_id); } - if(schema->name == "data_tamer_msgs/msg/Snapshot") + if (schema->name == "data_tamer_msgs/msg/Snapshot") { channels_containing_datatamer_data.insert(channel_id); } @@ -106,32 +102,31 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat QString channel_encoding = QString::fromStdString(channel_ptr->messageEncoding); QString schema_encoding = QString::fromStdString(schema->encoding); - auto it = parserFactories()->find( channel_encoding ); + auto it = parserFactories()->find(channel_encoding); - if(it == parserFactories()->end() ) + if (it == parserFactories()->end()) { - it = parserFactories()->find( schema_encoding ); + it = parserFactories()->find(schema_encoding); } - if(it == parserFactories()->end() ) + if (it == parserFactories()->end()) { // show message only once per encoding type - if(notified_encoding_problem.count(schema_encoding) == 0) + if (notified_encoding_problem.count(schema_encoding) == 0) { notified_encoding_problem.insert(schema_encoding); auto msg = QString("No parser available for encoding [%0] nor [%1]") - .arg(channel_encoding).arg(schema_encoding); + .arg(channel_encoding) + .arg(schema_encoding); QMessageBox::warning(nullptr, "Encoding problem", msg); } continue; } auto& parser_factory = it->second; - auto parser = parser_factory->createParser(topic_name, - schema->name, - definition, - plot_data); - parsers_by_channel.insert( {channel_ptr->id, parser} ); + auto parser = + parser_factory->createParser(topic_name, schema->name, definition, plot_data); + parsers_by_channel.insert({ channel_ptr->id, parser }); }; DialogMCAP dialog(channels, mcap_schemas); @@ -151,7 +146,7 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat dialog_params.max_array_size); QString topic_name = QString::fromStdString(channels[channel_id]->topic); - if( dialog_params.selected_topics.contains(topic_name) ) + if (dialog_params.selected_topics.contains(topic_name)) { enabled_channels.insert(channel_id); } @@ -166,9 +161,7 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat auto messages = reader.readMessages(onProblem); - QProgressDialog progress_dialog("Loading... please wait", - "Cancel", - 0, 0, nullptr); + QProgressDialog progress_dialog("Loading... please wait", "Cancel", 0, 0, nullptr); progress_dialog.setModal(true); progress_dialog.setAutoClose(true); progress_dialog.setAutoReset(true); @@ -180,7 +173,7 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat for (const auto& msg_view : messages) { - if( enabled_channels.count(msg_view.channel->id) == 0 ) + if (enabled_channels.count(msg_view.channel->id) == 0) { continue; } @@ -188,7 +181,7 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat // MCAP always represents publishTime in nanoseconds double timestamp_sec = double(msg_view.message.publishTime) * 1e-9; auto parser_it = parsers_by_channel.find(msg_view.channel->id); - if( parser_it == parsers_by_channel.end() ) + if (parser_it == parsers_by_channel.end()) { qDebug() << "Skipping channeld id: " << msg_view.channel->id; continue; @@ -212,4 +205,3 @@ bool DataLoadMCAP::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_dat qDebug() << "Loaded file in " << timer.elapsed() << "milliseconds"; return true; } - diff --git a/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.h b/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.h index eed0dbc87..d889ed9a6 100644 --- a/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.h +++ b/plotjuggler_plugins/DataLoadMCAP/dataload_mcap.h @@ -28,5 +28,4 @@ class DataLoadMCAP : public DataLoader { return "DataLoad MCAP"; } - }; diff --git a/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.cpp b/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.cpp index ed1bb5bc7..4236afb00 100644 --- a/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.cpp +++ b/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.cpp @@ -8,18 +8,18 @@ const QString DialogMCAP::prefix = "DialogLoadMCAP::"; - -DialogMCAP::DialogMCAP(const std::unordered_map &channels, - const std::unordered_map &schemas, - QWidget *parent) : - QDialog(parent), - ui(new Ui::dialog_mcap) +DialogMCAP::DialogMCAP(const std::unordered_map& channels, + const std::unordered_map& schemas, + QWidget* parent) + : QDialog(parent), ui(new Ui::dialog_mcap) { ui->setupUi(this); ui->tableWidget->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Stretch); - ui->tableWidget->horizontalHeader()->setSectionResizeMode(1, QHeaderView::ResizeToContents); - ui->tableWidget->horizontalHeader()->setSectionResizeMode(2, QHeaderView::ResizeToContents); + ui->tableWidget->horizontalHeader()->setSectionResizeMode( + 1, QHeaderView::ResizeToContents); + ui->tableWidget->horizontalHeader()->setSectionResizeMode( + 2, QHeaderView::ResizeToContents); ui->tableWidget->setRowCount(channels.size()); @@ -30,26 +30,29 @@ DialogMCAP::DialogMCAP(const std::unordered_map &channels bool clamp_checked = settings.value(prefix + "clamp", true).toBool(); int max_array = settings.value(prefix + "max_array", 500).toInt(); - if( clamp_checked ) + if (clamp_checked) { ui->radioClamp->setChecked(true); } - else{ + else + { ui->radioSkip->setChecked(true); } - ui->spinBox->setValue( max_array ); + ui->spinBox->setValue(max_array); int row = 0; - for(const auto& [id, channel]: channels ) + for (const auto& [id, channel] : channels) { auto topic = QString::fromStdString(channel->topic); - auto const& schema = schemas.at( channel->schemaId ); + auto const& schema = schemas.at(channel->schemaId); - ui->tableWidget->setItem(row, 0, new QTableWidgetItem(topic) ); - ui->tableWidget->setItem(row, 1, new QTableWidgetItem(QString::fromStdString(schema->name)) ); - ui->tableWidget->setItem(row, 2, new QTableWidgetItem(QString::fromStdString(schema->encoding)) ); + ui->tableWidget->setItem(row, 0, new QTableWidgetItem(topic)); + ui->tableWidget->setItem(row, 1, + new QTableWidgetItem(QString::fromStdString(schema->name))); + ui->tableWidget->setItem( + row, 2, new QTableWidgetItem(QString::fromStdString(schema->encoding))); - if( selected.contains(topic) ) + if (selected.contains(topic)) { ui->tableWidget->selectRow(row); } @@ -69,11 +72,11 @@ DialogMCAP::Params DialogMCAP::getParams() const params.max_array_size = ui->spinBox->value(); params.clamp_large_arrays = ui->radioClamp->isChecked(); - QItemSelectionModel *select = ui->tableWidget->selectionModel(); + QItemSelectionModel* select = ui->tableWidget->selectionModel(); QStringList selected_topics; - for(QModelIndex index: select->selectedRows()) + for (QModelIndex index : select->selectedRows()) { - params.selected_topics.push_back( ui->tableWidget->item(index.row(), 0)->text() ); + params.selected_topics.push_back(ui->tableWidget->item(index.row(), 0)->text()); } return params; } @@ -95,11 +98,11 @@ void DialogMCAP::accept() settings.setValue(prefix + "clamp", clamp_checked); settings.setValue(prefix + "max_array", max_array); - QItemSelectionModel *select = ui->tableWidget->selectionModel(); + QItemSelectionModel* select = ui->tableWidget->selectionModel(); QStringList selected_topics; - for(QModelIndex index: select->selectedRows()) + for (QModelIndex index : select->selectedRows()) { - selected_topics.push_back( ui->tableWidget->item(index.row(), 0)->text() ); + selected_topics.push_back(ui->tableWidget->item(index.row(), 0)->text()); } settings.setValue(prefix + "selected", selected_topics); diff --git a/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.h b/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.h index ef7e51715..ffef64eb9 100644 --- a/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.h +++ b/plotjuggler_plugins/DataLoadMCAP/dialog_mcap.h @@ -5,7 +5,8 @@ #include "mcap/reader.hpp" -namespace Ui { +namespace Ui +{ class dialog_mcap; } @@ -14,7 +15,6 @@ class DialogMCAP : public QDialog Q_OBJECT public: - struct Params { QStringList selected_topics; @@ -22,9 +22,9 @@ class DialogMCAP : public QDialog bool clamp_large_arrays; }; - explicit DialogMCAP(const std::unordered_map& channels, + explicit DialogMCAP(const std::unordered_map& channels, const std::unordered_map& schemas, - QWidget *parent = nullptr); + QWidget* parent = nullptr); ~DialogMCAP(); Params getParams() const; @@ -34,9 +34,9 @@ private slots: void accept() override; private: - Ui::dialog_mcap *ui; + Ui::dialog_mcap* ui; static const QString prefix; }; -#endif // DIALOG_MCAP_H +#endif // DIALOG_MCAP_H diff --git a/plotjuggler_plugins/DataLoadParquet/dataload_parquet.cpp b/plotjuggler_plugins/DataLoadParquet/dataload_parquet.cpp index 603cef769..ccd782f67 100644 --- a/plotjuggler_plugins/DataLoadParquet/dataload_parquet.cpp +++ b/plotjuggler_plugins/DataLoadParquet/dataload_parquet.cpp @@ -17,30 +17,24 @@ DataLoadParquet::DataLoadParquet() ui->setupUi(_dialog); connect(ui->checkBoxDateFormat, &QCheckBox::toggled, this, - [=](bool checked){ - ui->lineEditDateFormat->setEnabled(checked); - }); + [=](bool checked) { ui->lineEditDateFormat->setEnabled(checked); }); connect(ui->listWidgetSeries, &QListWidget::currentTextChanged, this, - [=](QString text) { - ui->buttonBox->setEnabled( !text.isEmpty() ); - }); + [=](QString text) { ui->buttonBox->setEnabled(!text.isEmpty()); }); connect(ui->listWidgetSeries, &QListWidget::doubleClicked, this, - [=](const QModelIndex &) { - _dialog->accept(); - }); + [=](const QModelIndex&) { _dialog->accept(); }); - connect(ui->radioButtonIndex, &QRadioButton::toggled, this, - [=](bool checked) { - ui->buttonBox->setEnabled(checked ); - ui->listWidgetSeries->setEnabled( !checked ); - }); + connect(ui->radioButtonIndex, &QRadioButton::toggled, this, [=](bool checked) { + ui->buttonBox->setEnabled(checked); + ui->listWidgetSeries->setEnabled(!checked); + }); QSettings settings; - bool radio_index_checked = settings.value("DataLoadParquet::radioIndexChecked", false).toBool(); - ui->radioButtonIndex->setChecked( radio_index_checked ); + bool radio_index_checked = + settings.value("DataLoadParquet::radioIndexChecked", false).toBool(); + ui->radioButtonIndex->setChecked(radio_index_checked); bool parse_date_time = settings.value("DataLoadParquet::parseDateTime", false).toBool(); ui->checkBoxDateFormat->setChecked(parse_date_time); @@ -59,19 +53,18 @@ DataLoadParquet::~DataLoadParquet() const std::vector& DataLoadParquet::compatibleFileExtensions() const { - static std::vector extensions = {"parquet"}; + static std::vector extensions = { "parquet" }; return extensions; } - bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data) { - using parquet::Type; using parquet::ConvertedType; + using parquet::Type; parquet_reader_ = parquet::ParquetFileReader::OpenFile(info->filename.toStdString()); - if( !parquet_reader_ ) + if (!parquet_reader_) { return false; } @@ -82,37 +75,36 @@ bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_ std::vector column_type; std::vector converted_column_type; - std::vector valid_column( num_columns, true ); + std::vector valid_column(num_columns, true); - for( size_t col=0; colColumn(col); + auto column = schema->Column(col); auto type = column->physical_type(); auto converted_type = column->converted_type(); - column_type.push_back( type ); - converted_column_type.push_back( converted_type ); + column_type.push_back(type); + converted_column_type.push_back(converted_type); - valid_column[col] = (type == Type::BOOLEAN || - type == Type::INT32 || - type == Type::INT64 || - type == Type::FLOAT || - type == Type::DOUBLE); + valid_column[col] = + (type == Type::BOOLEAN || type == Type::INT32 || type == Type::INT64 || + type == Type::FLOAT || type == Type::DOUBLE); - ui->listWidgetSeries->addItem( QString::fromStdString(column->name()) ); + ui->listWidgetSeries->addItem(QString::fromStdString(column->name())); } { QSettings settings; - if( _default_time_axis.isEmpty() ) + if (_default_time_axis.isEmpty()) { - _default_time_axis = settings.value("DataLoadParquet::prevTimestamp", {}).toString(); + _default_time_axis = + settings.value("DataLoadParquet::prevTimestamp", {}).toString(); } if (_default_time_axis.isEmpty() == false) { auto items = ui->listWidgetSeries->findItems(_default_time_axis, Qt::MatchExactly); - if( items.size() > 0 ) + if (items.size() > 0) { ui->listWidgetSeries->setCurrentItem(items.front()); } @@ -127,10 +119,10 @@ bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_ QString selected_stamp; - if( ui->radioButtonSelect->isChecked() ) + if (ui->radioButtonSelect->isChecked()) { auto selected = ui->listWidgetSeries->selectedItems(); - if( selected.size() == 1) + if (selected.size() == 1) { selected_stamp = selected.front()->text(); } @@ -138,8 +130,10 @@ bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_ QSettings settings; settings.setValue("DataLoadParquet::prevTimestamp", selected_stamp); - settings.setValue("DataLoadParquet::radioIndexChecked", ui->radioButtonIndex->isChecked()); - settings.setValue("DataLoadParquet::parseDateTime", ui->checkBoxDateFormat->isChecked()); + settings.setValue("DataLoadParquet::radioIndexChecked", + ui->radioButtonIndex->isChecked()); + settings.setValue("DataLoadParquet::parseDateTime", + ui->checkBoxDateFormat->isChecked()); settings.setValue("DataLoadParquet::dateFromat", ui->lineEditDateFormat->text()); //----------------------------- @@ -148,38 +142,38 @@ bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_ std::vector series(num_columns, nullptr); - for(size_t col=0; colColumn(col); + auto column = schema->Column(col); const std::string& name = column->name(); - if( name == selected_stamp.toStdString() ) + if (name == selected_stamp.toStdString()) { timestamp_column = col; } - if( valid_column[col] ) + if (valid_column[col]) { series[col] = &(plot_data.addNumeric(name)->second); } } - parquet::StreamReader os{std::move(parquet_reader_)}; + parquet::StreamReader os{ std::move(parquet_reader_) }; - std::vector row_values( num_columns, 0.0 ); + std::vector row_values(num_columns, 0.0); int row = 0; - while ( !os.eof() ) + while (!os.eof()) { // extract an entire row - for(size_t col=0; col(tmp); break; } - case Type::INT32: + case Type::INT32: case Type::INT64: { - switch(converted_type) + switch (converted_type) { - case ConvertedType::INT_8: - { + case ConvertedType::INT_8: { int8_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::INT_16: - { + case ConvertedType::INT_16: { int16_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::INT_32: - { + case ConvertedType::INT_32: { int32_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::INT_64: - { + case ConvertedType::INT_64: { int64_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::UINT_8: - { + case ConvertedType::UINT_8: { uint8_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::UINT_16: - { + case ConvertedType::UINT_16: { uint16_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::UINT_32: - { + case ConvertedType::UINT_32: { uint32_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case ConvertedType::UINT_64: - { + case ConvertedType::UINT_64: { uint64_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } default: { - //Fallback in case no converted type is provided - switch(type) + // Fallback in case no converted type is provided + switch (type) { - case Type::INT32: - { + case Type::INT32: { int32_t tmp; os >> tmp; row_values[col] = static_cast(tmp); break; } - case Type::INT64: - { + case Type::INT64: { int64_t tmp; os >> tmp; row_values[col] = static_cast(tmp); @@ -282,24 +266,24 @@ bool DataLoadParquet::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_ } default: { } - } // end switch - } // end for column + } // end switch + } // end for column os >> parquet::EndRow; double timestamp = timestamp_column >= 0 ? row_values[timestamp_column] : row; row++; - for(size_t col=0; colpushBack( {timestamp, row_values[col] }); + series[col]->pushBack({ timestamp, row_values[col] }); } } } @@ -339,7 +323,7 @@ bool DataLoadParquet::xmlLoadState(const QDomElement& parent_element) } if (elem.hasAttribute("dateFromat")) { - ui->lineEditDateFormat->setText( elem.attribute("dateFromat") ); + ui->lineEditDateFormat->setText(elem.attribute("dateFromat")); } } diff --git a/plotjuggler_plugins/DataLoadParquet/dataload_parquet.h b/plotjuggler_plugins/DataLoadParquet/dataload_parquet.h index ffaafa6fe..f88d5d733 100644 --- a/plotjuggler_plugins/DataLoadParquet/dataload_parquet.h +++ b/plotjuggler_plugins/DataLoadParquet/dataload_parquet.h @@ -38,9 +38,7 @@ class DataLoadParquet : public DataLoader virtual bool xmlLoadState(const QDomElement& parent_element) override; - private: - Ui::DialogParquet* ui = nullptr; std::vector _extensions; diff --git a/plotjuggler_plugins/DataLoadULog/string_view.hpp b/plotjuggler_plugins/DataLoadULog/string_view.hpp index f0cd234d2..ef5378791 100644 --- a/plotjuggler_plugins/DataLoadULog/string_view.hpp +++ b/plotjuggler_plugins/DataLoadULog/string_view.hpp @@ -11,74 +11,81 @@ #ifndef NONSTD_SV_LITE_H_INCLUDED #define NONSTD_SV_LITE_H_INCLUDED -#define string_view_lite_MAJOR 1 -#define string_view_lite_MINOR 1 -#define string_view_lite_PATCH 0 +#define string_view_lite_MAJOR 1 +#define string_view_lite_MINOR 1 +#define string_view_lite_PATCH 0 -#define string_view_lite_VERSION nssv_STRINGIFY(string_view_lite_MAJOR) "." nssv_STRINGIFY(string_view_lite_MINOR) "." nssv_STRINGIFY(string_view_lite_PATCH) +#define string_view_lite_VERSION \ + nssv_STRINGIFY(string_view_lite_MAJOR) "." nssv_STRINGIFY( \ + string_view_lite_MINOR) "." nssv_STRINGIFY(string_view_lite_PATCH) -#define nssv_STRINGIFY( x ) nssv_STRINGIFY_( x ) -#define nssv_STRINGIFY_( x ) #x +#define nssv_STRINGIFY(x) nssv_STRINGIFY_(x) +#define nssv_STRINGIFY_(x) #x // string-view lite configuration: -#define nssv_STRING_VIEW_DEFAULT 0 -#define nssv_STRING_VIEW_NONSTD 1 -#define nssv_STRING_VIEW_STD 2 +#define nssv_STRING_VIEW_DEFAULT 0 +#define nssv_STRING_VIEW_NONSTD 1 +#define nssv_STRING_VIEW_STD 2 -#if !defined( nssv_CONFIG_SELECT_STRING_VIEW ) -# define nssv_CONFIG_SELECT_STRING_VIEW ( nssv_HAVE_STD_STRING_VIEW ? nssv_STRING_VIEW_STD : nssv_STRING_VIEW_NONSTD ) +#if !defined(nssv_CONFIG_SELECT_STRING_VIEW) +#define nssv_CONFIG_SELECT_STRING_VIEW \ + (nssv_HAVE_STD_STRING_VIEW ? nssv_STRING_VIEW_STD : nssv_STRING_VIEW_NONSTD) #endif -#if defined( nssv_CONFIG_SELECT_STD_STRING_VIEW ) || defined( nssv_CONFIG_SELECT_NONSTD_STRING_VIEW ) -# error nssv_CONFIG_SELECT_STD_STRING_VIEW and nssv_CONFIG_SELECT_NONSTD_STRING_VIEW are deprecated and removed, please use nssv_CONFIG_SELECT_STRING_VIEW=nssv_STRING_VIEW_... +#if defined(nssv_CONFIG_SELECT_STD_STRING_VIEW) || \ + defined(nssv_CONFIG_SELECT_NONSTD_STRING_VIEW) +#error nssv_CONFIG_SELECT_STD_STRING_VIEW and nssv_CONFIG_SELECT_NONSTD_STRING_VIEW are deprecated and removed, please use nssv_CONFIG_SELECT_STRING_VIEW=nssv_STRING_VIEW_... #endif -#ifndef nssv_CONFIG_STD_SV_OPERATOR -# define nssv_CONFIG_STD_SV_OPERATOR 0 +#ifndef nssv_CONFIG_STD_SV_OPERATOR +#define nssv_CONFIG_STD_SV_OPERATOR 0 #endif -#ifndef nssv_CONFIG_USR_SV_OPERATOR -# define nssv_CONFIG_USR_SV_OPERATOR 1 +#ifndef nssv_CONFIG_USR_SV_OPERATOR +#define nssv_CONFIG_USR_SV_OPERATOR 1 #endif -#ifdef nssv_CONFIG_CONVERSION_STD_STRING -# define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS nssv_CONFIG_CONVERSION_STD_STRING -# define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS nssv_CONFIG_CONVERSION_STD_STRING +#ifdef nssv_CONFIG_CONVERSION_STD_STRING +#define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS nssv_CONFIG_CONVERSION_STD_STRING +#define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS nssv_CONFIG_CONVERSION_STD_STRING #endif -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS -# define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS 1 +#ifndef nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS +#define nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS 1 #endif -#ifndef nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -# define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS 1 +#ifndef nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS +#define nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS 1 #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. -#ifndef nssv_CPLUSPLUS -# if defined(_MSVC_LANG ) && !defined(__clang__) -# define nssv_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) -# else -# define nssv_CPLUSPLUS __cplusplus -# endif +#ifndef nssv_CPLUSPLUS +#if defined(_MSVC_LANG) && !defined(__clang__) +#define nssv_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG) +#else +#define nssv_CPLUSPLUS __cplusplus +#endif #endif -#define nssv_CPP98_OR_GREATER ( nssv_CPLUSPLUS >= 199711L ) -#define nssv_CPP11_OR_GREATER ( nssv_CPLUSPLUS >= 201103L ) -#define nssv_CPP11_OR_GREATER_ ( nssv_CPLUSPLUS >= 201103L ) -#define nssv_CPP14_OR_GREATER ( nssv_CPLUSPLUS >= 201402L ) -#define nssv_CPP17_OR_GREATER ( nssv_CPLUSPLUS >= 201703L ) -#define nssv_CPP20_OR_GREATER ( nssv_CPLUSPLUS >= 202000L ) +#define nssv_CPP98_OR_GREATER (nssv_CPLUSPLUS >= 199711L) +#define nssv_CPP11_OR_GREATER (nssv_CPLUSPLUS >= 201103L) +#define nssv_CPP11_OR_GREATER_ (nssv_CPLUSPLUS >= 201103L) +#define nssv_CPP14_OR_GREATER (nssv_CPLUSPLUS >= 201402L) +#define nssv_CPP17_OR_GREATER (nssv_CPLUSPLUS >= 201703L) +#define nssv_CPP20_OR_GREATER (nssv_CPLUSPLUS >= 202000L) -# define nssv_HAVE_STD_STRING_VIEW 0 +#define nssv_HAVE_STD_STRING_VIEW 0 -#define nssv_USES_STD_STRING_VIEW ( (nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_STD) || ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_DEFAULT) && nssv_HAVE_STD_STRING_VIEW) ) +#define nssv_USES_STD_STRING_VIEW \ + ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_STD) || \ + ((nssv_CONFIG_SELECT_STRING_VIEW == nssv_STRING_VIEW_DEFAULT) && \ + nssv_HAVE_STD_STRING_VIEW)) -#define nssv_HAVE_STARTS_WITH ( nssv_CPP20_OR_GREATER || !nssv_USES_STD_STRING_VIEW ) -#define nssv_HAVE_ENDS_WITH nssv_HAVE_STARTS_WITH +#define nssv_HAVE_STARTS_WITH (nssv_CPP20_OR_GREATER || !nssv_USES_STD_STRING_VIEW) +#define nssv_HAVE_ENDS_WITH nssv_HAVE_STARTS_WITH // // Use C++17 std::string_view: @@ -92,20 +99,21 @@ #if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -namespace nonstd { +namespace nonstd +{ -template< class CharT, class Traits, class Allocator = std::allocator > +template > std::basic_string -to_string( std::basic_string_view v, Allocator const & a = Allocator() ) +to_string(std::basic_string_view v, Allocator const& a = Allocator()) { - return std::basic_string( v.begin(), v.end(), a ); + return std::basic_string(v.begin(), v.end(), a); } -template< class CharT, class Traits, class Allocator > +template std::basic_string_view -to_string_view( std::basic_string const & s ) +to_string_view(std::basic_string const& s) { - return std::basic_string_view( s.data(), s.size() ); + return std::basic_string_view(s.data(), s.size()); } // Literal operators sv and _sv: @@ -118,45 +126,51 @@ using namespace std::literals::string_view_literals; #if nssv_CONFIG_USR_SV_OPERATOR -inline namespace literals { -inline namespace string_view_literals { - +inline namespace literals +{ +inline namespace string_view_literals +{ -constexpr std::string_view operator "" _sv( const char* str, size_t len ) noexcept // (1) +constexpr std::string_view operator"" _sv(const char* str, size_t len) noexcept // (1) { - return std::string_view{ str, len }; + return std::string_view{ str, len }; } -constexpr std::u16string_view operator "" _sv( const char16_t* str, size_t len ) noexcept // (2) +constexpr std::u16string_view operator"" _sv(const char16_t* str, + size_t len) noexcept // (2) { - return std::u16string_view{ str, len }; + return std::u16string_view{ str, len }; } -constexpr std::u32string_view operator "" _sv( const char32_t* str, size_t len ) noexcept // (3) +constexpr std::u32string_view operator"" _sv(const char32_t* str, + size_t len) noexcept // (3) { - return std::u32string_view{ str, len }; + return std::u32string_view{ str, len }; } -constexpr std::wstring_view operator "" _sv( const wchar_t* str, size_t len ) noexcept // (4) +constexpr std::wstring_view operator"" _sv(const wchar_t* str, + size_t len) noexcept // (4) { - return std::wstring_view{ str, len }; + return std::wstring_view{ str, len }; } -}} // namespace literals::string_view_literals +} // namespace string_view_literals +} // namespace literals -#endif // nssv_CONFIG_USR_SV_OPERATOR +#endif // nssv_CONFIG_USR_SV_OPERATOR -} // namespace nonstd +} // namespace nonstd -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS +#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -namespace nonstd { +namespace nonstd +{ +using std::basic_string_view; using std::string_view; -using std::wstring_view; using std::u16string_view; using std::u32string_view; -using std::basic_string_view; +using std::wstring_view; // literal "sv" and "_sv", see above @@ -169,9 +183,9 @@ using std::operator>=; using std::operator<<; -} // namespace nonstd +} // namespace nonstd -#else // nssv_HAVE_STD_STRING_VIEW +#else // nssv_HAVE_STD_STRING_VIEW // // Before C++17: use string_view lite: @@ -190,115 +204,118 @@ using std::operator<<; // MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) // MSVC++ 14.1 _MSC_VER >= 1910 (Visual Studio 2017) -#if defined(_MSC_VER ) && !defined(__clang__) -# define nssv_COMPILER_MSVC_VER (_MSC_VER ) -# define nssv_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) +#if defined(_MSC_VER) && !defined(__clang__) +#define nssv_COMPILER_MSVC_VER (_MSC_VER) +#define nssv_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * (5 + (_MSC_VER < 1900))) #else -# define nssv_COMPILER_MSVC_VER 0 -# define nssv_COMPILER_MSVC_VERSION 0 +#define nssv_COMPILER_MSVC_VER 0 +#define nssv_COMPILER_MSVC_VERSION 0 #endif -#define nssv_COMPILER_VERSION( major, minor, patch ) (10 * ( 10 * major + minor) + patch) +#define nssv_COMPILER_VERSION(major, minor, patch) (10 * (10 * major + minor) + patch) #if defined(__clang__) -# define nssv_COMPILER_CLANG_VERSION nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) +#define nssv_COMPILER_CLANG_VERSION \ + nssv_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) #else -# define nssv_COMPILER_CLANG_VERSION 0 +#define nssv_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) -# define nssv_COMPILER_GNUC_VERSION nssv_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#define nssv_COMPILER_GNUC_VERSION \ + nssv_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else -# define nssv_COMPILER_GNUC_VERSION 0 +#define nssv_COMPILER_GNUC_VERSION 0 #endif // half-open range [lo..hi): -#define nssv_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) +#define nssv_BETWEEN(v, lo, hi) ((lo) <= (v) && (v) < (hi)) // Presence of language and library features: #ifdef _HAS_CPP0X -# define nssv_HAS_CPP0X _HAS_CPP0X +#define nssv_HAS_CPP0X _HAS_CPP0X #else -# define nssv_HAS_CPP0X 0 +#define nssv_HAS_CPP0X 0 #endif // Unless defined otherwise below, consider VC14 as C++11 for variant-lite: #if nssv_COMPILER_MSVC_VER >= 1900 -# undef nssv_CPP11_OR_GREATER -# define nssv_CPP11_OR_GREATER 1 +#undef nssv_CPP11_OR_GREATER +#define nssv_CPP11_OR_GREATER 1 #endif -#define nssv_CPP11_90 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1500) -#define nssv_CPP11_100 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1600) -#define nssv_CPP11_110 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1700) -#define nssv_CPP11_120 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1800) -#define nssv_CPP11_140 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1900) -#define nssv_CPP11_141 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1910) +#define nssv_CPP11_90 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1500) +#define nssv_CPP11_100 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1600) +#define nssv_CPP11_110 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1700) +#define nssv_CPP11_120 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1800) +#define nssv_CPP11_140 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1900) +#define nssv_CPP11_141 (nssv_CPP11_OR_GREATER_ || nssv_COMPILER_MSVC_VER >= 1910) -#define nssv_CPP14_000 (nssv_CPP14_OR_GREATER) -#define nssv_CPP17_000 (nssv_CPP17_OR_GREATER) +#define nssv_CPP14_000 (nssv_CPP14_OR_GREATER) +#define nssv_CPP17_000 (nssv_CPP17_OR_GREATER) // Presence of C++11 language features: -#define nssv_HAVE_CONSTEXPR_11 nssv_CPP11_140 -#define nssv_HAVE_EXPLICIT_CONVERSION nssv_CPP11_140 -#define nssv_HAVE_INLINE_NAMESPACE nssv_CPP11_140 -#define nssv_HAVE_NOEXCEPT nssv_CPP11_140 -#define nssv_HAVE_NULLPTR nssv_CPP11_100 -#define nssv_HAVE_REF_QUALIFIER nssv_CPP11_140 -#define nssv_HAVE_UNICODE_LITERALS nssv_CPP11_140 +#define nssv_HAVE_CONSTEXPR_11 nssv_CPP11_140 +#define nssv_HAVE_EXPLICIT_CONVERSION nssv_CPP11_140 +#define nssv_HAVE_INLINE_NAMESPACE nssv_CPP11_140 +#define nssv_HAVE_NOEXCEPT nssv_CPP11_140 +#define nssv_HAVE_NULLPTR nssv_CPP11_100 +#define nssv_HAVE_REF_QUALIFIER nssv_CPP11_140 +#define nssv_HAVE_UNICODE_LITERALS nssv_CPP11_140 #define nssv_HAVE_USER_DEFINED_LITERALS nssv_CPP11_140 -#define nssv_HAVE_WCHAR16_T nssv_CPP11_100 -#define nssv_HAVE_WCHAR32_T nssv_CPP11_100 +#define nssv_HAVE_WCHAR16_T nssv_CPP11_100 +#define nssv_HAVE_WCHAR32_T nssv_CPP11_100 -#if ! ( ( nssv_CPP11 && nssv_COMPILER_CLANG_VERSION ) || nssv_BETWEEN( nssv_COMPILER_CLANG_VERSION, 300, 400 ) ) -# define nssv_HAVE_STD_DEFINED_LITERALS nssv_CPP11_140 +#if !((nssv_CPP11 && nssv_COMPILER_CLANG_VERSION) || \ + nssv_BETWEEN(nssv_COMPILER_CLANG_VERSION, 300, 400)) +#define nssv_HAVE_STD_DEFINED_LITERALS nssv_CPP11_140 #endif // Presence of C++14 language features: -#define nssv_HAVE_CONSTEXPR_14 nssv_CPP14_000 +#define nssv_HAVE_CONSTEXPR_14 nssv_CPP14_000 // Presence of C++17 language features: -#define nssv_HAVE_NODISCARD nssv_CPP17_000 +#define nssv_HAVE_NODISCARD nssv_CPP17_000 // Presence of C++ library features: -#define nssv_HAVE_STD_HASH nssv_CPP11_120 +#define nssv_HAVE_STD_HASH nssv_CPP11_120 // C++ feature usage: #if nssv_HAVE_CONSTEXPR_11 -# define nssv_constexpr constexpr +#define nssv_constexpr constexpr #else -# define nssv_constexpr /*constexpr*/ +#define nssv_constexpr /*constexpr*/ #endif -#if nssv_HAVE_CONSTEXPR_14 -# define nssv_constexpr14 constexpr +#if nssv_HAVE_CONSTEXPR_14 +#define nssv_constexpr14 constexpr #else -# define nssv_constexpr14 /*constexpr*/ +#define nssv_constexpr14 /*constexpr*/ #endif #if nssv_HAVE_EXPLICIT_CONVERSION -# define nssv_explicit explicit +#define nssv_explicit explicit #else -# define nssv_explicit /*explicit*/ +#define nssv_explicit /*explicit*/ #endif #if nssv_HAVE_INLINE_NAMESPACE -# define nssv_inline_ns inline +#define nssv_inline_ns inline #else -# define nssv_inline_ns /*inline*/ +#define nssv_inline_ns /*inline*/ #endif #if nssv_HAVE_NOEXCEPT -# define nssv_noexcept noexcept +#define nssv_noexcept noexcept #else -# define nssv_noexcept /*noexcept*/ +#define nssv_noexcept /*noexcept*/ #endif //#if nssv_HAVE_REF_QUALIFIER @@ -310,15 +327,15 @@ using std::operator<<; //#endif #if nssv_HAVE_NULLPTR -# define nssv_nullptr nullptr +#define nssv_nullptr nullptr #else -# define nssv_nullptr NULL +#define nssv_nullptr NULL #endif #if nssv_HAVE_NODISCARD -# define nssv_nodiscard [[nodiscard]] +#define nssv_nodiscard [[nodiscard]] #else -# define nssv_nodiscard /*[[nodiscard]]*/ +#define nssv_nodiscard /*[[nodiscard]]*/ #endif // Additional includes: @@ -329,41 +346,42 @@ using std::operator<<; #include #include #include -#include // std::char_traits<> +#include // std::char_traits<> #if nssv_CPP11_OR_GREATER -# include +#include #endif // Clang, GNUC, MSVC warning suppression macros: #if defined(__clang__) -# pragma clang diagnostic ignored "-Wreserved-user-defined-literal" -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wuser-defined-literals" +#pragma clang diagnostic ignored "-Wreserved-user-defined-literal" +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wuser-defined-literals" #elif defined(__GNUC__) -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wliteral-suffix" -#endif // __clang__ +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wliteral-suffix" +#endif // __clang__ #if nssv_COMPILER_MSVC_VERSION >= 140 -# define nssv_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] -# define nssv_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress: code) ) -# define nssv_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) +#define nssv_SUPPRESS_MSGSL_WARNING(expr) [[gsl::suppress(expr)]] +#define nssv_SUPPRESS_MSVC_WARNING(code, descr) __pragma(warning(suppress : code)) +#define nssv_DISABLE_MSVC_WARNINGS(codes) \ + __pragma(warning(push)) __pragma(warning(disable : codes)) #else -# define nssv_SUPPRESS_MSGSL_WARNING(expr) -# define nssv_SUPPRESS_MSVC_WARNING(code, descr) -# define nssv_DISABLE_MSVC_WARNINGS(codes) +#define nssv_SUPPRESS_MSGSL_WARNING(expr) +#define nssv_SUPPRESS_MSVC_WARNING(code, descr) +#define nssv_DISABLE_MSVC_WARNINGS(codes) #endif #if defined(__clang__) -# define nssv_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") +#define nssv_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") #elif defined(__GNUC__) -# define nssv_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") +#define nssv_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") #elif nssv_COMPILER_MSVC_VERSION >= 140 -# define nssv_RESTORE_WARNINGS() __pragma(warning(pop )) +#define nssv_RESTORE_WARNINGS() __pragma(warning(pop)) #else -# define nssv_RESTORE_WARNINGS() +#define nssv_RESTORE_WARNINGS() #endif // Suppress the following MSVC (GSL) warnings: @@ -373,405 +391,472 @@ using std::operator<<; // use brace initialization, gsl::narrow_cast or gsl::narow // - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead -nssv_DISABLE_MSVC_WARNINGS( 4455 26481 26472 ) -//nssv_DISABLE_CLANG_WARNINGS( "-Wuser-defined-literals" ) -//nssv_DISABLE_GNUC_WARNINGS( -Wliteral-suffix ) +nssv_DISABLE_MSVC_WARNINGS(4455 26481 26472) + // nssv_DISABLE_CLANG_WARNINGS( "-Wuser-defined-literals" ) + // nssv_DISABLE_GNUC_WARNINGS( -Wliteral-suffix ) -namespace nonstd { namespace sv_lite { + namespace nonstd +{ + namespace sv_lite + { -template -< - class CharT, - class Traits = std::char_traits -> -class basic_string_view; + template > + class basic_string_view; -// -// basic_string_view: -// + // + // basic_string_view: + // -template -< - class CharT, - class Traits /* = std::char_traits */ -> -class basic_string_view -{ -public: + template */ + > + class basic_string_view + { + public: // Member types: typedef Traits traits_type; - typedef CharT value_type; + typedef CharT value_type; - typedef CharT * pointer; - typedef CharT const * const_pointer; - typedef CharT & reference; - typedef CharT const & const_reference; + typedef CharT* pointer; + typedef CharT const* const_pointer; + typedef CharT& reference; + typedef CharT const& const_reference; typedef const_pointer iterator; typedef const_pointer const_iterator; - typedef std::reverse_iterator< const_iterator > reverse_iterator; - typedef std::reverse_iterator< const_iterator > const_reverse_iterator; + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; - typedef std::size_t size_type; - typedef std::ptrdiff_t difference_type; + typedef std::size_t size_type; + typedef std::ptrdiff_t difference_type; // 24.4.2.1 Construction and assignment: - nssv_constexpr basic_string_view() nssv_noexcept - : data_( nssv_nullptr ) - , size_( 0 ) - {} + nssv_constexpr basic_string_view() nssv_noexcept : data_(nssv_nullptr), size_(0) + { + } #if nssv_CPP11_OR_GREATER - nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept = default; + nssv_constexpr + basic_string_view(basic_string_view const& other) nssv_noexcept = default; #else - nssv_constexpr basic_string_view( basic_string_view const & other ) nssv_noexcept - : data_( other.data_) - , size_( other.size_) - {} + nssv_constexpr basic_string_view(basic_string_view const& other) nssv_noexcept + : data_(other.data_), + size_(other.size_) + { + } #endif - nssv_constexpr basic_string_view( CharT const * s, size_type count ) - : data_( s ) - , size_( count ) - {} + nssv_constexpr basic_string_view(CharT const* s, size_type count) + : data_(s), size_(count) + { + } - nssv_constexpr basic_string_view( CharT const * s) - : data_( s ) - , size_( Traits::length(s) ) - {} + nssv_constexpr basic_string_view(CharT const* s) : data_(s), size_(Traits::length(s)) + { + } // Assignment: #if nssv_CPP11_OR_GREATER - nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept = default; + nssv_constexpr14 basic_string_view& + operator=(basic_string_view const& other) nssv_noexcept = default; #else - nssv_constexpr14 basic_string_view & operator=( basic_string_view const & other ) nssv_noexcept + nssv_constexpr14 basic_string_view& + operator=(basic_string_view const& other) nssv_noexcept { - data_ = other.data_; - size_ = other.size_; - return *this; + data_ = other.data_; + size_ = other.size_; + return *this; } #endif // 24.4.2.2 Iterator support: - nssv_constexpr const_iterator begin() const nssv_noexcept { return data_; } - nssv_constexpr const_iterator end() const nssv_noexcept { return data_ + size_; } + nssv_constexpr const_iterator begin() const nssv_noexcept + { + return data_; + } + nssv_constexpr const_iterator end() const nssv_noexcept + { + return data_ + size_; + } - nssv_constexpr const_iterator cbegin() const nssv_noexcept { return begin(); } - nssv_constexpr const_iterator cend() const nssv_noexcept { return end(); } + nssv_constexpr const_iterator cbegin() const nssv_noexcept + { + return begin(); + } + nssv_constexpr const_iterator cend() const nssv_noexcept + { + return end(); + } - nssv_constexpr const_reverse_iterator rbegin() const nssv_noexcept { return const_reverse_iterator( end() ); } - nssv_constexpr const_reverse_iterator rend() const nssv_noexcept { return const_reverse_iterator( begin() ); } + nssv_constexpr const_reverse_iterator rbegin() const nssv_noexcept + { + return const_reverse_iterator(end()); + } + nssv_constexpr const_reverse_iterator rend() const nssv_noexcept + { + return const_reverse_iterator(begin()); + } - nssv_constexpr const_reverse_iterator crbegin() const nssv_noexcept { return rbegin(); } - nssv_constexpr const_reverse_iterator crend() const nssv_noexcept { return rend(); } + nssv_constexpr const_reverse_iterator crbegin() const nssv_noexcept + { + return rbegin(); + } + nssv_constexpr const_reverse_iterator crend() const nssv_noexcept + { + return rend(); + } // 24.4.2.3 Capacity: - nssv_constexpr size_type size() const nssv_noexcept { return size_; } - nssv_constexpr size_type length() const nssv_noexcept { return size_; } - nssv_constexpr size_type max_size() const nssv_noexcept { return (std::numeric_limits< size_type >::max)(); } + nssv_constexpr size_type size() const nssv_noexcept + { + return size_; + } + nssv_constexpr size_type length() const nssv_noexcept + { + return size_; + } + nssv_constexpr size_type max_size() const nssv_noexcept + { + return (std::numeric_limits::max)(); + } // since C++20 nssv_nodiscard nssv_constexpr bool empty() const nssv_noexcept { - return 0 == size_; + return 0 == size_; } // 24.4.2.4 Element access: - nssv_constexpr const_reference operator[]( size_type pos ) const + nssv_constexpr const_reference operator[](size_type pos) const { - return data_at( pos ); + return data_at(pos); } - nssv_constexpr14 const_reference at( size_type pos ) const + nssv_constexpr14 const_reference at(size_type pos) const { - if ( pos < size() ) - { - return data_at( pos ); - } + if (pos < size()) + { + return data_at(pos); + } - throw std::out_of_range("nonst::string_view::at()"); + throw std::out_of_range("nonst::string_view::at()"); } - nssv_constexpr const_reference front() const { return data_at( 0 ); } - nssv_constexpr const_reference back() const { return data_at( size() - 1 ); } + nssv_constexpr const_reference front() const + { + return data_at(0); + } + nssv_constexpr const_reference back() const + { + return data_at(size() - 1); + } - nssv_constexpr const_pointer data() const nssv_noexcept { return data_; } + nssv_constexpr const_pointer data() const nssv_noexcept + { + return data_; + } // 24.4.2.5 Modifiers: - nssv_constexpr14 void remove_prefix( size_type n ) + nssv_constexpr14 void remove_prefix(size_type n) { - assert( n <= size() ); - data_ += n; - size_ -= n; + assert(n <= size()); + data_ += n; + size_ -= n; } - nssv_constexpr14 void remove_suffix( size_type n ) + nssv_constexpr14 void remove_suffix(size_type n) { - assert( n <= size() ); - size_ -= n; + assert(n <= size()); + size_ -= n; } - nssv_constexpr14 void swap( basic_string_view & other ) nssv_noexcept + nssv_constexpr14 void swap(basic_string_view& other) nssv_noexcept { - using std::swap; - swap( data_, other.data_ ); - swap( size_, other.size_ ); + using std::swap; + swap(data_, other.data_); + swap(size_, other.size_); } // 24.4.2.6 String operations: - size_type copy( CharT * dest, size_type n, size_type pos = 0 ) const + size_type copy(CharT* dest, size_type n, size_type pos = 0) const { - if ( pos > size() ) - throw std::out_of_range("nonst::string_view::copy()"); + if (pos > size()) + throw std::out_of_range("nonst::string_view::copy()"); - const size_type rlen = (std::min)( n, size() - pos ); + const size_type rlen = (std::min)(n, size() - pos); - (void) Traits::copy( dest, data() + pos, rlen ); + (void)Traits::copy(dest, data() + pos, rlen); - return rlen; + return rlen; } - nssv_constexpr14 basic_string_view substr( size_type pos = 0, size_type n = npos ) const + nssv_constexpr14 basic_string_view substr(size_type pos = 0, size_type n = npos) const { - if ( pos > size() ) - throw std::out_of_range("nonst::string_view::substr()"); + if (pos > size()) + throw std::out_of_range("nonst::string_view::substr()"); - return basic_string_view( data() + pos, (std::min)( n, size() - pos ) ); + return basic_string_view(data() + pos, (std::min)(n, size() - pos)); } // compare(), 6x: - nssv_constexpr14 int compare( basic_string_view other ) const nssv_noexcept // (1) + nssv_constexpr14 int compare(basic_string_view other) const nssv_noexcept // (1) { - if ( const int result = Traits::compare( data(), other.data(), (std::min)( size(), other.size() ) ) ) - return result; + if (const int result = + Traits::compare(data(), other.data(), (std::min)(size(), other.size()))) + return result; - return size() == other.size() ? 0 : size() < other.size() ? -1 : 1; + return size() == other.size() ? 0 : size() < other.size() ? -1 : 1; } - nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other ) const // (2) + nssv_constexpr int compare(size_type pos1, size_type n1, + basic_string_view other) const // (2) { - return substr( pos1, n1 ).compare( other ); + return substr(pos1, n1).compare(other); } - nssv_constexpr int compare( size_type pos1, size_type n1, basic_string_view other, size_type pos2, size_type n2 ) const // (3) + nssv_constexpr int compare(size_type pos1, size_type n1, basic_string_view other, + size_type pos2, size_type n2) const // (3) { - return substr( pos1, n1 ).compare( other.substr( pos2, n2 ) ); + return substr(pos1, n1).compare(other.substr(pos2, n2)); } - nssv_constexpr int compare( CharT const * s ) const // (4) + nssv_constexpr int compare(CharT const* s) const // (4) { - return compare( basic_string_view( s ) ); + return compare(basic_string_view(s)); } - nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s ) const // (5) + nssv_constexpr int compare(size_type pos1, size_type n1, CharT const* s) const // (5) { - return substr( pos1, n1 ).compare( basic_string_view( s ) ); + return substr(pos1, n1).compare(basic_string_view(s)); } - nssv_constexpr int compare( size_type pos1, size_type n1, CharT const * s, size_type n2 ) const // (6) + nssv_constexpr int compare(size_type pos1, size_type n1, CharT const* s, + size_type n2) const // (6) { - return substr( pos1, n1 ).compare( basic_string_view( s, n2 ) ); + return substr(pos1, n1).compare(basic_string_view(s, n2)); } // 24.4.2.7 Searching: // starts_with(), 3x, since C++20: - nssv_constexpr bool starts_with( basic_string_view v ) const nssv_noexcept // (1) + nssv_constexpr bool starts_with(basic_string_view v) const nssv_noexcept // (1) { - return size() >= v.size() && compare( 0, v.size(), v ) == 0; + return size() >= v.size() && compare(0, v.size(), v) == 0; } - nssv_constexpr bool starts_with( CharT c ) const nssv_noexcept // (2) + nssv_constexpr bool starts_with(CharT c) const nssv_noexcept // (2) { - return starts_with( basic_string_view( &c, 1 ) ); + return starts_with(basic_string_view(&c, 1)); } - nssv_constexpr bool starts_with( CharT const * s ) const // (3) + nssv_constexpr bool starts_with(CharT const* s) const // (3) { - return starts_with( basic_string_view( s ) ); + return starts_with(basic_string_view(s)); } // ends_with(), 3x, since C++20: - nssv_constexpr bool ends_with( basic_string_view v ) const nssv_noexcept // (1) + nssv_constexpr bool ends_with(basic_string_view v) const nssv_noexcept // (1) { - return size() >= v.size() && compare( size() - v.size(), npos, v ) == 0; + return size() >= v.size() && compare(size() - v.size(), npos, v) == 0; } - nssv_constexpr bool ends_with( CharT c ) const nssv_noexcept // (2) + nssv_constexpr bool ends_with(CharT c) const nssv_noexcept // (2) { - return ends_with( basic_string_view( &c, 1 ) ); + return ends_with(basic_string_view(&c, 1)); } - nssv_constexpr bool ends_with( CharT const * s ) const // (3) + nssv_constexpr bool ends_with(CharT const* s) const // (3) { - return ends_with( basic_string_view( s ) ); + return ends_with(basic_string_view(s)); } // find(), 4x: - nssv_constexpr14 size_type find( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) + nssv_constexpr14 size_type find(basic_string_view v, + size_type pos = 0) const nssv_noexcept // (1) { - return assert( v.size() == 0 || v.data() != nssv_nullptr ) - , pos >= size() - ? npos - : to_pos( std::search( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); + return assert(v.size() == 0 || v.data() != nssv_nullptr), + pos >= size() ? npos : + to_pos(std::search(cbegin() + pos, cend(), v.cbegin(), + v.cend(), Traits::eq)); } - nssv_constexpr14 size_type find( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) + nssv_constexpr14 size_type find(CharT c, + size_type pos = 0) const nssv_noexcept // (2) { - return find( basic_string_view( &c, 1 ), pos ); + return find(basic_string_view(&c, 1), pos); } - nssv_constexpr14 size_type find( CharT const * s, size_type pos, size_type n ) const // (3) + nssv_constexpr14 size_type find(CharT const* s, size_type pos, + size_type n) const // (3) { - return find( basic_string_view( s, n ), pos ); + return find(basic_string_view(s, n), pos); } - nssv_constexpr14 size_type find( CharT const * s, size_type pos = 0 ) const // (4) + nssv_constexpr14 size_type find(CharT const* s, size_type pos = 0) const // (4) { - return find( basic_string_view( s ), pos ); + return find(basic_string_view(s), pos); } // rfind(), 4x: - nssv_constexpr14 size_type rfind( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) + nssv_constexpr14 size_type rfind(basic_string_view v, + size_type pos = npos) const nssv_noexcept // (1) { - if ( size() < v.size() ) - return npos; + if (size() < v.size()) + return npos; - if ( v.empty() ) - return (std::min)( size(), pos ); + if (v.empty()) + return (std::min)(size(), pos); - const_iterator last = cbegin() + (std::min)( size() - v.size(), pos ) + v.size(); - const_iterator result = std::find_end( cbegin(), last, v.cbegin(), v.cend(), Traits::eq ); + const_iterator last = cbegin() + (std::min)(size() - v.size(), pos) + v.size(); + const_iterator result = + std::find_end(cbegin(), last, v.cbegin(), v.cend(), Traits::eq); - return result != last ? size_type( result - cbegin() ) : npos; + return result != last ? size_type(result - cbegin()) : npos; } - nssv_constexpr14 size_type rfind( CharT c, size_type pos = npos ) const nssv_noexcept // (2) + nssv_constexpr14 size_type rfind(CharT c, + size_type pos = npos) const nssv_noexcept // (2) { - return rfind( basic_string_view( &c, 1 ), pos ); + return rfind(basic_string_view(&c, 1), pos); } - nssv_constexpr14 size_type rfind( CharT const * s, size_type pos, size_type n ) const // (3) + nssv_constexpr14 size_type rfind(CharT const* s, size_type pos, + size_type n) const // (3) { - return rfind( basic_string_view( s, n ), pos ); + return rfind(basic_string_view(s, n), pos); } - nssv_constexpr14 size_type rfind( CharT const * s, size_type pos = npos ) const // (4) + nssv_constexpr14 size_type rfind(CharT const* s, size_type pos = npos) const // (4) { - return rfind( basic_string_view( s ), pos ); + return rfind(basic_string_view(s), pos); } // find_first_of(), 4x: - nssv_constexpr size_type find_first_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) + nssv_constexpr size_type find_first_of(basic_string_view v, + size_type pos = 0) const nssv_noexcept // (1) { - return pos >= size() - ? npos - : to_pos( std::find_first_of( cbegin() + pos, cend(), v.cbegin(), v.cend(), Traits::eq ) ); + return pos >= size() ? npos : + to_pos(std::find_first_of(cbegin() + pos, cend(), v.cbegin(), + v.cend(), Traits::eq)); } - nssv_constexpr size_type find_first_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) + nssv_constexpr size_type find_first_of(CharT c, + size_type pos = 0) const nssv_noexcept // (2) { - return find_first_of( basic_string_view( &c, 1 ), pos ); + return find_first_of(basic_string_view(&c, 1), pos); } - nssv_constexpr size_type find_first_of( CharT const * s, size_type pos, size_type n ) const // (3) + nssv_constexpr size_type find_first_of(CharT const* s, size_type pos, + size_type n) const // (3) { - return find_first_of( basic_string_view( s, n ), pos ); + return find_first_of(basic_string_view(s, n), pos); } - nssv_constexpr size_type find_first_of( CharT const * s, size_type pos = 0 ) const // (4) + nssv_constexpr size_type find_first_of(CharT const* s, + size_type pos = 0) const // (4) { - return find_first_of( basic_string_view( s ), pos ); + return find_first_of(basic_string_view(s), pos); } // find_last_of(), 4x: - nssv_constexpr size_type find_last_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) + nssv_constexpr size_type + find_last_of(basic_string_view v, size_type pos = npos) const nssv_noexcept // (1) { - return empty() - ? npos - : pos >= size() - ? find_last_of( v, size() - 1 ) - : to_pos( std::find_first_of( const_reverse_iterator( cbegin() + pos + 1 ), crend(), v.cbegin(), v.cend(), Traits::eq ) ); + return empty() ? + npos : + pos >= size() ? + find_last_of(v, size() - 1) : + to_pos(std::find_first_of(const_reverse_iterator(cbegin() + pos + 1), + crend(), v.cbegin(), v.cend(), Traits::eq)); } - nssv_constexpr size_type find_last_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) + nssv_constexpr size_type + find_last_of(CharT c, size_type pos = npos) const nssv_noexcept // (2) { - return find_last_of( basic_string_view( &c, 1 ), pos ); + return find_last_of(basic_string_view(&c, 1), pos); } - nssv_constexpr size_type find_last_of( CharT const * s, size_type pos, size_type count ) const // (3) + nssv_constexpr size_type find_last_of(CharT const* s, size_type pos, + size_type count) const // (3) { - return find_last_of( basic_string_view( s, count ), pos ); + return find_last_of(basic_string_view(s, count), pos); } - nssv_constexpr size_type find_last_of( CharT const * s, size_type pos = npos ) const // (4) + nssv_constexpr size_type find_last_of(CharT const* s, + size_type pos = npos) const // (4) { - return find_last_of( basic_string_view( s ), pos ); + return find_last_of(basic_string_view(s), pos); } // find_first_not_of(), 4x: - nssv_constexpr size_type find_first_not_of( basic_string_view v, size_type pos = 0 ) const nssv_noexcept // (1) + nssv_constexpr size_type + find_first_not_of(basic_string_view v, size_type pos = 0) const nssv_noexcept // (1) { - return pos >= size() - ? npos - : to_pos( std::find_if( cbegin() + pos, cend(), not_in_view( v ) ) ); + return pos >= size() ? npos : + to_pos(std::find_if(cbegin() + pos, cend(), not_in_view(v))); } - nssv_constexpr size_type find_first_not_of( CharT c, size_type pos = 0 ) const nssv_noexcept // (2) + nssv_constexpr size_type + find_first_not_of(CharT c, size_type pos = 0) const nssv_noexcept // (2) { - return find_first_not_of( basic_string_view( &c, 1 ), pos ); + return find_first_not_of(basic_string_view(&c, 1), pos); } - nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos, size_type count ) const // (3) + nssv_constexpr size_type find_first_not_of(CharT const* s, size_type pos, + size_type count) const // (3) { - return find_first_not_of( basic_string_view( s, count ), pos ); + return find_first_not_of(basic_string_view(s, count), pos); } - nssv_constexpr size_type find_first_not_of( CharT const * s, size_type pos = 0 ) const // (4) + nssv_constexpr size_type find_first_not_of(CharT const* s, + size_type pos = 0) const // (4) { - return find_first_not_of( basic_string_view( s ), pos ); + return find_first_not_of(basic_string_view(s), pos); } // find_last_not_of(), 4x: - nssv_constexpr size_type find_last_not_of( basic_string_view v, size_type pos = npos ) const nssv_noexcept // (1) + nssv_constexpr size_type find_last_not_of( + basic_string_view v, size_type pos = npos) const nssv_noexcept // (1) { - return empty() - ? npos - : pos >= size() - ? find_last_not_of( v, size() - 1 ) - : to_pos( std::find_if( const_reverse_iterator( cbegin() + pos + 1 ), crend(), not_in_view( v ) ) ); + return empty() ? npos : + pos >= size() ? + find_last_not_of(v, size() - 1) : + to_pos(std::find_if(const_reverse_iterator(cbegin() + pos + 1), + crend(), not_in_view(v))); } - nssv_constexpr size_type find_last_not_of( CharT c, size_type pos = npos ) const nssv_noexcept // (2) + nssv_constexpr size_type + find_last_not_of(CharT c, size_type pos = npos) const nssv_noexcept // (2) { - return find_last_not_of( basic_string_view( &c, 1 ), pos ); + return find_last_not_of(basic_string_view(&c, 1), pos); } - nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos, size_type count ) const // (3) + nssv_constexpr size_type find_last_not_of(CharT const* s, size_type pos, + size_type count) const // (3) { - return find_last_not_of( basic_string_view( s, count ), pos ); + return find_last_not_of(basic_string_view(s, count), pos); } - nssv_constexpr size_type find_last_not_of( CharT const * s, size_type pos = npos ) const // (4) + nssv_constexpr size_type find_last_not_of(CharT const* s, + size_type pos = npos) const // (4) { - return find_last_not_of( basic_string_view( s ), pos ); + return find_last_not_of(basic_string_view(s), pos); } // Constants: @@ -779,303 +864,333 @@ class basic_string_view #if nssv_CPP17_OR_GREATER static nssv_constexpr size_type npos = size_type(-1); #elif nssv_CPP11_OR_GREATER - enum : size_type { npos = size_type(-1) }; + enum : size_type + { + npos = size_type(-1) + }; #else - enum { npos = size_type(-1) }; + enum + { + npos = size_type(-1) + }; #endif -private: + private: struct not_in_view { - const basic_string_view v; + const basic_string_view v; - nssv_constexpr not_in_view( basic_string_view v ) : v( v ) {} + nssv_constexpr not_in_view(basic_string_view v) : v(v) + { + } - nssv_constexpr bool operator()( CharT c ) const - { - return npos == v.find_first_of( c ); - } + nssv_constexpr bool operator()(CharT c) const + { + return npos == v.find_first_of(c); + } }; - nssv_constexpr size_type to_pos( const_iterator it ) const + nssv_constexpr size_type to_pos(const_iterator it) const { - return it == cend() ? npos : size_type( it - cbegin() ); + return it == cend() ? npos : size_type(it - cbegin()); } - nssv_constexpr size_type to_pos( const_reverse_iterator it ) const + nssv_constexpr size_type to_pos(const_reverse_iterator it) const { - return it == crend() ? npos : size_type( crend() - it - 1 ); + return it == crend() ? npos : size_type(crend() - it - 1); } - nssv_constexpr const_reference data_at( size_type pos ) const + nssv_constexpr const_reference data_at(size_type pos) const { -#if nssv_BETWEEN( nssv_COMPILER_GNUC_VERSION, 1, 500 ) - return data_[pos]; +#if nssv_BETWEEN(nssv_COMPILER_GNUC_VERSION, 1, 500) + return data_[pos]; #else - return assert( pos < size() ), data_[pos]; + return assert(pos < size()), data_[pos]; #endif } -private: + private: const_pointer data_; - size_type size_; + size_type size_; -public: + public: #if nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS - template< class Allocator > - basic_string_view( std::basic_string const & s ) nssv_noexcept - : data_( s.data() ) - , size_( s.size() ) - {} + template + basic_string_view(std::basic_string const& s) nssv_noexcept + : data_(s.data()), + size_(s.size()) + { + } #if nssv_HAVE_EXPLICIT_CONVERSION - template< class Allocator > + template explicit operator std::basic_string() const { - return to_string( Allocator() ); + return to_string(Allocator()); } -#endif // nssv_HAVE_EXPLICIT_CONVERSION +#endif // nssv_HAVE_EXPLICIT_CONVERSION #if nssv_CPP11_OR_GREATER - template< class Allocator = std::allocator > + template > std::basic_string - to_string( Allocator const & a = Allocator() ) const + to_string(Allocator const& a = Allocator()) const { - return std::basic_string( begin(), end(), a ); + return std::basic_string(begin(), end(), a); } #else - std::basic_string - to_string() const + std::basic_string to_string() const { - return std::basic_string( begin(), end() ); + return std::basic_string(begin(), end()); } - template< class Allocator > - std::basic_string - to_string( Allocator const & a ) const + template + std::basic_string to_string(Allocator const& a) const { - return std::basic_string( begin(), end(), a ); + return std::basic_string(begin(), end(), a); } -#endif // nssv_CPP11_OR_GREATER - -#endif // nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS -}; - -// -// Non-member functions: -// - -// 24.4.3 Non-member comparison functions: -// lexicographically compare two string views (function template): - -template< class CharT, class Traits > -nssv_constexpr bool operator== ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) == 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator!= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) != 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator< ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator<= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator> ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -template< class CharT, class Traits > -nssv_constexpr bool operator>= ( - basic_string_view lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } - -// Let S be basic_string_view, and sv be an instance of S. -// Implementations shall provide sufficient additional overloads marked -// constexpr and noexcept so that an object t with an implicit conversion -// to S can be compared according to Table 67. - -#if nssv_CPP11_OR_GREATER && ! nssv_BETWEEN( nssv_COMPILER_MSVC_VERSION, 100, 141 ) - -#define nssv_BASIC_STRING_VIEW_I(T,U) typename std::decay< basic_string_view >::type - -#if nssv_BETWEEN( nssv_COMPILER_MSVC_VERSION, 140, 150 ) -# define nssv_MSVC_ORDER(x) , int=x +#endif // nssv_CPP11_OR_GREATER + +#endif // nssv_CONFIG_CONVERSION_STD_STRING_CLASS_METHODS + }; + + // + // Non-member functions: + // + + // 24.4.3 Non-member comparison functions: + // lexicographically compare two string views (function template): + + template + nssv_constexpr bool operator==(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) == 0; + } + + template + nssv_constexpr bool operator!=(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) != 0; + } + + template + nssv_constexpr bool operator<(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) < 0; + } + + template + nssv_constexpr bool operator<=(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) <= 0; + } + + template + nssv_constexpr bool operator>(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) > 0; + } + + template + nssv_constexpr bool operator>=(basic_string_view lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) >= 0; + } + + // Let S be basic_string_view, and sv be an instance of S. + // Implementations shall provide sufficient additional overloads marked + // constexpr and noexcept so that an object t with an implicit conversion + // to S can be compared according to Table 67. + +#if nssv_CPP11_OR_GREATER && !nssv_BETWEEN(nssv_COMPILER_MSVC_VERSION, 100, 141) + +#define nssv_BASIC_STRING_VIEW_I(T, U) typename std::decay >::type + +#if nssv_BETWEEN(nssv_COMPILER_MSVC_VERSION, 140, 150) +#define nssv_MSVC_ORDER(x) , int = x #else -# define nssv_MSVC_ORDER(x) /*, int=x*/ +#define nssv_MSVC_ORDER(x) /*, int=x*/ #endif -// == - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator==( - basic_string_view lhs, - nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) == 0; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator==( - nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, - basic_string_view rhs ) nssv_noexcept -{ return lhs.size() == rhs.size() && lhs.compare( rhs ) == 0; } - -// != - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator!= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.size() != rhs.size() || lhs.compare( rhs ) != 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator!= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) != 0 ; } - -// < - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator< ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator< ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) < 0 ; } - -// <= - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator<= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator<= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) <= 0 ; } - -// > - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator> ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator> ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) > 0 ; } - -// >= - -template< class CharT, class Traits nssv_MSVC_ORDER(1) > -nssv_constexpr bool operator>= ( - basic_string_view < CharT, Traits > lhs, - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } - -template< class CharT, class Traits nssv_MSVC_ORDER(2) > -nssv_constexpr bool operator>= ( - nssv_BASIC_STRING_VIEW_I( CharT, Traits ) lhs, - basic_string_view < CharT, Traits > rhs ) nssv_noexcept -{ return lhs.compare( rhs ) >= 0 ; } + // == + + template + nssv_constexpr bool operator==(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) + rhs) nssv_noexcept + { + return lhs.compare(rhs) == 0; + } + + template + nssv_constexpr bool operator==(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.size() == rhs.size() && lhs.compare(rhs) == 0; + } + + // != + + template + nssv_constexpr bool operator!=(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) + rhs) nssv_noexcept + { + return lhs.size() != rhs.size() || lhs.compare(rhs) != 0; + } + + template + nssv_constexpr bool operator!=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) != 0; + } + + // < + + template + nssv_constexpr bool operator<(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept + { + return lhs.compare(rhs) < 0; + } + + template + nssv_constexpr bool operator<(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) < 0; + } + + // <= + + template + nssv_constexpr bool operator<=(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) + rhs) nssv_noexcept + { + return lhs.compare(rhs) <= 0; + } + + template + nssv_constexpr bool operator<=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) <= 0; + } + + // > + + template + nssv_constexpr bool operator>(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) rhs) nssv_noexcept + { + return lhs.compare(rhs) > 0; + } + + template + nssv_constexpr bool operator>(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) > 0; + } + + // >= + + template + nssv_constexpr bool operator>=(basic_string_view lhs, + nssv_BASIC_STRING_VIEW_I(CharT, Traits) + rhs) nssv_noexcept + { + return lhs.compare(rhs) >= 0; + } + + template + nssv_constexpr bool operator>=(nssv_BASIC_STRING_VIEW_I(CharT, Traits) lhs, + basic_string_view rhs) nssv_noexcept + { + return lhs.compare(rhs) >= 0; + } #undef nssv_MSVC_ORDER #undef nssv_BASIC_STRING_VIEW_I -#endif // nssv_CPP11_OR_GREATER +#endif // nssv_CPP11_OR_GREATER -// 24.4.4 Inserters and extractors: + // 24.4.4 Inserters and extractors: -namespace detail { + namespace detail + { -template< class Stream > -void write_padding( Stream & os, std::streamsize n ) -{ - for ( std::streamsize i = 0; i < n; ++i ) - os.rdbuf()->sputc( os.fill() ); -} + template + void write_padding(Stream& os, std::streamsize n) + { + for (std::streamsize i = 0; i < n; ++i) + os.rdbuf()->sputc(os.fill()); + } -template< class Stream, class View > -Stream & write_to_stream( Stream & os, View const & sv ) -{ - typename Stream::sentry sentry( os ); + template + Stream& write_to_stream(Stream& os, View const& sv) + { + typename Stream::sentry sentry(os); - if ( !os ) - return os; + if (!os) + return os; - const std::streamsize length = static_cast( sv.length() ); + const std::streamsize length = static_cast(sv.length()); // Whether, and how, to pad: - const bool pad = ( length < os.width() ); - const bool left_pad = pad && ( os.flags() & std::ios_base::adjustfield ) == std::ios_base::right; + const bool pad = (length < os.width()); + const bool left_pad = + pad && (os.flags() & std::ios_base::adjustfield) == std::ios_base::right; - if ( left_pad ) - write_padding( os, os.width() - length ); + if (left_pad) + write_padding(os, os.width() - length); // Write span characters: - os.rdbuf()->sputn( sv.begin(), length ); + os.rdbuf()->sputn(sv.begin(), length); - if ( pad && !left_pad ) - write_padding( os, os.width() - length ); + if (pad && !left_pad) + write_padding(os, os.width() - length); // Reset output stream width: - os.width( 0 ); + os.width(0); return os; -} + } -} // namespace detail + } // namespace detail -template< class CharT, class Traits > -std::basic_ostream & -operator<<( - std::basic_ostream& os, - basic_string_view sv ) -{ - return detail::write_to_stream( os, sv ); -} + template + std::basic_ostream& operator<<(std::basic_ostream& os, + basic_string_view sv) + { + return detail::write_to_stream(os, sv); + } -// Several typedefs for common character types are provided: + // Several typedefs for common character types are provided: -typedef basic_string_view string_view; -typedef basic_string_view wstring_view; + typedef basic_string_view string_view; + typedef basic_string_view wstring_view; #if nssv_HAVE_WCHAR16_T -typedef basic_string_view u16string_view; -typedef basic_string_view u32string_view; + typedef basic_string_view u16string_view; + typedef basic_string_view u32string_view; #endif -}} // namespace nonstd::sv_lite + } // namespace sv_lite +} // namespace nonstd::sv_lite // // 24.4.6 Suffix for basic_string_view literals: @@ -1083,59 +1198,71 @@ typedef basic_string_view u32string_view; #if nssv_HAVE_USER_DEFINED_LITERALS -namespace nonstd { -nssv_inline_ns namespace literals { -nssv_inline_ns namespace string_view_literals { +namespace nonstd +{ +nssv_inline_ns namespace literals +{ + nssv_inline_ns namespace string_view_literals + { #if nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS -nssv_constexpr nonstd::sv_lite::string_view operator "" sv( const char* str, size_t len ) nssv_noexcept // (1) -{ - return nonstd::sv_lite::string_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::string_view operator"" sv(const char* str, size_t len) + nssv_noexcept // (1) + { + return nonstd::sv_lite::string_view{ str, len }; + } -nssv_constexpr nonstd::sv_lite::u16string_view operator "" sv( const char16_t* str, size_t len ) nssv_noexcept // (2) -{ - return nonstd::sv_lite::u16string_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::u16string_view operator"" sv( + const char16_t* str, size_t len) nssv_noexcept // (2) + { + return nonstd::sv_lite::u16string_view{ str, len }; + } -nssv_constexpr nonstd::sv_lite::u32string_view operator "" sv( const char32_t* str, size_t len ) nssv_noexcept // (3) -{ - return nonstd::sv_lite::u32string_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::u32string_view operator"" sv( + const char32_t* str, size_t len) nssv_noexcept // (3) + { + return nonstd::sv_lite::u32string_view{ str, len }; + } -nssv_constexpr nonstd::sv_lite::wstring_view operator "" sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) -{ - return nonstd::sv_lite::wstring_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::wstring_view operator"" sv( + const wchar_t* str, size_t len) nssv_noexcept // (4) + { + return nonstd::sv_lite::wstring_view{ str, len }; + } -#endif // nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS +#endif // nssv_CONFIG_STD_SV_OPERATOR && nssv_HAVE_STD_DEFINED_LITERALS #if nssv_CONFIG_USR_SV_OPERATOR -nssv_constexpr nonstd::sv_lite::string_view operator "" _sv( const char* str, size_t len ) nssv_noexcept // (1) -{ - return nonstd::sv_lite::string_view{ str, len }; -} - -nssv_constexpr nonstd::sv_lite::u16string_view operator "" _sv( const char16_t* str, size_t len ) nssv_noexcept // (2) -{ - return nonstd::sv_lite::u16string_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::string_view operator"" _sv( + const char* str, size_t len) nssv_noexcept // (1) + { + return nonstd::sv_lite::string_view{ str, len }; + } -nssv_constexpr nonstd::sv_lite::u32string_view operator "" _sv( const char32_t* str, size_t len ) nssv_noexcept // (3) -{ - return nonstd::sv_lite::u32string_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::u16string_view operator"" _sv( + const char16_t* str, size_t len) nssv_noexcept // (2) + { + return nonstd::sv_lite::u16string_view{ str, len }; + } -nssv_constexpr nonstd::sv_lite::wstring_view operator "" _sv( const wchar_t* str, size_t len ) nssv_noexcept // (4) -{ - return nonstd::sv_lite::wstring_view{ str, len }; -} + nssv_constexpr nonstd::sv_lite::u32string_view operator"" _sv( + const char32_t* str, size_t len) nssv_noexcept // (3) + { + return nonstd::sv_lite::u32string_view{ str, len }; + } -#endif // nssv_CONFIG_USR_SV_OPERATOR + nssv_constexpr nonstd::sv_lite::wstring_view operator"" _sv( + const wchar_t* str, size_t len) nssv_noexcept // (4) + { + return nonstd::sv_lite::wstring_view{ str, len }; + } -}}} // namespace nonstd::literals::string_view_literals +#endif // nssv_CONFIG_USR_SV_OPERATOR + } +} +} // namespace nonstd #endif @@ -1145,54 +1272,57 @@ nssv_constexpr nonstd::sv_lite::wstring_view operator "" _sv( const wchar_t* str #if nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS -namespace nonstd { -namespace sv_lite { +namespace nonstd +{ +namespace sv_lite +{ // Exclude MSVC 14 (19.00): it yields ambiguous to_string(): #if nssv_CPP11_OR_GREATER && nssv_COMPILER_MSVC_VERSION != 140 -template< class CharT, class Traits, class Allocator = std::allocator > -std::basic_string -to_string( basic_string_view v, Allocator const & a = Allocator() ) +template > +std::basic_string to_string(basic_string_view v, + Allocator const& a = Allocator()) { - return std::basic_string( v.begin(), v.end(), a ); + return std::basic_string(v.begin(), v.end(), a); } #else -template< class CharT, class Traits > -std::basic_string -to_string( basic_string_view v ) +template +std::basic_string to_string(basic_string_view v) { - return std::basic_string( v.begin(), v.end() ); + return std::basic_string(v.begin(), v.end()); } -template< class CharT, class Traits, class Allocator > -std::basic_string -to_string( basic_string_view v, Allocator const & a ) +template +std::basic_string to_string(basic_string_view v, + Allocator const& a) { - return std::basic_string( v.begin(), v.end(), a ); + return std::basic_string(v.begin(), v.end(), a); } -#endif // nssv_CPP11_OR_GREATER +#endif // nssv_CPP11_OR_GREATER -template< class CharT, class Traits, class Allocator > +template basic_string_view -to_string_view( std::basic_string const & s ) +to_string_view(std::basic_string const& s) { - return basic_string_view( s.data(), s.size() ); + return basic_string_view(s.data(), s.size()); } -}} // namespace nonstd::sv_lite +} // namespace sv_lite +} // namespace nonstd -#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS +#endif // nssv_CONFIG_CONVERSION_STD_STRING_FREE_FUNCTIONS // // make types and algorithms available in namespace nonstd: // -namespace nonstd { +namespace nonstd +{ using sv_lite::basic_string_view; using sv_lite::string_view; @@ -1221,7 +1351,7 @@ using sv_lite::to_string; using sv_lite::to_string_view; #endif -} // namespace nonstd +} // namespace nonstd // 24.4.5 Hash support (C++11): @@ -1232,53 +1362,54 @@ using sv_lite::to_string_view; #include -namespace std { +namespace std +{ -template<> -struct hash< nonstd::string_view > +template <> +struct hash { public: - std::size_t operator()( nonstd::string_view v ) const nssv_noexcept - { - return std::hash()( std::string( v.data(), v.size() ) ); - } + std::size_t operator()(nonstd::string_view v) const nssv_noexcept + { + return std::hash()(std::string(v.data(), v.size())); + } }; -template<> -struct hash< nonstd::wstring_view > +template <> +struct hash { public: - std::size_t operator()( nonstd::wstring_view v ) const nssv_noexcept - { - return std::hash()( std::wstring( v.data(), v.size() ) ); - } + std::size_t operator()(nonstd::wstring_view v) const nssv_noexcept + { + return std::hash()(std::wstring(v.data(), v.size())); + } }; -template<> -struct hash< nonstd::u16string_view > +template <> +struct hash { public: - std::size_t operator()( nonstd::u16string_view v ) const nssv_noexcept - { - return std::hash()( std::u16string( v.data(), v.size() ) ); - } + std::size_t operator()(nonstd::u16string_view v) const nssv_noexcept + { + return std::hash()(std::u16string(v.data(), v.size())); + } }; -template<> -struct hash< nonstd::u32string_view > +template <> +struct hash { public: - std::size_t operator()( nonstd::u32string_view v ) const nssv_noexcept - { - return std::hash()( std::u32string( v.data(), v.size() ) ); - } + std::size_t operator()(nonstd::u32string_view v) const nssv_noexcept + { + return std::hash()(std::u32string(v.data(), v.size())); + } }; -} // namespace std +} // namespace std -#endif // nssv_HAVE_STD_HASH +#endif // nssv_HAVE_STD_HASH nssv_RESTORE_WARNINGS() -#endif // nssv_HAVE_STD_STRING_VIEW -#endif // NONSTD_SV_LITE_H_INCLUDED +#endif // nssv_HAVE_STD_STRING_VIEW +#endif // NONSTD_SV_LITE_H_INCLUDED diff --git a/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.cpp b/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.cpp index bf75a0a45..5276ff854 100644 --- a/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.cpp +++ b/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.cpp @@ -7,10 +7,9 @@ #include #include -DataStreamMQTT::DataStreamMQTT(): - _running(false) +DataStreamMQTT::DataStreamMQTT() : _running(false) { - _notification_action = new QAction(this); + _notification_action = new QAction(this); connect(_notification_action, &QAction::triggered, this, [this]() { QMessageBox::warning(nullptr, "MQTT error", @@ -34,43 +33,44 @@ DataStreamMQTT::~DataStreamMQTT() delete _dialog; } -bool DataStreamMQTT::start(QStringList *) +bool DataStreamMQTT::start(QStringList*) { if (_running) { return _running; } - //cleanup notifications + // cleanup notifications _failed_parsing = 0; emit notificationsChanged(0); - if( parserFactories() == nullptr || parserFactories()->empty() ) + if (parserFactories() == nullptr || parserFactories()->empty()) { - QMessageBox::warning(nullptr,tr("MQTT Client"), tr("No available MessageParsers"), QMessageBox::Ok); + QMessageBox::warning(nullptr, tr("MQTT Client"), tr("No available MessageParsers"), + QMessageBox::Ok); _running = false; return false; } bool first_start = _dialog->ui->comboBoxProtocol->count() == 0; - if( first_start ) + if (first_start) { // change the section of the dialog related to protocols - for( const auto& it: *parserFactories()) + for (const auto& it : *parserFactories()) { - _dialog->ui->comboBoxProtocol->addItem( it.first ); + _dialog->ui->comboBoxProtocol->addItem(it.first); - if(auto widget = it.second->optionsWidget() ) + if (auto widget = it.second->optionsWidget()) { widget->setVisible(false); - _dialog->ui->layoutOptions->addWidget( widget ); + _dialog->ui->layoutOptions->addWidget(widget); } } connect(_dialog->ui->comboBoxProtocol, - qOverload(&QComboBox::currentIndexChanged), - this, &DataStreamMQTT::onComboProtocolChanged); + qOverload(&QComboBox::currentIndexChanged), this, + &DataStreamMQTT::onComboProtocolChanged); } _running = false; @@ -79,22 +79,21 @@ bool DataStreamMQTT::start(QStringList *) _protocol = settings.value("MosquittoMQTT::serialization_protocol", "JSON").toString(); _dialog->ui->comboBoxProtocol->setCurrentText(_protocol); - if( _dialog->exec() == QDialog::Rejected ) + if (_dialog->exec() == QDialog::Rejected) { return false; } _protocol = _dialog->ui->comboBoxProtocol->currentText(); // remove all previous subscriptions and create new ones - for( const auto& topic: _mosq->config().topics ) + for (const auto& topic : _mosq->config().topics) { _mosq->unsubscribe(topic); } - for (const auto& item: _dialog->ui->listWidget->selectedItems()) + for (const auto& item : _dialog->ui->listWidget->selectedItems()) { - MQTTClient::TopicCallback callback = [this](const mosquitto_message* message) - { + MQTTClient::TopicCallback callback = [this](const mosquitto_message* message) { onMessageReceived(message); }; @@ -109,7 +108,7 @@ bool DataStreamMQTT::start(QStringList *) void DataStreamMQTT::shutdown() { - if( _running ) + if (_running) { _running = false; _parsers.clear(); @@ -123,12 +122,11 @@ bool DataStreamMQTT::isRunning() const return _running; } - void DataStreamMQTT::onComboProtocolChanged(const QString& selected_protocol) { if (_current_parser_creator) { - if( auto prev_widget = _current_parser_creator->optionsWidget()) + if (auto prev_widget = _current_parser_creator->optionsWidget()) { prev_widget->setVisible(false); } @@ -141,37 +139,39 @@ void DataStreamMQTT::onComboProtocolChanged(const QString& selected_protocol) } } -void DataStreamMQTT::onMessageReceived(const mosquitto_message *message) +void DataStreamMQTT::onMessageReceived(const mosquitto_message* message) { std::unique_lock lk(mutex()); auto it = _parsers.find(message->topic); - if( it == _parsers.end() ) + if (it == _parsers.end()) { - auto& parser_factory = parserFactories()->at( _protocol ); - auto parser = parser_factory->createParser({message->topic}, {}, {}, dataMap()); - it = _parsers.insert( {message->topic, parser} ).first; + auto& parser_factory = parserFactories()->at(_protocol); + auto parser = parser_factory->createParser({ message->topic }, {}, {}, dataMap()); + it = _parsers.insert({ message->topic, parser }).first; } auto& parser = it->second; bool result = false; - try { - MessageRef msg( static_cast(message->payload), message->payloadlen); + try + { + MessageRef msg(static_cast(message->payload), message->payloadlen); using namespace std::chrono; auto ts = high_resolution_clock::now().time_since_epoch(); - double timestamp = 1e-6* double( duration_cast(ts).count() ); + double timestamp = 1e-6 * double(duration_cast(ts).count()); result = parser->parseMessage(msg, timestamp); } - catch (std::exception& ) {} + catch (std::exception&) + { + } emit dataReceived(); - if( !result ) + if (!result) { _failed_parsing++; emit notificationsChanged(_failed_parsing); } } - diff --git a/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.h b/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.h index 7481a3b27..8e530a07d 100644 --- a/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.h +++ b/plotjuggler_plugins/DataStreamMQTT/datastream_mqtt.h @@ -46,12 +46,11 @@ class DataStreamMQTT : public PJ::DataStreamer private slots: - void onComboProtocolChanged(const QString &); + void onComboProtocolChanged(const QString&); void onMessageReceived(const mosquitto_message* message); private: - bool _running; std::unordered_map _parsers; @@ -70,5 +69,4 @@ private slots: ParserFactoryPlugin::Ptr _current_parser_creator; }; - -#endif // DATASTREAM_MQTT_H +#endif // DATASTREAM_MQTT_H diff --git a/plotjuggler_plugins/DataStreamMQTT/mosquitto_config.h b/plotjuggler_plugins/DataStreamMQTT/mosquitto_config.h index 8622055a8..4e631a5cc 100644 --- a/plotjuggler_plugins/DataStreamMQTT/mosquitto_config.h +++ b/plotjuggler_plugins/DataStreamMQTT/mosquitto_config.h @@ -5,7 +5,8 @@ #include #include -struct MosquittoConfig { +struct MosquittoConfig +{ int protocol_version; int keepalive; std::string host; @@ -27,28 +28,28 @@ struct MosquittoConfig { std::string ciphers; bool insecure; std::string tls_version; -# ifdef WITH_TLS_PSK +#ifdef WITH_TLS_PSK std::string psk; std::string psk_identity; -# endif +#endif - bool clean_session; /* sub */ - std::vector topics; /* sub */ - bool no_retain; /* sub */ + bool clean_session; /* sub */ + std::vector topics; /* sub */ + bool no_retain; /* sub */ std::vector filter_outs; /* sub */ - bool verbose; /* sub */ - bool eol; /* sub */ - int msg_count; /* sub */ + bool verbose; /* sub */ + bool eol; /* sub */ + int msg_count; /* sub */ #ifdef WITH_SOCKS std::string socks5_host; int socks5_port; std::string socks5_username; std::string socks5_password; #endif - mosquitto_property *connect_props; - mosquitto_property *subscribe_props; - mosquitto_property *unsubscribe_props; - mosquitto_property *disconnect_props; + mosquitto_property* connect_props; + mosquitto_property* subscribe_props; + mosquitto_property* unsubscribe_props; + mosquitto_property* disconnect_props; }; -#endif // MOSQUITTO_CONFIG_H +#endif // MOSQUITTO_CONFIG_H diff --git a/plotjuggler_plugins/DataStreamMQTT/mqtt_client.cpp b/plotjuggler_plugins/DataStreamMQTT/mqtt_client.cpp index 1ca64b181..8014f2996 100644 --- a/plotjuggler_plugins/DataStreamMQTT/mqtt_client.cpp +++ b/plotjuggler_plugins/DataStreamMQTT/mqtt_client.cpp @@ -8,37 +8,40 @@ #include #endif -void connect_callback(struct mosquitto *mosq, void *context, int result, int, const mosquitto_property *) +void connect_callback(struct mosquitto* mosq, void* context, int result, int, + const mosquitto_property*) { MQTTClient* self = static_cast(context); - if( !result ) + if (!result) { - for(const auto& topic: self->config().topics) + for (const auto& topic : self->config().topics) { mosquitto_subscribe(mosq, nullptr, topic.c_str(), self->config().qos); } } else { - QMessageBox::warning(nullptr, "MQTT Client", - QString("Connection error: %1").arg(mosquitto_reason_string(result)), - QMessageBox::Ok); + QMessageBox::warning( + nullptr, "MQTT Client", + QString("Connection error: %1").arg(mosquitto_reason_string(result)), + QMessageBox::Ok); } self->_connected = true; } -void disconnect_callback(struct mosquitto *mosq, void *context, int result) +void disconnect_callback(struct mosquitto* mosq, void* context, int result) { MQTTClient* self = static_cast(context); - if( self->isConnected() && result == MOSQ_ERR_CONN_LOST ) + if (self->isConnected() && result == MOSQ_ERR_CONN_LOST) { emit self->disconnected(); } } -void message_callback(struct mosquitto *mosq, void *context, const struct mosquitto_message *message, const mosquitto_property *) +void message_callback(struct mosquitto* mosq, void* context, + const struct mosquitto_message* message, const mosquitto_property*) { MQTTClient* self = static_cast(context); self->onMessageReceived(message); @@ -58,53 +61,50 @@ MQTTClient::MQTTClient() MQTTClient::~MQTTClient() { - if(_connected) + if (_connected) { disconnect(); } mosquitto_lib_cleanup(); } -bool MQTTClient::connect(const MosquittoConfig &config) +bool MQTTClient::connect(const MosquittoConfig& config) { - if( _connected ) + if (_connected) { disconnect(); } mosquitto_int_option(_mosq, MOSQ_OPT_PROTOCOL_VERSION, config.protocol_version); - if(( !config.username.empty() || !config.password.empty()) ) + if ((!config.username.empty() || !config.password.empty())) { - if(mosquitto_username_pw_set(_mosq, config.username.c_str(), config.password.c_str())) + if (mosquitto_username_pw_set(_mosq, config.username.c_str(), + config.password.c_str())) { return false; } } - if( config.cafile.empty() == false ) + if (config.cafile.empty() == false) { - const char *cafile = config.cafile.c_str(); - const char *certfile = config.certfile.empty() ? nullptr: config.certfile.c_str(); - const char *keyfile = config.keyfile.empty() ? nullptr: config.keyfile.c_str(); + const char* cafile = config.cafile.c_str(); + const char* certfile = config.certfile.empty() ? nullptr : config.certfile.c_str(); + const char* keyfile = config.keyfile.empty() ? nullptr : config.keyfile.c_str(); mosquitto_tls_set(_mosq, cafile, nullptr, certfile, keyfile, nullptr); } mosquitto_max_inflight_messages_set(_mosq, config.max_inflight); - const mosquitto_property *properties = nullptr; // todo + const mosquitto_property* properties = nullptr; // todo - int rc = mosquitto_connect_bind_v5(_mosq, - config.host.c_str(), - config.port, - config.keepalive, - nullptr, - properties); + int rc = mosquitto_connect_bind_v5(_mosq, config.host.c_str(), config.port, + config.keepalive, nullptr, properties); // TODO bind - if(rc>0) + if (rc > 0) { - if(rc == MOSQ_ERR_ERRNO) + if (rc == MOSQ_ERR_ERRNO) { char err[1024]; #ifndef WIN32 @@ -112,8 +112,8 @@ bool MQTTClient::connect(const MosquittoConfig &config) #else FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL); #endif - QMessageBox::warning(nullptr, "MQTT Client", - QString("Error: %1").arg(err), QMessageBox::Ok); + QMessageBox::warning(nullptr, "MQTT Client", QString("Error: %1").arg(err), + QMessageBox::Ok); } else { @@ -133,7 +133,7 @@ bool MQTTClient::connect(const MosquittoConfig &config) void MQTTClient::disconnect() { - if( _connected ) + if (_connected) { mosquitto_disconnect(_mosq); mosquitto_loop_stop(_mosq, true); @@ -148,26 +148,27 @@ bool MQTTClient::isConnected() const return _connected; } -void MQTTClient::addMessageCallback(const std::string &topic, MQTTClient::TopicCallback callback) +void MQTTClient::addMessageCallback(const std::string& topic, + MQTTClient::TopicCallback callback) { std::unique_lock lk(_mutex); _message_callbacks[topic] = callback; } -void MQTTClient::onMessageReceived(const mosquitto_message * message) +void MQTTClient::onMessageReceived(const mosquitto_message* message) { std::unique_lock lk(_mutex); _topics_set.insert(message->topic); auto it = _message_callbacks.find(message->topic); - if( it != _message_callbacks.end() ) + if (it != _message_callbacks.end()) { it->second(message); } } -const MosquittoConfig &MQTTClient::config() const +const MosquittoConfig& MQTTClient::config() const { return _config; } @@ -178,12 +179,12 @@ std::unordered_set MQTTClient::getTopicList() return _topics_set; } -void MQTTClient::subscribe(const std::string &topic, int qos) +void MQTTClient::subscribe(const std::string& topic, int qos) { mosquitto_subscribe(_mosq, nullptr, topic.c_str(), qos); } -void MQTTClient::unsubscribe(const std::string &topic) +void MQTTClient::unsubscribe(const std::string& topic) { mosquitto_unsubscribe(_mosq, nullptr, topic.c_str()); } diff --git a/plotjuggler_plugins/DataStreamMQTT/mqtt_client.h b/plotjuggler_plugins/DataStreamMQTT/mqtt_client.h index d0729b561..845bc94d0 100644 --- a/plotjuggler_plugins/DataStreamMQTT/mqtt_client.h +++ b/plotjuggler_plugins/DataStreamMQTT/mqtt_client.h @@ -10,7 +10,7 @@ #include #include -class MQTTClient: public QObject +class MQTTClient : public QObject { Q_OBJECT @@ -26,31 +26,31 @@ class MQTTClient: public QObject bool isConnected() const; - using TopicCallback = std::function; + using TopicCallback = std::function; void addMessageCallback(const std::string& topic, TopicCallback callback); bool _connected = false; - void onMessageReceived(const mosquitto_message *message); + void onMessageReceived(const mosquitto_message* message); const MosquittoConfig& config() const; std::unordered_set getTopicList(); - void subscribe(const std::string& topic, int qos ); + void subscribe(const std::string& topic, int qos); - void unsubscribe(const std::string& topic ); + void unsubscribe(const std::string& topic); signals: void disconnected(); private: - mosquitto *_mosq = nullptr; + mosquitto* _mosq = nullptr; std::unordered_map _message_callbacks; std::unordered_set _topics_set; std::mutex _mutex; MosquittoConfig _config; }; -#endif // MQTT_CLIENT_H +#endif // MQTT_CLIENT_H diff --git a/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.cpp b/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.cpp index a0637b2a1..81b2038cb 100644 --- a/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.cpp +++ b/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.cpp @@ -8,30 +8,28 @@ void MQTT_Dialog::onConnectionClosed() changeConnectionState(false); ui->listWidget->clear(); _topic_list.clear(); - ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); _topic_list_timer->stop(); } -MQTT_Dialog::MQTT_Dialog(MQTTClient::Ptr mosq_client): - QDialog(nullptr), - ui(new Ui::DataStreamMQTT), - _client(mosq_client) +MQTT_Dialog::MQTT_Dialog(MQTTClient::Ptr mosq_client) + : QDialog(nullptr), ui(new Ui::DataStreamMQTT), _client(mosq_client) { ui->setupUi(this); - ui->lineEditPort->setValidator( new QIntValidator ); + ui->lineEditPort->setValidator(new QIntValidator); - ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( false ); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - static QString uuid = QString("Plotjuggler-") + QString::number(rand()); + static QString uuid = QString("Plotjuggler-") + QString::number(rand()); QSettings settings; restoreGeometry(settings.value("MosquittoMQTT::geometry").toByteArray()); QString host = settings.value("MosquittoMQTT::host").toString(); - ui->lineEditHost->setText( host ); + ui->lineEditHost->setText(host); int port = settings.value("MosquittoMQTT::port", 1883).toInt(); - ui->lineEditPort->setText( QString::number(port) ); + ui->lineEditPort->setText(QString::number(port)); int qos = settings.value("MosquittoMQTT::qos", 0).toInt(); ui->comboBoxQoS->setCurrentIndex(qos); @@ -40,7 +38,7 @@ MQTT_Dialog::MQTT_Dialog(MQTTClient::Ptr mosq_client): ui->comboBoxVersion->setCurrentIndex(protocol_mqtt); QString topic_filter = settings.value("MosquittoMQTT::filter").toString(); - ui->lineEditTopicFilter->setText(topic_filter ); + ui->lineEditTopicFilter->setText(topic_filter); QString username = settings.value("MosquittoMQTT::username", "").toString(); ui->lineEditUsername->setText(username); @@ -48,22 +46,24 @@ MQTT_Dialog::MQTT_Dialog(MQTTClient::Ptr mosq_client): QString password = settings.value("MosquittoMQTT::password", "").toString(); ui->lineEditPassword->setText(password); - _server_certificate_file = settings.value("MosquittoMQTT::server_certificate", "").toString(); - if( !_server_certificate_file.isEmpty() ) + _server_certificate_file = + settings.value("MosquittoMQTT::server_certificate", "").toString(); + if (!_server_certificate_file.isEmpty()) { ui->labelServerCertificate->setText(QFileInfo(_server_certificate_file).fileName()); ui->buttonEraseServerCertificate->setEnabled(true); } - _client_certificate_file = settings.value("MosquittoMQTT::client_certificate", "").toString(); - if( !_client_certificate_file.isEmpty() ) + _client_certificate_file = + settings.value("MosquittoMQTT::client_certificate", "").toString(); + if (!_client_certificate_file.isEmpty()) { ui->labelClientCertificate->setText(QFileInfo(_client_certificate_file).fileName()); ui->buttonEraseClientCertificate->setEnabled(true); } _private_key_file = settings.value("MosquittoMQTT::private_key", "").toString(); - if( !_private_key_file.isEmpty() ) + if (!_private_key_file.isEmpty()) { ui->labelPrivateKey->setText(QFileInfo(_private_key_file).fileName()); ui->buttonErasePrivateKey->setEnabled(true); @@ -76,56 +76,50 @@ MQTT_Dialog::MQTT_Dialog(MQTTClient::Ptr mosq_client): QString theme = settings.value("StyleSheet::theme", "light").toString(); - const QPixmap &icon_pixmap = LoadSvg(":/resources/svg/import.svg", theme); + const QPixmap& icon_pixmap = LoadSvg(":/resources/svg/import.svg", theme); ui->buttonLoadServerCertificate->setIcon(icon_pixmap); ui->buttonLoadClientCertificate->setIcon(icon_pixmap); ui->buttonLoadPrivateKey->setIcon(icon_pixmap); - connect(ui->buttonConnect, &QPushButton::clicked, - this, &MQTT_Dialog::onButtonConnect); - - connect(_topic_list_timer, &QTimer::timeout, - this, &MQTT_Dialog::onUpdateTopicList); - - connect(ui->listWidget, &QListWidget::itemSelectionChanged, - this, &MQTT_Dialog::onSelectionChanged); - - connect(ui->buttonLoadServerCertificate, &QPushButton::clicked, - this, &MQTT_Dialog::onLoadServerCertificate); - - connect(ui->buttonLoadClientCertificate, &QPushButton::clicked, - this, &MQTT_Dialog::onLoadClientCertificate); - - connect(ui->buttonLoadPrivateKey, &QPushButton::clicked, - this, &MQTT_Dialog::onLoadPrivateKey); - - connect(ui->buttonEraseServerCertificate, &QPushButton::clicked, - this, [this](){ - ui->buttonEraseServerCertificate->setEnabled(false); - ui->labelServerCertificate->setText(""); - _server_certificate_file.clear(); - }); - - connect(ui->buttonEraseClientCertificate, &QPushButton::clicked, - this, [this](){ - ui->buttonEraseClientCertificate->setEnabled(false); - ui->labelClientCertificate->setText(""); - _client_certificate_file.clear(); - }); - - connect(ui->buttonErasePrivateKey, &QPushButton::clicked, - this, [this](){ - ui->buttonErasePrivateKey->setEnabled(false); - ui->labelPrivateKey->setText(""); - _private_key_file.clear(); - }); - - connect(_client.get(), &MQTTClient::disconnected, this, - [this]() { - onConnectionClosed(); - QMessageBox::warning(this, "Connection Lost", - "Client disconnected. Maybe a problem with autentication?"); - }); + connect(ui->buttonConnect, &QPushButton::clicked, this, &MQTT_Dialog::onButtonConnect); + + connect(_topic_list_timer, &QTimer::timeout, this, &MQTT_Dialog::onUpdateTopicList); + + connect(ui->listWidget, &QListWidget::itemSelectionChanged, this, + &MQTT_Dialog::onSelectionChanged); + + connect(ui->buttonLoadServerCertificate, &QPushButton::clicked, this, + &MQTT_Dialog::onLoadServerCertificate); + + connect(ui->buttonLoadClientCertificate, &QPushButton::clicked, this, + &MQTT_Dialog::onLoadClientCertificate); + + connect(ui->buttonLoadPrivateKey, &QPushButton::clicked, this, + &MQTT_Dialog::onLoadPrivateKey); + + connect(ui->buttonEraseServerCertificate, &QPushButton::clicked, this, [this]() { + ui->buttonEraseServerCertificate->setEnabled(false); + ui->labelServerCertificate->setText(""); + _server_certificate_file.clear(); + }); + + connect(ui->buttonEraseClientCertificate, &QPushButton::clicked, this, [this]() { + ui->buttonEraseClientCertificate->setEnabled(false); + ui->labelClientCertificate->setText(""); + _client_certificate_file.clear(); + }); + + connect(ui->buttonErasePrivateKey, &QPushButton::clicked, this, [this]() { + ui->buttonErasePrivateKey->setEnabled(false); + ui->labelPrivateKey->setText(""); + _private_key_file.clear(); + }); + + connect(_client.get(), &MQTTClient::disconnected, this, [this]() { + onConnectionClosed(); + QMessageBox::warning(this, "Connection Lost", + "Client disconnected. Maybe a problem with autentication?"); + }); } void MQTT_Dialog::saveSettings() @@ -139,9 +133,11 @@ void MQTT_Dialog::saveSettings() settings.setValue("MosquittoMQTT::filter", ui->lineEditTopicFilter->text()); settings.setValue("MosquittoMQTT::username", ui->lineEditPassword->text()); settings.setValue("MosquittoMQTT::password", ui->lineEditUsername->text()); - settings.setValue("MosquittoMQTT::protocol_version", ui->comboBoxVersion->currentIndex()); + settings.setValue("MosquittoMQTT::protocol_version", + ui->comboBoxVersion->currentIndex()); settings.setValue("MosquittoMQTT::qos", ui->comboBoxQoS->currentIndex()); - settings.setValue("MosquittoMQTT::serialization_protocol", ui->comboBoxProtocol->currentText()); + settings.setValue("MosquittoMQTT::serialization_protocol", + ui->comboBoxProtocol->currentText()); settings.setValue("MosquittoMQTT::server_certificate", _server_certificate_file); settings.setValue("MosquittoMQTT::client_certificate", _client_certificate_file); settings.setValue("MosquittoMQTT::private_key", _private_key_file); @@ -150,7 +146,7 @@ void MQTT_Dialog::saveSettings() MQTT_Dialog::~MQTT_Dialog() { - while( ui->layoutOptions->count() > 0) + while (ui->layoutOptions->count() > 0) { auto item = ui->layoutOptions->takeAt(0); item->widget()->setParent(nullptr); @@ -163,7 +159,7 @@ MQTT_Dialog::~MQTT_Dialog() void MQTT_Dialog::onButtonConnect() { - if( _client->isConnected() ) + if (_client->isConnected()) { onConnectionClosed(); return; @@ -178,16 +174,15 @@ void MQTT_Dialog::onButtonConnect() config.username = ui->lineEditUsername->text().toStdString(); config.password = ui->lineEditPassword->text().toStdString(); config.qos = ui->comboBoxQoS->currentIndex(); - config.protocol_version = - MQTT_PROTOCOL_V31 + ui->comboBoxVersion->currentIndex(); + config.protocol_version = MQTT_PROTOCOL_V31 + ui->comboBoxVersion->currentIndex(); - config.keepalive = 60; // TODO - config.bind_address = ""; //TODO - config.max_inflight = 20; //TODO - config.clean_session = true; //TODO - config.eol = true; //TODO + config.keepalive = 60; // TODO + config.bind_address = ""; // TODO + config.max_inflight = 20; // TODO + config.clean_session = true; // TODO + config.eol = true; // TODO - if( ui->checkBoxSecurity->isChecked() ) + if (ui->checkBoxSecurity->isChecked()) { config.cafile = _server_certificate_file.toStdString(); config.certfile = _client_certificate_file.toStdString(); @@ -206,11 +201,11 @@ void MQTT_Dialog::onUpdateTopicList() auto topic_list = _client->getTopicList(); bool changed = ui->listWidget->count() != topic_list.size(); - if( !changed ) + if (!changed) { - for(const auto& topic: topic_list) + for (const auto& topic : topic_list) { - if( _topic_list.count(topic) == 0 ) + if (_topic_list.count(topic) == 0) { changed = true; break; @@ -218,18 +213,18 @@ void MQTT_Dialog::onUpdateTopicList() } } - if( changed ) + if (changed) { ui->listWidget->clear(); - for(const auto& topic: topic_list) + for (const auto& topic : topic_list) { - ui->listWidget->addItem( QString::fromStdString(topic) ); + ui->listWidget->addItem(QString::fromStdString(topic)); _topic_list.insert(topic); } ui->listWidget->sortItems(); } - if( _client->isConnected() == false ) + if (_client->isConnected() == false) { onConnectionClosed(); } @@ -238,13 +233,13 @@ void MQTT_Dialog::onUpdateTopicList() void MQTT_Dialog::onSelectionChanged() { bool selected = ui->listWidget->selectedItems().count() > 0; - ui->buttonBox->button( QDialogButtonBox::Ok )->setEnabled( selected ); + ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(selected); } void MQTT_Dialog::changeConnectionState(bool connected) { ui->connectionFrame->setEnabled(!connected); - ui->buttonConnect->setText( connected ? "Disconnect" : "Connect"); + ui->buttonConnect->setText(connected ? "Disconnect" : "Connect"); ui->lineEditTopicFilter->setEnabled(!connected); ui->listWidget->setEnabled(connected); } @@ -252,13 +247,13 @@ void MQTT_Dialog::changeConnectionState(bool connected) void MQTT_Dialog::onLoadServerCertificate() { QSettings settings; - QString directory = settings.value("MQTT_Dialog.loadDirectory", - QDir::currentPath()).toString(); + QString directory = + settings.value("MQTT_Dialog.loadDirectory", QDir::currentPath()).toString(); - QString filename = QFileDialog::getOpenFileName( - this, "Select Server Certificate", directory,tr("CRT (*.crt)") ); + QString filename = QFileDialog::getOpenFileName(this, "Select Server Certificate", + directory, tr("CRT (*.crt)")); - if( !filename.isEmpty() ) + if (!filename.isEmpty()) { _server_certificate_file = filename; directory = QFileInfo(filename).absolutePath(); @@ -272,13 +267,13 @@ void MQTT_Dialog::onLoadServerCertificate() void MQTT_Dialog::onLoadClientCertificate() { QSettings settings; - QString directory = settings.value("MQTT_Dialog.loadDirectory", - QDir::currentPath()).toString(); + QString directory = + settings.value("MQTT_Dialog.loadDirectory", QDir::currentPath()).toString(); - QString filename = QFileDialog::getOpenFileName( - this, "Select Client Certificate", directory,tr("CRT (*.crt)") ); + QString filename = QFileDialog::getOpenFileName(this, "Select Client Certificate", + directory, tr("CRT (*.crt)")); - if( !filename.isEmpty() ) + if (!filename.isEmpty()) { _client_certificate_file = filename; directory = QFileInfo(filename).absolutePath(); @@ -292,13 +287,13 @@ void MQTT_Dialog::onLoadClientCertificate() void MQTT_Dialog::onLoadPrivateKey() { QSettings settings; - QString directory = settings.value("MQTT_Dialog.loadDirectory", - QDir::currentPath()).toString(); + QString directory = + settings.value("MQTT_Dialog.loadDirectory", QDir::currentPath()).toString(); - QString filename = QFileDialog::getOpenFileName( - this, "Select PrivateKey", directory,tr("Key (*.key)") ); + QString filename = QFileDialog::getOpenFileName(this, "Select PrivateKey", directory, + tr("Key (*.key)")); - if( !filename.isEmpty() ) + if (!filename.isEmpty()) { _private_key_file = filename; directory = QFileInfo(filename).absolutePath(); diff --git a/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.h b/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.h index 832fe564b..693f29b46 100644 --- a/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.h +++ b/plotjuggler_plugins/DataStreamMQTT/mqtt_dialog.h @@ -9,7 +9,7 @@ #include #include -class MQTT_Dialog: public QDialog +class MQTT_Dialog : public QDialog { public: MQTT_Dialog(MQTTClient::Ptr mosq_client); @@ -29,10 +29,9 @@ public slots: void onSelectionChanged(); private: - MQTTClient::Ptr _client; - QTimer *_topic_list_timer; + QTimer* _topic_list_timer; void changeConnectionState(bool connected); @@ -53,4 +52,4 @@ private slots: std::unordered_set _topic_list; }; -#endif // MQTT_DIALOG_H +#endif // MQTT_DIALOG_H diff --git a/plotjuggler_plugins/DataStreamUDP/udp_server.cpp b/plotjuggler_plugins/DataStreamUDP/udp_server.cpp index 415fda7c0..181b873d3 100644 --- a/plotjuggler_plugins/DataStreamUDP/udp_server.cpp +++ b/plotjuggler_plugins/DataStreamUDP/udp_server.cpp @@ -107,11 +107,11 @@ bool UDP_Server::start(QStringList*) ParserFactoryPlugin::Ptr parser_creator; connect(dialog.ui->comboBoxProtocol, - qOverload(&QComboBox::currentIndexChanged), - this, [&](const QString & selected_protocol) { + qOverload(&QComboBox::currentIndexChanged), this, + [&](const QString& selected_protocol) { if (parser_creator) { - if( auto prev_widget = parser_creator->optionsWidget()) + if (auto prev_widget = parser_creator->optionsWidget()) { prev_widget->setVisible(false); } diff --git a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp index 90a432920..9ca4bed70 100644 --- a/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp +++ b/plotjuggler_plugins/DataStreamWebsocket/websocket_server.cpp @@ -106,11 +106,11 @@ bool WebsocketServer::start(QStringList*) ParserFactoryPlugin::Ptr parser_creator; connect(dialog->ui->comboBoxProtocol, - qOverload(&QComboBox::currentIndexChanged), - this, [&](const QString & selected_protocol) { + qOverload(&QComboBox::currentIndexChanged), this, + [&](const QString& selected_protocol) { if (parser_creator) { - if( auto prev_widget = parser_creator->optionsWidget()) + if (auto prev_widget = parser_creator->optionsWidget()) { prev_widget->setVisible(false); } diff --git a/plotjuggler_plugins/DataStreamZMQ/zmq.hpp b/plotjuggler_plugins/DataStreamZMQ/zmq.hpp index fac00fc6c..cdd5aa46b 100644 --- a/plotjuggler_plugins/DataStreamZMQ/zmq.hpp +++ b/plotjuggler_plugins/DataStreamZMQ/zmq.hpp @@ -146,13 +146,12 @@ #define CPPZMQ_VERSION_MINOR 8 #define CPPZMQ_VERSION_PATCH 0 -#define CPPZMQ_VERSION \ - ZMQ_MAKE_VERSION(CPPZMQ_VERSION_MAJOR, CPPZMQ_VERSION_MINOR, \ - CPPZMQ_VERSION_PATCH) +#define CPPZMQ_VERSION \ + ZMQ_MAKE_VERSION(CPPZMQ_VERSION_MAJOR, CPPZMQ_VERSION_MINOR, CPPZMQ_VERSION_PATCH) // Detect whether the compiler supports C++11 rvalue references. -#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 2)) \ - && defined(__GXX_EXPERIMENTAL_CXX0X__)) +#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 2)) && \ + defined(__GXX_EXPERIMENTAL_CXX0X__)) #define ZMQ_HAS_RVALUE_REFS #define ZMQ_DELETED_FUNCTION = delete #elif defined(__clang__) @@ -175,12 +174,12 @@ #define ZMQ_DELETED_FUNCTION #endif -#if defined(ZMQ_CPP11) && !defined(__llvm__) && !defined(__INTEL_COMPILER) \ - && defined(__GNUC__) && __GNUC__ < 5 +#if defined(ZMQ_CPP11) && !defined(__llvm__) && !defined(__INTEL_COMPILER) && \ + defined(__GNUC__) && __GNUC__ < 5 #define ZMQ_CPP11_PARTIAL #elif defined(__GLIBCXX__) && __GLIBCXX__ < 20160805 -//the date here is the last date of gcc 4.9.4, which -// effectively means libstdc++ from gcc 5.5 and higher won't trigger this branch +// the date here is the last date of gcc 4.9.4, which +// effectively means libstdc++ from gcc 5.5 and higher won't trigger this branch #define ZMQ_CPP11_PARTIAL #endif @@ -202,8 +201,8 @@ /* Socket event data */ typedef struct { - uint16_t event; // id of the event as bitfield - int32_t value; // value is either error code, fd or reconnect interval + uint16_t event; // id of the event as bitfield + int32_t value; // value is either error code, fd or reconnect interval } zmq_event_t; #endif @@ -212,13 +211,12 @@ typedef struct #define zmq_msg_recv(msg, socket, flags) zmq_recvmsg(socket, msg, flags) #endif - // In order to prevent unused variable warnings when building in non-debug // mode use this macro to make assertions. #ifndef NDEBUG #define ZMQ_ASSERT(expression) assert(expression) #else -#define ZMQ_ASSERT(expression) (void) (expression) +#define ZMQ_ASSERT(expression) (void)(expression) #endif namespace zmq @@ -230,42 +228,47 @@ namespace ranges { using std::begin; using std::end; -template auto begin(T &&r) -> decltype(begin(std::forward(r))) +template +auto begin(T&& r) -> decltype(begin(std::forward(r))) { - return begin(std::forward(r)); + return begin(std::forward(r)); } -template auto end(T &&r) -> decltype(end(std::forward(r))) +template +auto end(T&& r) -> decltype(end(std::forward(r))) { - return end(std::forward(r)); + return end(std::forward(r)); } -} // namespace ranges +} // namespace ranges -template using void_t = void; +template +using void_t = void; -template +template using iter_value_t = typename std::iterator_traits::value_type; -template -using range_iter_t = decltype( - ranges::begin(std::declval::type &>())); +template +using range_iter_t = + decltype(ranges::begin(std::declval::type&>())); -template using range_value_t = iter_value_t>; +template +using range_value_t = iter_value_t>; -template struct is_range : std::false_type +template +struct is_range : std::false_type { }; -template +template struct is_range< - T, - void_t::type &>()) - == ranges::end(std::declval::type &>()))>> - : std::true_type + T, void_t::type&>()) == + ranges::end( + std::declval::type&>()))>> + : std::true_type { }; -} // namespace detail +} // namespace detail #endif typedef zmq_free_fn free_fn; @@ -273,626 +276,685 @@ typedef zmq_pollitem_t pollitem_t; class error_t : public std::exception { - public: - error_t() ZMQ_NOTHROW : errnum(zmq_errno()) {} - explicit error_t(int err) ZMQ_NOTHROW : errnum(err) {} - virtual const char *what() const ZMQ_NOTHROW ZMQ_OVERRIDE - { - return zmq_strerror(errnum); - } - int num() const ZMQ_NOTHROW { return errnum; } - - private: - int errnum; +public: + error_t() ZMQ_NOTHROW : errnum(zmq_errno()) + { + } + explicit error_t(int err) ZMQ_NOTHROW : errnum(err) + { + } + virtual const char* what() const ZMQ_NOTHROW ZMQ_OVERRIDE + { + return zmq_strerror(errnum); + } + int num() const ZMQ_NOTHROW + { + return errnum; + } + +private: + int errnum; }; -inline int poll(zmq_pollitem_t *items_, size_t nitems_, long timeout_ = -1) +inline int poll(zmq_pollitem_t* items_, size_t nitems_, long timeout_ = -1) { - int rc = zmq_poll(items_, static_cast(nitems_), timeout_); - if (rc < 0) - throw error_t(); - return rc; + int rc = zmq_poll(items_, static_cast(nitems_), timeout_); + if (rc < 0) + throw error_t(); + return rc; } ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items") -inline int poll(zmq_pollitem_t const *items_, size_t nitems_, long timeout_ = -1) +inline int poll(zmq_pollitem_t const* items_, size_t nitems_, long timeout_ = -1) { - return poll(const_cast(items_), nitems_, timeout_); + return poll(const_cast(items_), nitems_, timeout_); } #ifdef ZMQ_CPP11 ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items") -inline int -poll(zmq_pollitem_t const *items, size_t nitems, std::chrono::milliseconds timeout) +inline int poll(zmq_pollitem_t const* items, size_t nitems, + std::chrono::milliseconds timeout) { - return poll(const_cast(items), nitems, - static_cast(timeout.count())); + return poll(const_cast(items), nitems, + static_cast(timeout.count())); } ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items") -inline int poll(std::vector const &items, +inline int poll(std::vector const& items, std::chrono::milliseconds timeout) { - return poll(const_cast(items.data()), items.size(), - static_cast(timeout.count())); + return poll(const_cast(items.data()), items.size(), + static_cast(timeout.count())); } ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items") -inline int poll(std::vector const &items, long timeout_ = -1) +inline int poll(std::vector const& items, long timeout_ = -1) { - return poll(const_cast(items.data()), items.size(), timeout_); + return poll(const_cast(items.data()), items.size(), timeout_); } -inline int -poll(zmq_pollitem_t *items, size_t nitems, std::chrono::milliseconds timeout) +inline int poll(zmq_pollitem_t* items, size_t nitems, std::chrono::milliseconds timeout) { - return poll(items, nitems, static_cast(timeout.count())); + return poll(items, nitems, static_cast(timeout.count())); } -inline int poll(std::vector &items, - std::chrono::milliseconds timeout) +inline int poll(std::vector& items, std::chrono::milliseconds timeout) { - return poll(items.data(), items.size(), static_cast(timeout.count())); + return poll(items.data(), items.size(), static_cast(timeout.count())); } ZMQ_DEPRECATED("from 4.3.1, use poll taking std::chrono instead of long") -inline int poll(std::vector &items, long timeout_ = -1) +inline int poll(std::vector& items, long timeout_ = -1) { - return poll(items.data(), items.size(), timeout_); + return poll(items.data(), items.size(), timeout_); } -template -inline int poll(std::array &items, +template +inline int poll(std::array& items, std::chrono::milliseconds timeout) { - return poll(items.data(), items.size(), static_cast(timeout.count())); + return poll(items.data(), items.size(), static_cast(timeout.count())); } #endif - -inline void version(int *major_, int *minor_, int *patch_) +inline void version(int* major_, int* minor_, int* patch_) { - zmq_version(major_, minor_, patch_); + zmq_version(major_, minor_, patch_); } #ifdef ZMQ_CPP11 inline std::tuple version() { - std::tuple v; - zmq_version(&std::get<0>(v), &std::get<1>(v), &std::get<2>(v)); - return v; + std::tuple v; + zmq_version(&std::get<0>(v), &std::get<1>(v), &std::get<2>(v)); + return v; } #if !defined(ZMQ_CPP11_PARTIAL) namespace detail { -template struct is_char_type +template +struct is_char_type { - // true if character type for string literals in C++11 - static constexpr bool value = - std::is_same::value || std::is_same::value - || std::is_same::value || std::is_same::value; + // true if character type for string literals in C++11 + static constexpr bool value = + std::is_same::value || std::is_same::value || + std::is_same::value || std::is_same::value; }; -} +} // namespace detail #endif #endif class message_t { - public: - message_t() ZMQ_NOTHROW - { - int rc = zmq_msg_init(&msg); - ZMQ_ASSERT(rc == 0); - } - - explicit message_t(size_t size_) - { - int rc = zmq_msg_init_size(&msg, size_); - if (rc != 0) - throw error_t(); - } +public: + message_t() ZMQ_NOTHROW + { + int rc = zmq_msg_init(&msg); + ZMQ_ASSERT(rc == 0); + } - template message_t(ForwardIter first, ForwardIter last) - { - typedef typename std::iterator_traits::value_type value_t; - - assert(std::distance(first, last) >= 0); - size_t const size_ = - static_cast(std::distance(first, last)) * sizeof(value_t); - int const rc = zmq_msg_init_size(&msg, size_); - if (rc != 0) - throw error_t(); - std::copy(first, last, data()); - } + explicit message_t(size_t size_) + { + int rc = zmq_msg_init_size(&msg, size_); + if (rc != 0) + throw error_t(); + } + + template + message_t(ForwardIter first, ForwardIter last) + { + typedef typename std::iterator_traits::value_type value_t; + + assert(std::distance(first, last) >= 0); + size_t const size_ = + static_cast(std::distance(first, last)) * sizeof(value_t); + int const rc = zmq_msg_init_size(&msg, size_); + if (rc != 0) + throw error_t(); + std::copy(first, last, data()); + } - message_t(const void *data_, size_t size_) + message_t(const void* data_, size_t size_) + { + int rc = zmq_msg_init_size(&msg, size_); + if (rc != 0) + throw error_t(); + if (size_) { - int rc = zmq_msg_init_size(&msg, size_); - if (rc != 0) - throw error_t(); - if (size_) { - // this constructor allows (nullptr, 0), - // memcpy with a null pointer is UB - memcpy(data(), data_, size_); - } + // this constructor allows (nullptr, 0), + // memcpy with a null pointer is UB + memcpy(data(), data_, size_); } + } - message_t(void *data_, size_t size_, free_fn *ffn_, void *hint_ = ZMQ_NULLPTR) - { - int rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_); - if (rc != 0) - throw error_t(); - } + message_t(void* data_, size_t size_, free_fn* ffn_, void* hint_ = ZMQ_NULLPTR) + { + int rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_); + if (rc != 0) + throw error_t(); + } - // overload set of string-like types and generic containers + // overload set of string-like types and generic containers #if defined(ZMQ_CPP11) && !defined(ZMQ_CPP11_PARTIAL) - // NOTE this constructor will include the null terminator - // when called with a string literal. - // An overload taking const char* can not be added because - // it would be preferred over this function and break compatiblity. - template< - class Char, - size_t N, - typename = typename std::enable_if::value>::type> - ZMQ_DEPRECATED("from 4.7.0, use constructors taking iterators, (pointer, size) " - "or strings instead") - explicit message_t(const Char (&data)[N]) : - message_t(detail::ranges::begin(data), detail::ranges::end(data)) - { - } - - template::value - && ZMQ_IS_TRIVIALLY_COPYABLE(detail::range_value_t) - && !detail::is_char_type>::value - && !std::is_same::value>::type> - explicit message_t(const Range &rng) : - message_t(detail::ranges::begin(rng), detail::ranges::end(rng)) - { - } - - explicit message_t(const std::string &str) : message_t(str.data(), str.size()) {} + // NOTE this constructor will include the null terminator + // when called with a string literal. + // An overload taking const char* can not be added because + // it would be preferred over this function and break compatiblity. + template ::value>::type> + ZMQ_DEPRECATED("from 4.7.0, use constructors taking iterators, (pointer, size) " + "or strings instead") + explicit message_t(const Char (&data)[N]) + : message_t(detail::ranges::begin(data), detail::ranges::end(data)) + { + } + + template ::value && + ZMQ_IS_TRIVIALLY_COPYABLE(detail::range_value_t) && + !detail::is_char_type>::value && + !std::is_same::value>::type> + explicit message_t(const Range& rng) + : message_t(detail::ranges::begin(rng), detail::ranges::end(rng)) + { + } + + explicit message_t(const std::string& str) : message_t(str.data(), str.size()) + { + } #if CPPZMQ_HAS_STRING_VIEW - explicit message_t(std::string_view str) : message_t(str.data(), str.size()) {} + explicit message_t(std::string_view str) : message_t(str.data(), str.size()) + { + } #endif #endif #ifdef ZMQ_HAS_RVALUE_REFS - message_t(message_t &&rhs) ZMQ_NOTHROW : msg(rhs.msg) - { - int rc = zmq_msg_init(&rhs.msg); - ZMQ_ASSERT(rc == 0); - } - - message_t &operator=(message_t &&rhs) ZMQ_NOTHROW - { - std::swap(msg, rhs.msg); - return *this; - } -#endif - - ~message_t() ZMQ_NOTHROW - { - int rc = zmq_msg_close(&msg); - ZMQ_ASSERT(rc == 0); - } - - void rebuild() - { - int rc = zmq_msg_close(&msg); - if (rc != 0) - throw error_t(); - rc = zmq_msg_init(&msg); - ZMQ_ASSERT(rc == 0); - } - - void rebuild(size_t size_) - { - int rc = zmq_msg_close(&msg); - if (rc != 0) - throw error_t(); - rc = zmq_msg_init_size(&msg, size_); - if (rc != 0) - throw error_t(); - } - - void rebuild(const void *data_, size_t size_) - { - int rc = zmq_msg_close(&msg); - if (rc != 0) - throw error_t(); - rc = zmq_msg_init_size(&msg, size_); - if (rc != 0) - throw error_t(); - memcpy(data(), data_, size_); - } - - void rebuild(void *data_, size_t size_, free_fn *ffn_, void *hint_ = ZMQ_NULLPTR) - { - int rc = zmq_msg_close(&msg); - if (rc != 0) - throw error_t(); - rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_); - if (rc != 0) - throw error_t(); - } - - ZMQ_DEPRECATED("from 4.3.1, use move taking non-const reference instead") - void move(message_t const *msg_) - { - int rc = zmq_msg_move(&msg, const_cast(msg_->handle())); - if (rc != 0) - throw error_t(); - } - - void move(message_t &msg_) - { - int rc = zmq_msg_move(&msg, msg_.handle()); - if (rc != 0) - throw error_t(); - } - - ZMQ_DEPRECATED("from 4.3.1, use copy taking non-const reference instead") - void copy(message_t const *msg_) - { - int rc = zmq_msg_copy(&msg, const_cast(msg_->handle())); - if (rc != 0) - throw error_t(); - } - - void copy(message_t &msg_) - { - int rc = zmq_msg_copy(&msg, msg_.handle()); - if (rc != 0) - throw error_t(); - } - - bool more() const ZMQ_NOTHROW - { - int rc = zmq_msg_more(const_cast(&msg)); - return rc != 0; - } - - void *data() ZMQ_NOTHROW { return zmq_msg_data(&msg); } - - const void *data() const ZMQ_NOTHROW - { - return zmq_msg_data(const_cast(&msg)); - } - - size_t size() const ZMQ_NOTHROW - { - return zmq_msg_size(const_cast(&msg)); - } + message_t(message_t&& rhs) ZMQ_NOTHROW : msg(rhs.msg) + { + int rc = zmq_msg_init(&rhs.msg); + ZMQ_ASSERT(rc == 0); + } + + message_t& operator=(message_t&& rhs) ZMQ_NOTHROW + { + std::swap(msg, rhs.msg); + return *this; + } +#endif + + ~message_t() ZMQ_NOTHROW + { + int rc = zmq_msg_close(&msg); + ZMQ_ASSERT(rc == 0); + } + + void rebuild() + { + int rc = zmq_msg_close(&msg); + if (rc != 0) + throw error_t(); + rc = zmq_msg_init(&msg); + ZMQ_ASSERT(rc == 0); + } + + void rebuild(size_t size_) + { + int rc = zmq_msg_close(&msg); + if (rc != 0) + throw error_t(); + rc = zmq_msg_init_size(&msg, size_); + if (rc != 0) + throw error_t(); + } - ZMQ_NODISCARD bool empty() const ZMQ_NOTHROW { return size() == 0u; } + void rebuild(const void* data_, size_t size_) + { + int rc = zmq_msg_close(&msg); + if (rc != 0) + throw error_t(); + rc = zmq_msg_init_size(&msg, size_); + if (rc != 0) + throw error_t(); + memcpy(data(), data_, size_); + } - template T *data() ZMQ_NOTHROW { return static_cast(data()); } + void rebuild(void* data_, size_t size_, free_fn* ffn_, void* hint_ = ZMQ_NULLPTR) + { + int rc = zmq_msg_close(&msg); + if (rc != 0) + throw error_t(); + rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_); + if (rc != 0) + throw error_t(); + } - template T const *data() const ZMQ_NOTHROW - { - return static_cast(data()); - } + ZMQ_DEPRECATED("from 4.3.1, use move taking non-const reference instead") + void move(message_t const* msg_) + { + int rc = zmq_msg_move(&msg, const_cast(msg_->handle())); + if (rc != 0) + throw error_t(); + } - ZMQ_DEPRECATED("from 4.3.0, use operator== instead") - bool equal(const message_t *other) const ZMQ_NOTHROW { return *this == *other; } + void move(message_t& msg_) + { + int rc = zmq_msg_move(&msg, msg_.handle()); + if (rc != 0) + throw error_t(); + } - bool operator==(const message_t &other) const ZMQ_NOTHROW - { - const size_t my_size = size(); - return my_size == other.size() && 0 == memcmp(data(), other.data(), my_size); - } + ZMQ_DEPRECATED("from 4.3.1, use copy taking non-const reference instead") + void copy(message_t const* msg_) + { + int rc = zmq_msg_copy(&msg, const_cast(msg_->handle())); + if (rc != 0) + throw error_t(); + } - bool operator!=(const message_t &other) const ZMQ_NOTHROW - { - return !(*this == other); - } + void copy(message_t& msg_) + { + int rc = zmq_msg_copy(&msg, msg_.handle()); + if (rc != 0) + throw error_t(); + } + + bool more() const ZMQ_NOTHROW + { + int rc = zmq_msg_more(const_cast(&msg)); + return rc != 0; + } + + void* data() ZMQ_NOTHROW + { + return zmq_msg_data(&msg); + } + + const void* data() const ZMQ_NOTHROW + { + return zmq_msg_data(const_cast(&msg)); + } + + size_t size() const ZMQ_NOTHROW + { + return zmq_msg_size(const_cast(&msg)); + } + + ZMQ_NODISCARD bool empty() const ZMQ_NOTHROW + { + return size() == 0u; + } + + template + T* data() ZMQ_NOTHROW + { + return static_cast(data()); + } + + template + T const* data() const ZMQ_NOTHROW + { + return static_cast(data()); + } + + ZMQ_DEPRECATED("from 4.3.0, use operator== instead") + bool equal(const message_t* other) const ZMQ_NOTHROW + { + return *this == *other; + } + + bool operator==(const message_t& other) const ZMQ_NOTHROW + { + const size_t my_size = size(); + return my_size == other.size() && 0 == memcmp(data(), other.data(), my_size); + } + + bool operator!=(const message_t& other) const ZMQ_NOTHROW + { + return !(*this == other); + } #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3, 2, 0) - int get(int property_) - { - int value = zmq_msg_get(&msg, property_); - if (value == -1) - throw error_t(); - return value; - } + int get(int property_) + { + int value = zmq_msg_get(&msg, property_); + if (value == -1) + throw error_t(); + return value; + } #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 1, 0) - const char *gets(const char *property_) - { - const char *value = zmq_msg_gets(&msg, property_); - if (value == ZMQ_NULLPTR) - throw error_t(); - return value; - } + const char* gets(const char* property_) + { + const char* value = zmq_msg_gets(&msg, property_); + if (value == ZMQ_NULLPTR) + throw error_t(); + return value; + } #endif #if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0) - uint32_t routing_id() const - { - return zmq_msg_routing_id(const_cast(&msg)); - } - - void set_routing_id(uint32_t routing_id) - { - int rc = zmq_msg_set_routing_id(&msg, routing_id); - if (rc != 0) - throw error_t(); - } + uint32_t routing_id() const + { + return zmq_msg_routing_id(const_cast(&msg)); + } + + void set_routing_id(uint32_t routing_id) + { + int rc = zmq_msg_set_routing_id(&msg, routing_id); + if (rc != 0) + throw error_t(); + } - const char *group() const - { - return zmq_msg_group(const_cast(&msg)); - } + const char* group() const + { + return zmq_msg_group(const_cast(&msg)); + } - void set_group(const char *group) - { - int rc = zmq_msg_set_group(&msg, group); - if (rc != 0) - throw error_t(); - } + void set_group(const char* group) + { + int rc = zmq_msg_set_group(&msg, group); + if (rc != 0) + throw error_t(); + } #endif - // interpret message content as a string - std::string to_string() const - { - return std::string(static_cast(data()), size()); - } + // interpret message content as a string + std::string to_string() const + { + return std::string(static_cast(data()), size()); + } #if CPPZMQ_HAS_STRING_VIEW - // interpret message content as a string - std::string_view to_string_view() const noexcept - { - return std::string_view(static_cast(data()), size()); - } -#endif - - /** Dump content to string for debugging. - * Ascii chars are readable, the rest is printed as hex. - * Probably ridiculously slow. - * Use to_string() or to_string_view() for - * interpreting the message as a string. - */ - std::string str() const - { - // Partly mutuated from the same method in zmq::multipart_t - std::stringstream os; - - const unsigned char *msg_data = this->data(); - unsigned char byte; - size_t size = this->size(); - int is_ascii[2] = {0, 0}; - - os << "zmq::message_t [size " << std::dec << std::setw(3) - << std::setfill('0') << size << "] ("; - // Totally arbitrary - if (size >= 1000) { - os << "... too big to print)"; - } else { - while (size--) { - byte = *msg_data++; - - is_ascii[1] = (byte >= 32 && byte < 127); - if (is_ascii[1] != is_ascii[0]) - os << " "; // Separate text/non text - - if (is_ascii[1]) { - os << byte; - } else { - os << std::hex << std::uppercase << std::setw(2) - << std::setfill('0') << static_cast(byte); - } - is_ascii[0] = is_ascii[1]; - } - os << ")"; + // interpret message content as a string + std::string_view to_string_view() const noexcept + { + return std::string_view(static_cast(data()), size()); + } +#endif + + /** Dump content to string for debugging. + * Ascii chars are readable, the rest is printed as hex. + * Probably ridiculously slow. + * Use to_string() or to_string_view() for + * interpreting the message as a string. + */ + std::string str() const + { + // Partly mutuated from the same method in zmq::multipart_t + std::stringstream os; + + const unsigned char* msg_data = this->data(); + unsigned char byte; + size_t size = this->size(); + int is_ascii[2] = { 0, 0 }; + + os << "zmq::message_t [size " << std::dec << std::setw(3) << std::setfill('0') << size + << "] ("; + // Totally arbitrary + if (size >= 1000) + { + os << "... too big to print)"; + } + else + { + while (size--) + { + byte = *msg_data++; + + is_ascii[1] = (byte >= 32 && byte < 127); + if (is_ascii[1] != is_ascii[0]) + os << " "; // Separate text/non text + + if (is_ascii[1]) + { + os << byte; } - return os.str(); - } - - void swap(message_t &other) ZMQ_NOTHROW - { - // this assumes zmq::msg_t from libzmq is trivially relocatable - std::swap(msg, other.msg); - } - - ZMQ_NODISCARD zmq_msg_t *handle() ZMQ_NOTHROW { return &msg; } - ZMQ_NODISCARD const zmq_msg_t *handle() const ZMQ_NOTHROW { return &msg; } - - private: - // The underlying message - zmq_msg_t msg; - - // Disable implicit message copying, so that users won't use shared - // messages (less efficient) without being aware of the fact. - message_t(const message_t &) ZMQ_DELETED_FUNCTION; - void operator=(const message_t &) ZMQ_DELETED_FUNCTION; + else + { + os << std::hex << std::uppercase << std::setw(2) << std::setfill('0') + << static_cast(byte); + } + is_ascii[0] = is_ascii[1]; + } + os << ")"; + } + return os.str(); + } + + void swap(message_t& other) ZMQ_NOTHROW + { + // this assumes zmq::msg_t from libzmq is trivially relocatable + std::swap(msg, other.msg); + } + + ZMQ_NODISCARD zmq_msg_t* handle() ZMQ_NOTHROW + { + return &msg; + } + ZMQ_NODISCARD const zmq_msg_t* handle() const ZMQ_NOTHROW + { + return &msg; + } + +private: + // The underlying message + zmq_msg_t msg; + + // Disable implicit message copying, so that users won't use shared + // messages (less efficient) without being aware of the fact. + message_t(const message_t&) ZMQ_DELETED_FUNCTION; + void operator=(const message_t&) ZMQ_DELETED_FUNCTION; }; -inline void swap(message_t &a, message_t &b) ZMQ_NOTHROW +inline void swap(message_t& a, message_t& b) ZMQ_NOTHROW { - a.swap(b); + a.swap(b); } #ifdef ZMQ_CPP11 enum class ctxopt { #ifdef ZMQ_BLOCKY - blocky = ZMQ_BLOCKY, + blocky = ZMQ_BLOCKY, #endif #ifdef ZMQ_IO_THREADS - io_threads = ZMQ_IO_THREADS, + io_threads = ZMQ_IO_THREADS, #endif #ifdef ZMQ_THREAD_SCHED_POLICY - thread_sched_policy = ZMQ_THREAD_SCHED_POLICY, + thread_sched_policy = ZMQ_THREAD_SCHED_POLICY, #endif #ifdef ZMQ_THREAD_PRIORITY - thread_priority = ZMQ_THREAD_PRIORITY, + thread_priority = ZMQ_THREAD_PRIORITY, #endif #ifdef ZMQ_THREAD_AFFINITY_CPU_ADD - thread_affinity_cpu_add = ZMQ_THREAD_AFFINITY_CPU_ADD, + thread_affinity_cpu_add = ZMQ_THREAD_AFFINITY_CPU_ADD, #endif #ifdef ZMQ_THREAD_AFFINITY_CPU_REMOVE - thread_affinity_cpu_remove = ZMQ_THREAD_AFFINITY_CPU_REMOVE, + thread_affinity_cpu_remove = ZMQ_THREAD_AFFINITY_CPU_REMOVE, #endif #ifdef ZMQ_THREAD_NAME_PREFIX - thread_name_prefix = ZMQ_THREAD_NAME_PREFIX, + thread_name_prefix = ZMQ_THREAD_NAME_PREFIX, #endif #ifdef ZMQ_MAX_MSGSZ - max_msgsz = ZMQ_MAX_MSGSZ, + max_msgsz = ZMQ_MAX_MSGSZ, #endif #ifdef ZMQ_ZERO_COPY_RECV - zero_copy_recv = ZMQ_ZERO_COPY_RECV, + zero_copy_recv = ZMQ_ZERO_COPY_RECV, #endif #ifdef ZMQ_MAX_SOCKETS - max_sockets = ZMQ_MAX_SOCKETS, + max_sockets = ZMQ_MAX_SOCKETS, #endif #ifdef ZMQ_SOCKET_LIMIT - socket_limit = ZMQ_SOCKET_LIMIT, + socket_limit = ZMQ_SOCKET_LIMIT, #endif #ifdef ZMQ_IPV6 - ipv6 = ZMQ_IPV6, + ipv6 = ZMQ_IPV6, #endif #ifdef ZMQ_MSG_T_SIZE - msg_t_size = ZMQ_MSG_T_SIZE + msg_t_size = ZMQ_MSG_T_SIZE #endif }; #endif class context_t { - public: - context_t() - { - ptr = zmq_ctx_new(); - if (ptr == ZMQ_NULLPTR) - throw error_t(); - } +public: + context_t() + { + ptr = zmq_ctx_new(); + if (ptr == ZMQ_NULLPTR) + throw error_t(); + } + explicit context_t(int io_threads_, int max_sockets_ = ZMQ_MAX_SOCKETS_DFLT) + { + ptr = zmq_ctx_new(); + if (ptr == ZMQ_NULLPTR) + throw error_t(); - explicit context_t(int io_threads_, int max_sockets_ = ZMQ_MAX_SOCKETS_DFLT) - { - ptr = zmq_ctx_new(); - if (ptr == ZMQ_NULLPTR) - throw error_t(); + int rc = zmq_ctx_set(ptr, ZMQ_IO_THREADS, io_threads_); + ZMQ_ASSERT(rc == 0); - int rc = zmq_ctx_set(ptr, ZMQ_IO_THREADS, io_threads_); - ZMQ_ASSERT(rc == 0); - - rc = zmq_ctx_set(ptr, ZMQ_MAX_SOCKETS, max_sockets_); - ZMQ_ASSERT(rc == 0); - } + rc = zmq_ctx_set(ptr, ZMQ_MAX_SOCKETS, max_sockets_); + ZMQ_ASSERT(rc == 0); + } #ifdef ZMQ_HAS_RVALUE_REFS - context_t(context_t &&rhs) ZMQ_NOTHROW : ptr(rhs.ptr) { rhs.ptr = ZMQ_NULLPTR; } - context_t &operator=(context_t &&rhs) ZMQ_NOTHROW - { - close(); - std::swap(ptr, rhs.ptr); - return *this; - } -#endif - - ~context_t() ZMQ_NOTHROW { close(); } - - ZMQ_CPP11_DEPRECATED("from 4.7.0, use set taking zmq::ctxopt instead") - int setctxopt(int option_, int optval_) - { - int rc = zmq_ctx_set(ptr, option_, optval_); - ZMQ_ASSERT(rc == 0); - return rc; - } + context_t(context_t&& rhs) ZMQ_NOTHROW : ptr(rhs.ptr) + { + rhs.ptr = ZMQ_NULLPTR; + } + context_t& operator=(context_t&& rhs) ZMQ_NOTHROW + { + close(); + std::swap(ptr, rhs.ptr); + return *this; + } +#endif + + ~context_t() ZMQ_NOTHROW + { + close(); + } + + ZMQ_CPP11_DEPRECATED("from 4.7.0, use set taking zmq::ctxopt instead") + int setctxopt(int option_, int optval_) + { + int rc = zmq_ctx_set(ptr, option_, optval_); + ZMQ_ASSERT(rc == 0); + return rc; + } - ZMQ_CPP11_DEPRECATED("from 4.7.0, use get taking zmq::ctxopt instead") - int getctxopt(int option_) { return zmq_ctx_get(ptr, option_); } + ZMQ_CPP11_DEPRECATED("from 4.7.0, use get taking zmq::ctxopt instead") + int getctxopt(int option_) + { + return zmq_ctx_get(ptr, option_); + } #ifdef ZMQ_CPP11 - void set(ctxopt option, int optval) - { - int rc = zmq_ctx_set(ptr, static_cast(option), optval); - if (rc == -1) - throw error_t(); - } - - ZMQ_NODISCARD int get(ctxopt option) - { - int rc = zmq_ctx_get(ptr, static_cast(option)); - // some options have a default value of -1 - // which is unfortunate, and may result in errors - // that don't make sense - if (rc == -1) - throw error_t(); - return rc; - } -#endif - - // Terminates context (see also shutdown()). - void close() ZMQ_NOTHROW - { - if (ptr == ZMQ_NULLPTR) - return; - - int rc; - do { - rc = zmq_ctx_destroy(ptr); - } while (rc == -1 && errno == EINTR); - - ZMQ_ASSERT(rc == 0); - ptr = ZMQ_NULLPTR; - } - - // Shutdown context in preparation for termination (close()). - // Causes all blocking socket operations and any further - // socket operations to return with ETERM. - void shutdown() ZMQ_NOTHROW - { - if (ptr == ZMQ_NULLPTR) - return; - int rc = zmq_ctx_shutdown(ptr); - ZMQ_ASSERT(rc == 0); - } - - // Be careful with this, it's probably only useful for - // using the C api together with an existing C++ api. - // Normally you should never need to use this. - ZMQ_EXPLICIT operator void *() ZMQ_NOTHROW { return ptr; } - - ZMQ_EXPLICIT operator void const *() const ZMQ_NOTHROW { return ptr; } - - ZMQ_NODISCARD void *handle() ZMQ_NOTHROW { return ptr; } - - ZMQ_DEPRECATED("from 4.7.0, use handle() != nullptr instead") - operator bool() const ZMQ_NOTHROW { return ptr != ZMQ_NULLPTR; } - - void swap(context_t &other) ZMQ_NOTHROW { std::swap(ptr, other.ptr); } - - private: - void *ptr; - - context_t(const context_t &) ZMQ_DELETED_FUNCTION; - void operator=(const context_t &) ZMQ_DELETED_FUNCTION; + void set(ctxopt option, int optval) + { + int rc = zmq_ctx_set(ptr, static_cast(option), optval); + if (rc == -1) + throw error_t(); + } + + ZMQ_NODISCARD int get(ctxopt option) + { + int rc = zmq_ctx_get(ptr, static_cast(option)); + // some options have a default value of -1 + // which is unfortunate, and may result in errors + // that don't make sense + if (rc == -1) + throw error_t(); + return rc; + } +#endif + + // Terminates context (see also shutdown()). + void close() ZMQ_NOTHROW + { + if (ptr == ZMQ_NULLPTR) + return; + + int rc; + do + { + rc = zmq_ctx_destroy(ptr); + } while (rc == -1 && errno == EINTR); + + ZMQ_ASSERT(rc == 0); + ptr = ZMQ_NULLPTR; + } + + // Shutdown context in preparation for termination (close()). + // Causes all blocking socket operations and any further + // socket operations to return with ETERM. + void shutdown() ZMQ_NOTHROW + { + if (ptr == ZMQ_NULLPTR) + return; + int rc = zmq_ctx_shutdown(ptr); + ZMQ_ASSERT(rc == 0); + } + + // Be careful with this, it's probably only useful for + // using the C api together with an existing C++ api. + // Normally you should never need to use this. + ZMQ_EXPLICIT operator void*() ZMQ_NOTHROW + { + return ptr; + } + + ZMQ_EXPLICIT operator void const*() const ZMQ_NOTHROW + { + return ptr; + } + + ZMQ_NODISCARD void* handle() ZMQ_NOTHROW + { + return ptr; + } + + ZMQ_DEPRECATED("from 4.7.0, use handle() != nullptr instead") + operator bool() const ZMQ_NOTHROW + { + return ptr != ZMQ_NULLPTR; + } + + void swap(context_t& other) ZMQ_NOTHROW + { + std::swap(ptr, other.ptr); + } + +private: + void* ptr; + + context_t(const context_t&) ZMQ_DELETED_FUNCTION; + void operator=(const context_t&) ZMQ_DELETED_FUNCTION; }; -inline void swap(context_t &a, context_t &b) ZMQ_NOTHROW +inline void swap(context_t& a, context_t& b) ZMQ_NOTHROW { - a.swap(b); + a.swap(b); } #ifdef ZMQ_CPP11 struct recv_buffer_size { - size_t size; // number of bytes written to buffer - size_t untruncated_size; // untruncated message size in bytes + size_t size; // number of bytes written to buffer + size_t untruncated_size; // untruncated message size in bytes - ZMQ_NODISCARD bool truncated() const noexcept - { - return size != untruncated_size; - } + ZMQ_NODISCARD bool truncated() const noexcept + { + return size != untruncated_size; + } }; #if CPPZMQ_HAS_OPTIONAL @@ -907,58 +969,67 @@ namespace detail { // A C++11 type emulating the most basic // operations of std::optional for trivial types -template class trivial_optional -{ - public: - static_assert(std::is_trivial::value, "T must be trivial"); - using value_type = T; - - trivial_optional() = default; - trivial_optional(T value) noexcept : _value(value), _has_value(true) {} - - const T *operator->() const noexcept - { - assert(_has_value); - return &_value; - } - T *operator->() noexcept - { - assert(_has_value); - return &_value; - } - - const T &operator*() const noexcept - { - assert(_has_value); - return _value; - } - T &operator*() noexcept - { - assert(_has_value); - return _value; - } - - T &value() - { - if (!_has_value) - throw std::exception(); - return _value; - } - const T &value() const - { - if (!_has_value) - throw std::exception(); - return _value; - } - - explicit operator bool() const noexcept { return _has_value; } - bool has_value() const noexcept { return _has_value; } - - private: - T _value{}; - bool _has_value{false}; +template +class trivial_optional +{ +public: + static_assert(std::is_trivial::value, "T must be trivial"); + using value_type = T; + + trivial_optional() = default; + trivial_optional(T value) noexcept : _value(value), _has_value(true) + { + } + + const T* operator->() const noexcept + { + assert(_has_value); + return &_value; + } + T* operator->() noexcept + { + assert(_has_value); + return &_value; + } + + const T& operator*() const noexcept + { + assert(_has_value); + return _value; + } + T& operator*() noexcept + { + assert(_has_value); + return _value; + } + + T& value() + { + if (!_has_value) + throw std::exception(); + return _value; + } + const T& value() const + { + if (!_has_value) + throw std::exception(); + return _value; + } + + explicit operator bool() const noexcept + { + return _has_value; + } + bool has_value() const noexcept + { + return _has_value; + } + +private: + T _value{}; + bool _has_value{ false }; }; -} // namespace detail +} // namespace detail using send_result_t = detail::trivial_optional; using recv_result_t = detail::trivial_optional; @@ -968,389 +1039,412 @@ using recv_buffer_result_t = detail::trivial_optional; namespace detail { -template constexpr T enum_bit_or(T a, T b) noexcept +template +constexpr T enum_bit_or(T a, T b) noexcept { - static_assert(std::is_enum::value, "must be enum"); - using U = typename std::underlying_type::type; - return static_cast(static_cast(a) | static_cast(b)); + static_assert(std::is_enum::value, "must be enum"); + using U = typename std::underlying_type::type; + return static_cast(static_cast(a) | static_cast(b)); } -template constexpr T enum_bit_and(T a, T b) noexcept +template +constexpr T enum_bit_and(T a, T b) noexcept { - static_assert(std::is_enum::value, "must be enum"); - using U = typename std::underlying_type::type; - return static_cast(static_cast(a) & static_cast(b)); + static_assert(std::is_enum::value, "must be enum"); + using U = typename std::underlying_type::type; + return static_cast(static_cast(a) & static_cast(b)); } -template constexpr T enum_bit_xor(T a, T b) noexcept +template +constexpr T enum_bit_xor(T a, T b) noexcept { - static_assert(std::is_enum::value, "must be enum"); - using U = typename std::underlying_type::type; - return static_cast(static_cast(a) ^ static_cast(b)); + static_assert(std::is_enum::value, "must be enum"); + using U = typename std::underlying_type::type; + return static_cast(static_cast(a) ^ static_cast(b)); } -template constexpr T enum_bit_not(T a) noexcept +template +constexpr T enum_bit_not(T a) noexcept { - static_assert(std::is_enum::value, "must be enum"); - using U = typename std::underlying_type::type; - return static_cast(~static_cast(a)); + static_assert(std::is_enum::value, "must be enum"); + using U = typename std::underlying_type::type; + return static_cast(~static_cast(a)); } -} // namespace detail +} // namespace detail // partially satisfies named requirement BitmaskType enum class send_flags : int { - none = 0, - dontwait = ZMQ_DONTWAIT, - sndmore = ZMQ_SNDMORE + none = 0, + dontwait = ZMQ_DONTWAIT, + sndmore = ZMQ_SNDMORE }; constexpr send_flags operator|(send_flags a, send_flags b) noexcept { - return detail::enum_bit_or(a, b); + return detail::enum_bit_or(a, b); } constexpr send_flags operator&(send_flags a, send_flags b) noexcept { - return detail::enum_bit_and(a, b); + return detail::enum_bit_and(a, b); } constexpr send_flags operator^(send_flags a, send_flags b) noexcept { - return detail::enum_bit_xor(a, b); + return detail::enum_bit_xor(a, b); } constexpr send_flags operator~(send_flags a) noexcept { - return detail::enum_bit_not(a); + return detail::enum_bit_not(a); } // partially satisfies named requirement BitmaskType enum class recv_flags : int { - none = 0, - dontwait = ZMQ_DONTWAIT + none = 0, + dontwait = ZMQ_DONTWAIT }; constexpr recv_flags operator|(recv_flags a, recv_flags b) noexcept { - return detail::enum_bit_or(a, b); + return detail::enum_bit_or(a, b); } constexpr recv_flags operator&(recv_flags a, recv_flags b) noexcept { - return detail::enum_bit_and(a, b); + return detail::enum_bit_and(a, b); } constexpr recv_flags operator^(recv_flags a, recv_flags b) noexcept { - return detail::enum_bit_xor(a, b); + return detail::enum_bit_xor(a, b); } constexpr recv_flags operator~(recv_flags a) noexcept { - return detail::enum_bit_not(a); + return detail::enum_bit_not(a); } - // mutable_buffer, const_buffer and buffer are based on // the Networking TS specification, draft: // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4771.pdf class mutable_buffer { - public: - constexpr mutable_buffer() noexcept : _data(nullptr), _size(0) {} - constexpr mutable_buffer(void *p, size_t n) noexcept : _data(p), _size(n) - { +public: + constexpr mutable_buffer() noexcept : _data(nullptr), _size(0) + { + } + constexpr mutable_buffer(void* p, size_t n) noexcept : _data(p), _size(n) + { #ifdef ZMQ_EXTENDED_CONSTEXPR - assert(p != nullptr || n == 0); -#endif - } - - constexpr void *data() const noexcept { return _data; } - constexpr size_t size() const noexcept { return _size; } - mutable_buffer &operator+=(size_t n) noexcept - { - // (std::min) is a workaround for when a min macro is defined - const auto shift = (std::min)(n, _size); - _data = static_cast(_data) + shift; - _size -= shift; - return *this; - } - - private: - void *_data; - size_t _size; + assert(p != nullptr || n == 0); +#endif + } + + constexpr void* data() const noexcept + { + return _data; + } + constexpr size_t size() const noexcept + { + return _size; + } + mutable_buffer& operator+=(size_t n) noexcept + { + // (std::min) is a workaround for when a min macro is defined + const auto shift = (std::min)(n, _size); + _data = static_cast(_data) + shift; + _size -= shift; + return *this; + } + +private: + void* _data; + size_t _size; }; -inline mutable_buffer operator+(const mutable_buffer &mb, size_t n) noexcept +inline mutable_buffer operator+(const mutable_buffer& mb, size_t n) noexcept { - return mutable_buffer(static_cast(mb.data()) + (std::min)(n, mb.size()), - mb.size() - (std::min)(n, mb.size())); + return mutable_buffer(static_cast(mb.data()) + (std::min)(n, mb.size()), + mb.size() - (std::min)(n, mb.size())); } -inline mutable_buffer operator+(size_t n, const mutable_buffer &mb) noexcept +inline mutable_buffer operator+(size_t n, const mutable_buffer& mb) noexcept { - return mb + n; + return mb + n; } class const_buffer { - public: - constexpr const_buffer() noexcept : _data(nullptr), _size(0) {} - constexpr const_buffer(const void *p, size_t n) noexcept : _data(p), _size(n) - { +public: + constexpr const_buffer() noexcept : _data(nullptr), _size(0) + { + } + constexpr const_buffer(const void* p, size_t n) noexcept : _data(p), _size(n) + { #ifdef ZMQ_EXTENDED_CONSTEXPR - assert(p != nullptr || n == 0); -#endif - } - constexpr const_buffer(const mutable_buffer &mb) noexcept : - _data(mb.data()), _size(mb.size()) - { - } - - constexpr const void *data() const noexcept { return _data; } - constexpr size_t size() const noexcept { return _size; } - const_buffer &operator+=(size_t n) noexcept - { - const auto shift = (std::min)(n, _size); - _data = static_cast(_data) + shift; - _size -= shift; - return *this; - } - - private: - const void *_data; - size_t _size; + assert(p != nullptr || n == 0); +#endif + } + constexpr const_buffer(const mutable_buffer& mb) noexcept + : _data(mb.data()), _size(mb.size()) + { + } + + constexpr const void* data() const noexcept + { + return _data; + } + constexpr size_t size() const noexcept + { + return _size; + } + const_buffer& operator+=(size_t n) noexcept + { + const auto shift = (std::min)(n, _size); + _data = static_cast(_data) + shift; + _size -= shift; + return *this; + } + +private: + const void* _data; + size_t _size; }; -inline const_buffer operator+(const const_buffer &cb, size_t n) noexcept +inline const_buffer operator+(const const_buffer& cb, size_t n) noexcept { - return const_buffer(static_cast(cb.data()) - + (std::min)(n, cb.size()), - cb.size() - (std::min)(n, cb.size())); + return const_buffer(static_cast(cb.data()) + (std::min)(n, cb.size()), + cb.size() - (std::min)(n, cb.size())); } -inline const_buffer operator+(size_t n, const const_buffer &cb) noexcept +inline const_buffer operator+(size_t n, const const_buffer& cb) noexcept { - return cb + n; + return cb + n; } // buffer creation -constexpr mutable_buffer buffer(void *p, size_t n) noexcept +constexpr mutable_buffer buffer(void* p, size_t n) noexcept { - return mutable_buffer(p, n); + return mutable_buffer(p, n); } -constexpr const_buffer buffer(const void *p, size_t n) noexcept +constexpr const_buffer buffer(const void* p, size_t n) noexcept { - return const_buffer(p, n); + return const_buffer(p, n); } -constexpr mutable_buffer buffer(const mutable_buffer &mb) noexcept +constexpr mutable_buffer buffer(const mutable_buffer& mb) noexcept { - return mb; + return mb; } -inline mutable_buffer buffer(const mutable_buffer &mb, size_t n) noexcept +inline mutable_buffer buffer(const mutable_buffer& mb, size_t n) noexcept { - return mutable_buffer(mb.data(), (std::min)(mb.size(), n)); + return mutable_buffer(mb.data(), (std::min)(mb.size(), n)); } -constexpr const_buffer buffer(const const_buffer &cb) noexcept +constexpr const_buffer buffer(const const_buffer& cb) noexcept { - return cb; + return cb; } -inline const_buffer buffer(const const_buffer &cb, size_t n) noexcept +inline const_buffer buffer(const const_buffer& cb, size_t n) noexcept { - return const_buffer(cb.data(), (std::min)(cb.size(), n)); + return const_buffer(cb.data(), (std::min)(cb.size(), n)); } namespace detail { -template struct is_buffer +template +struct is_buffer { - static constexpr bool value = + static constexpr bool value = std::is_same::value || std::is_same::value; }; -template struct is_pod_like +template +struct is_pod_like { - // NOTE: The networking draft N4771 section 16.11 requires - // T in the buffer functions below to be - // trivially copyable OR standard layout. - // Here we decide to be conservative and require both. - static constexpr bool value = + // NOTE: The networking draft N4771 section 16.11 requires + // T in the buffer functions below to be + // trivially copyable OR standard layout. + // Here we decide to be conservative and require both. + static constexpr bool value = ZMQ_IS_TRIVIALLY_COPYABLE(T) && std::is_standard_layout::value; }; -template constexpr auto seq_size(const C &c) noexcept -> decltype(c.size()) +template +constexpr auto seq_size(const C& c) noexcept -> decltype(c.size()) { - return c.size(); + return c.size(); } -template +template constexpr size_t seq_size(const T (&/*array*/)[N]) noexcept { - return N; + return N; } -template -auto buffer_contiguous_sequence(Seq &&seq) noexcept - -> decltype(buffer(std::addressof(*std::begin(seq)), size_t{})) +template +auto buffer_contiguous_sequence(Seq&& seq) noexcept + -> decltype(buffer(std::addressof(*std::begin(seq)), size_t{})) { - using T = typename std::remove_cv< + using T = typename std::remove_cv< typename std::remove_reference::type>::type; - static_assert(detail::is_pod_like::value, "T must be POD"); + static_assert(detail::is_pod_like::value, "T must be POD"); - const auto size = seq_size(seq); - return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr, - size * sizeof(T)); + const auto size = seq_size(seq); + return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr, + size * sizeof(T)); } -template -auto buffer_contiguous_sequence(Seq &&seq, size_t n_bytes) noexcept - -> decltype(buffer_contiguous_sequence(seq)) +template +auto buffer_contiguous_sequence(Seq&& seq, size_t n_bytes) noexcept + -> decltype(buffer_contiguous_sequence(seq)) { - using T = typename std::remove_cv< + using T = typename std::remove_cv< typename std::remove_reference::type>::type; - static_assert(detail::is_pod_like::value, "T must be POD"); + static_assert(detail::is_pod_like::value, "T must be POD"); - const auto size = seq_size(seq); - return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr, - (std::min)(size * sizeof(T), n_bytes)); + const auto size = seq_size(seq); + return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr, + (std::min)(size * sizeof(T), n_bytes)); } -} // namespace detail +} // namespace detail // C array -template mutable_buffer buffer(T (&data)[N]) noexcept +template +mutable_buffer buffer(T (&data)[N]) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template +template mutable_buffer buffer(T (&data)[N], size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } -template const_buffer buffer(const T (&data)[N]) noexcept +template +const_buffer buffer(const T (&data)[N]) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template +template const_buffer buffer(const T (&data)[N], size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } // std::array -template mutable_buffer buffer(std::array &data) noexcept +template +mutable_buffer buffer(std::array& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -mutable_buffer buffer(std::array &data, size_t n_bytes) noexcept +template +mutable_buffer buffer(std::array& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } -template -const_buffer buffer(std::array &data) noexcept +template +const_buffer buffer(std::array& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -const_buffer buffer(std::array &data, size_t n_bytes) noexcept +template +const_buffer buffer(std::array& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } -template -const_buffer buffer(const std::array &data) noexcept +template +const_buffer buffer(const std::array& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -const_buffer buffer(const std::array &data, size_t n_bytes) noexcept +template +const_buffer buffer(const std::array& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } // std::vector -template -mutable_buffer buffer(std::vector &data) noexcept +template +mutable_buffer buffer(std::vector& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -mutable_buffer buffer(std::vector &data, size_t n_bytes) noexcept +template +mutable_buffer buffer(std::vector& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } -template -const_buffer buffer(const std::vector &data) noexcept +template +const_buffer buffer(const std::vector& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -const_buffer buffer(const std::vector &data, size_t n_bytes) noexcept +template +const_buffer buffer(const std::vector& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } // std::basic_string -template -mutable_buffer buffer(std::basic_string &data) noexcept +template +mutable_buffer buffer(std::basic_string& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -mutable_buffer buffer(std::basic_string &data, +template +mutable_buffer buffer(std::basic_string& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } -template -const_buffer buffer(const std::basic_string &data) noexcept +template +const_buffer buffer(const std::basic_string& data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template -const_buffer buffer(const std::basic_string &data, +template +const_buffer buffer(const std::basic_string& data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } #if CPPZMQ_HAS_STRING_VIEW // std::basic_string_view -template +template const_buffer buffer(std::basic_string_view data) noexcept { - return detail::buffer_contiguous_sequence(data); + return detail::buffer_contiguous_sequence(data); } -template +template const_buffer buffer(std::basic_string_view data, size_t n_bytes) noexcept { - return detail::buffer_contiguous_sequence(data, n_bytes); + return detail::buffer_contiguous_sequence(data, n_bytes); } #endif // Buffer for a string literal (null terminated) // where the buffer size excludes the terminating character. // Equivalent to zmq::buffer(std::string_view("...")). -template +template constexpr const_buffer str_buffer(const Char (&data)[N]) noexcept { - static_assert(detail::is_pod_like::value, "Char must be POD"); + static_assert(detail::is_pod_like::value, "Char must be POD"); #ifdef ZMQ_EXTENDED_CONSTEXPR - assert(data[N - 1] == Char{0}); + assert(data[N - 1] == Char{ 0 }); #endif - return const_buffer(static_cast(data), (N - 1) * sizeof(Char)); + return const_buffer(static_cast(data), (N - 1) * sizeof(Char)); } namespace literals { -constexpr const_buffer operator"" _zbuf(const char *str, size_t len) noexcept +constexpr const_buffer operator"" _zbuf(const char* str, size_t len) noexcept { - return const_buffer(str, len * sizeof(char)); + return const_buffer(str, len * sizeof(char)); } -constexpr const_buffer operator"" _zbuf(const wchar_t *str, size_t len) noexcept +constexpr const_buffer operator"" _zbuf(const wchar_t* str, size_t len) noexcept { - return const_buffer(str, len * sizeof(wchar_t)); + return const_buffer(str, len * sizeof(wchar_t)); } -constexpr const_buffer operator"" _zbuf(const char16_t *str, size_t len) noexcept +constexpr const_buffer operator"" _zbuf(const char16_t* str, size_t len) noexcept { - return const_buffer(str, len * sizeof(char16_t)); + return const_buffer(str, len * sizeof(char16_t)); } -constexpr const_buffer operator"" _zbuf(const char32_t *str, size_t len) noexcept +constexpr const_buffer operator"" _zbuf(const char32_t* str, size_t len) noexcept { - return const_buffer(str, len * sizeof(char32_t)); + return const_buffer(str, len * sizeof(char32_t)); } -} - -#endif // ZMQ_CPP11 +} // namespace literals +#endif // ZMQ_CPP11 #ifdef ZMQ_CPP11 namespace sockopt @@ -1360,7 +1454,8 @@ namespace sockopt // and arrays with dynamic size (strings, binary data). // BoolUnit: if true accepts values of type bool (but passed as T into libzmq) -template struct integral_option +template +struct integral_option { }; @@ -1368,25 +1463,36 @@ template struct integral_option // 0: binary data // 1: null-terminated string (`getsockopt` size includes null) // 2: binary (size 32) or Z85 encoder string of size 41 (null included) -template struct array_option +template +struct array_option { }; -#define ZMQ_DEFINE_INTEGRAL_OPT(OPT, NAME, TYPE) \ - using NAME##_t = integral_option; \ - ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {} -#define ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(OPT, NAME, TYPE) \ - using NAME##_t = integral_option; \ - ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {} -#define ZMQ_DEFINE_ARRAY_OPT(OPT, NAME) \ - using NAME##_t = array_option; \ - ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {} -#define ZMQ_DEFINE_ARRAY_OPT_BINARY(OPT, NAME) \ - using NAME##_t = array_option; \ - ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {} -#define ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(OPT, NAME) \ - using NAME##_t = array_option; \ - ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {} +#define ZMQ_DEFINE_INTEGRAL_OPT(OPT, NAME, TYPE) \ + using NAME##_t = integral_option; \ + ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME \ + { \ + } +#define ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(OPT, NAME, TYPE) \ + using NAME##_t = integral_option; \ + ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME \ + { \ + } +#define ZMQ_DEFINE_ARRAY_OPT(OPT, NAME) \ + using NAME##_t = array_option; \ + ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME \ + { \ + } +#define ZMQ_DEFINE_ARRAY_OPT_BINARY(OPT, NAME) \ + using NAME##_t = array_option; \ + ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME \ + { \ + } +#define ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(OPT, NAME) \ + using NAME##_t = array_option; \ + ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME \ + { \ + } // duplicate definition from libzmq 4.3.3 #if defined _WIN32 @@ -1446,16 +1552,13 @@ ZMQ_DEFINE_ARRAY_OPT(ZMQ_GSSAPI_SERVICE_PRINCIPAL, gssapi_service_principal); #endif #ifdef ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE, - gssapi_service_principal_nametype, - int); + gssapi_service_principal_nametype, int); #endif #ifdef ZMQ_GSSAPI_PRINCIPAL ZMQ_DEFINE_ARRAY_OPT(ZMQ_GSSAPI_PRINCIPAL, gssapi_principal); #endif #ifdef ZMQ_GSSAPI_PRINCIPAL_NAMETYPE -ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, - gssapi_principal_nametype, - int); +ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_GSSAPI_PRINCIPAL_NAMETYPE, gssapi_principal_nametype, int); #endif #ifdef ZMQ_HANDSHAKE_IVL ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_HANDSHAKE_IVL, handshake_ivl, int); @@ -1638,913 +1741,965 @@ ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_ZAP_ENFORCE_DOMAIN, zap_enforce_domain, in ZMQ_DEFINE_ARRAY_OPT(ZMQ_ZAP_DOMAIN, zap_domain); #endif -} // namespace sockopt -#endif // ZMQ_CPP11 - +} // namespace sockopt +#endif // ZMQ_CPP11 namespace detail { class socket_base { - public: - socket_base() ZMQ_NOTHROW : _handle(ZMQ_NULLPTR) {} - ZMQ_EXPLICIT socket_base(void *handle) ZMQ_NOTHROW : _handle(handle) {} - - template - ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt") - void setsockopt(int option_, T const &optval) - { - setsockopt(option_, &optval, sizeof(T)); - } - - ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt") - void setsockopt(int option_, const void *optval_, size_t optvallen_) - { - int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_); - if (rc != 0) - throw error_t(); - } - - ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt") - void getsockopt(int option_, void *optval_, size_t *optvallen_) const - { - int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_); - if (rc != 0) - throw error_t(); - } +public: + socket_base() ZMQ_NOTHROW : _handle(ZMQ_NULLPTR) + { + } + ZMQ_EXPLICIT socket_base(void* handle) ZMQ_NOTHROW : _handle(handle) + { + } + + template + ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt") + void setsockopt(int option_, T const& optval) + { + setsockopt(option_, &optval, sizeof(T)); + } + + ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt") + void setsockopt(int option_, const void* optval_, size_t optvallen_) + { + int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_); + if (rc != 0) + throw error_t(); + } - template - ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt") - T getsockopt(int option_) const - { - T optval; - size_t optlen = sizeof(T); - getsockopt(option_, &optval, &optlen); - return optval; - } + ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt") + void getsockopt(int option_, void* optval_, size_t* optvallen_) const + { + int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_); + if (rc != 0) + throw error_t(); + } + + template + ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt") + T getsockopt(int option_) const + { + T optval; + size_t optlen = sizeof(T); + getsockopt(option_, &optval, &optlen); + return optval; + } #ifdef ZMQ_CPP11 - // Set integral socket option, e.g. - // `socket.set(zmq::sockopt::linger, 0)` - template - void set(sockopt::integral_option, const T &val) - { - static_assert(std::is_integral::value, "T must be integral"); - set_option(Opt, &val, sizeof val); - } - - // Set integral socket option from boolean, e.g. - // `socket.set(zmq::sockopt::immediate, false)` - template - void set(sockopt::integral_option, bool val) - { - static_assert(std::is_integral::value, "T must be integral"); - T rep_val = val; - set_option(Opt, &rep_val, sizeof rep_val); - } - - // Set array socket option, e.g. - // `socket.set(zmq::sockopt::plain_username, "foo123")` - template - void set(sockopt::array_option, const char *buf) - { - set_option(Opt, buf, std::strlen(buf)); - } - - // Set array socket option, e.g. - // `socket.set(zmq::sockopt::routing_id, zmq::buffer(id))` - template - void set(sockopt::array_option, const_buffer buf) - { - set_option(Opt, buf.data(), buf.size()); - } - - // Set array socket option, e.g. - // `socket.set(zmq::sockopt::routing_id, id_str)` - template - void set(sockopt::array_option, const std::string &buf) - { - set_option(Opt, buf.data(), buf.size()); - } + // Set integral socket option, e.g. + // `socket.set(zmq::sockopt::linger, 0)` + template + void set(sockopt::integral_option, const T& val) + { + static_assert(std::is_integral::value, "T must be integral"); + set_option(Opt, &val, sizeof val); + } + + // Set integral socket option from boolean, e.g. + // `socket.set(zmq::sockopt::immediate, false)` + template + void set(sockopt::integral_option, bool val) + { + static_assert(std::is_integral::value, "T must be integral"); + T rep_val = val; + set_option(Opt, &rep_val, sizeof rep_val); + } + + // Set array socket option, e.g. + // `socket.set(zmq::sockopt::plain_username, "foo123")` + template + void set(sockopt::array_option, const char* buf) + { + set_option(Opt, buf, std::strlen(buf)); + } + + // Set array socket option, e.g. + // `socket.set(zmq::sockopt::routing_id, zmq::buffer(id))` + template + void set(sockopt::array_option, const_buffer buf) + { + set_option(Opt, buf.data(), buf.size()); + } + + // Set array socket option, e.g. + // `socket.set(zmq::sockopt::routing_id, id_str)` + template + void set(sockopt::array_option, const std::string& buf) + { + set_option(Opt, buf.data(), buf.size()); + } #if CPPZMQ_HAS_STRING_VIEW - // Set array socket option, e.g. - // `socket.set(zmq::sockopt::routing_id, id_str)` - template - void set(sockopt::array_option, std::string_view buf) - { - set_option(Opt, buf.data(), buf.size()); - } -#endif - - // Get scalar socket option, e.g. - // `auto opt = socket.get(zmq::sockopt::linger)` - template - ZMQ_NODISCARD T get(sockopt::integral_option) const - { - static_assert(std::is_integral::value, "T must be integral"); - T val; - size_t size = sizeof val; - get_option(Opt, &val, &size); - assert(size == sizeof val); - return val; - } - - // Get array socket option, writes to buf, returns option size in bytes, e.g. - // `size_t optsize = socket.get(zmq::sockopt::routing_id, zmq::buffer(id))` - template - ZMQ_NODISCARD size_t get(sockopt::array_option, - mutable_buffer buf) const - { - size_t size = buf.size(); - get_option(Opt, buf.data(), &size); - return size; - } - - // Get array socket option as string (initializes the string buffer size to init_size) e.g. - // `auto s = socket.get(zmq::sockopt::routing_id)` - // Note: removes the null character from null-terminated string options, - // i.e. the string size excludes the null character. - template - ZMQ_NODISCARD std::string get(sockopt::array_option, - size_t init_size = 1024) const - { - if (NullTerm == 2 && init_size == 1024) { - init_size = 41; // get as Z85 string - } - std::string str(init_size, '\0'); - size_t size = get(sockopt::array_option{}, buffer(str)); - if (NullTerm == 1) { - if (size > 0) { - assert(str[size - 1] == '\0'); - --size; - } - } else if (NullTerm == 2) { - assert(size == 32 || size == 41); - if (size == 41) { - assert(str[size - 1] == '\0'); - --size; - } - } - str.resize(size); - return str; - } -#endif - - void bind(std::string const &addr) { bind(addr.c_str()); } - - void bind(const char *addr_) - { - int rc = zmq_bind(_handle, addr_); - if (rc != 0) - throw error_t(); - } - - void unbind(std::string const &addr) { unbind(addr.c_str()); } - - void unbind(const char *addr_) - { - int rc = zmq_unbind(_handle, addr_); - if (rc != 0) - throw error_t(); - } - - void connect(std::string const &addr) { connect(addr.c_str()); } - - void connect(const char *addr_) - { - int rc = zmq_connect(_handle, addr_); - if (rc != 0) - throw error_t(); - } + // Set array socket option, e.g. + // `socket.set(zmq::sockopt::routing_id, id_str)` + template + void set(sockopt::array_option, std::string_view buf) + { + set_option(Opt, buf.data(), buf.size()); + } +#endif + + // Get scalar socket option, e.g. + // `auto opt = socket.get(zmq::sockopt::linger)` + template + ZMQ_NODISCARD T get(sockopt::integral_option) const + { + static_assert(std::is_integral::value, "T must be integral"); + T val; + size_t size = sizeof val; + get_option(Opt, &val, &size); + assert(size == sizeof val); + return val; + } + + // Get array socket option, writes to buf, returns option size in bytes, e.g. + // `size_t optsize = socket.get(zmq::sockopt::routing_id, zmq::buffer(id))` + template + ZMQ_NODISCARD size_t get(sockopt::array_option, mutable_buffer buf) const + { + size_t size = buf.size(); + get_option(Opt, buf.data(), &size); + return size; + } + + // Get array socket option as string (initializes the string buffer size to init_size) + // e.g. `auto s = socket.get(zmq::sockopt::routing_id)` Note: removes the null character + // from null-terminated string options, i.e. the string size excludes the null + // character. + template + ZMQ_NODISCARD std::string get(sockopt::array_option, + size_t init_size = 1024) const + { + if (NullTerm == 2 && init_size == 1024) + { + init_size = 41; // get as Z85 string + } + std::string str(init_size, '\0'); + size_t size = get(sockopt::array_option{}, buffer(str)); + if (NullTerm == 1) + { + if (size > 0) + { + assert(str[size - 1] == '\0'); + --size; + } + } + else if (NullTerm == 2) + { + assert(size == 32 || size == 41); + if (size == 41) + { + assert(str[size - 1] == '\0'); + --size; + } + } + str.resize(size); + return str; + } +#endif + + void bind(std::string const& addr) + { + bind(addr.c_str()); + } + + void bind(const char* addr_) + { + int rc = zmq_bind(_handle, addr_); + if (rc != 0) + throw error_t(); + } - void disconnect(std::string const &addr) { disconnect(addr.c_str()); } + void unbind(std::string const& addr) + { + unbind(addr.c_str()); + } - void disconnect(const char *addr_) - { - int rc = zmq_disconnect(_handle, addr_); - if (rc != 0) - throw error_t(); - } + void unbind(const char* addr_) + { + int rc = zmq_unbind(_handle, addr_); + if (rc != 0) + throw error_t(); + } - bool connected() const ZMQ_NOTHROW { return (_handle != ZMQ_NULLPTR); } + void connect(std::string const& addr) + { + connect(addr.c_str()); + } - ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking a const_buffer and send_flags") - size_t send(const void *buf_, size_t len_, int flags_ = 0) - { - int nbytes = zmq_send(_handle, buf_, len_, flags_); - if (nbytes >= 0) - return static_cast(nbytes); - if (zmq_errno() == EAGAIN) - return 0; - throw error_t(); - } + void connect(const char* addr_) + { + int rc = zmq_connect(_handle, addr_); + if (rc != 0) + throw error_t(); + } - ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags") - bool send(message_t &msg_, - int flags_ = 0) // default until removed - { - int nbytes = zmq_msg_send(msg_.handle(), _handle, flags_); - if (nbytes >= 0) - return true; - if (zmq_errno() == EAGAIN) - return false; - throw error_t(); - } + void disconnect(std::string const& addr) + { + disconnect(addr.c_str()); + } - template - ZMQ_CPP11_DEPRECATED( - "from 4.4.1, use send taking message_t or buffer (for contiguous " - "ranges), and send_flags") - bool send(T first, T last, int flags_ = 0) - { - zmq::message_t msg(first, last); - int nbytes = zmq_msg_send(msg.handle(), _handle, flags_); - if (nbytes >= 0) - return true; - if (zmq_errno() == EAGAIN) - return false; - throw error_t(); - } + void disconnect(const char* addr_) + { + int rc = zmq_disconnect(_handle, addr_); + if (rc != 0) + throw error_t(); + } + + bool connected() const ZMQ_NOTHROW + { + return (_handle != ZMQ_NULLPTR); + } + + ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking a const_buffer and send_flags") + size_t send(const void* buf_, size_t len_, int flags_ = 0) + { + int nbytes = zmq_send(_handle, buf_, len_, flags_); + if (nbytes >= 0) + return static_cast(nbytes); + if (zmq_errno() == EAGAIN) + return 0; + throw error_t(); + } + + ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags") + bool send(message_t& msg_, + int flags_ = 0) // default until removed + { + int nbytes = zmq_msg_send(msg_.handle(), _handle, flags_); + if (nbytes >= 0) + return true; + if (zmq_errno() == EAGAIN) + return false; + throw error_t(); + } + + template + ZMQ_CPP11_DEPRECATED("from 4.4.1, use send taking message_t or buffer (for contiguous " + "ranges), and send_flags") + bool send(T first, T last, int flags_ = 0) + { + zmq::message_t msg(first, last); + int nbytes = zmq_msg_send(msg.handle(), _handle, flags_); + if (nbytes >= 0) + return true; + if (zmq_errno() == EAGAIN) + return false; + throw error_t(); + } #ifdef ZMQ_HAS_RVALUE_REFS - ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags") - bool send(message_t &&msg_, - int flags_ = 0) // default until removed - { + ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags") + bool send(message_t&& msg_, + int flags_ = 0) // default until removed + { #ifdef ZMQ_CPP11 - return send(msg_, static_cast(flags_)).has_value(); + return send(msg_, static_cast(flags_)).has_value(); #else - return send(msg_, flags_); + return send(msg_, flags_); #endif - } + } #endif #ifdef ZMQ_CPP11 - send_result_t send(const_buffer buf, send_flags flags = send_flags::none) - { - const int nbytes = - zmq_send(_handle, buf.data(), buf.size(), static_cast(flags)); - if (nbytes >= 0) - return static_cast(nbytes); - if (zmq_errno() == EAGAIN) - return {}; - throw error_t(); - } - - send_result_t send(message_t &msg, send_flags flags) - { - int nbytes = zmq_msg_send(msg.handle(), _handle, static_cast(flags)); - if (nbytes >= 0) - return static_cast(nbytes); - if (zmq_errno() == EAGAIN) - return {}; - throw error_t(); - } - - send_result_t send(message_t &&msg, send_flags flags) - { - return send(msg, flags); - } -#endif - - ZMQ_CPP11_DEPRECATED( - "from 4.3.1, use recv taking a mutable_buffer and recv_flags") - size_t recv(void *buf_, size_t len_, int flags_ = 0) - { - int nbytes = zmq_recv(_handle, buf_, len_, flags_); - if (nbytes >= 0) - return static_cast(nbytes); - if (zmq_errno() == EAGAIN) - return 0; - throw error_t(); - } - - ZMQ_CPP11_DEPRECATED( - "from 4.3.1, use recv taking a reference to message_t and recv_flags") - bool recv(message_t *msg_, int flags_ = 0) - { - int nbytes = zmq_msg_recv(msg_->handle(), _handle, flags_); - if (nbytes >= 0) - return true; - if (zmq_errno() == EAGAIN) - return false; - throw error_t(); - } + send_result_t send(const_buffer buf, send_flags flags = send_flags::none) + { + const int nbytes = zmq_send(_handle, buf.data(), buf.size(), static_cast(flags)); + if (nbytes >= 0) + return static_cast(nbytes); + if (zmq_errno() == EAGAIN) + return {}; + throw error_t(); + } + + send_result_t send(message_t& msg, send_flags flags) + { + int nbytes = zmq_msg_send(msg.handle(), _handle, static_cast(flags)); + if (nbytes >= 0) + return static_cast(nbytes); + if (zmq_errno() == EAGAIN) + return {}; + throw error_t(); + } + + send_result_t send(message_t&& msg, send_flags flags) + { + return send(msg, flags); + } +#endif + + ZMQ_CPP11_DEPRECATED("from 4.3.1, use recv taking a mutable_buffer and recv_flags") + size_t recv(void* buf_, size_t len_, int flags_ = 0) + { + int nbytes = zmq_recv(_handle, buf_, len_, flags_); + if (nbytes >= 0) + return static_cast(nbytes); + if (zmq_errno() == EAGAIN) + return 0; + throw error_t(); + } + + ZMQ_CPP11_DEPRECATED("from 4.3.1, use recv taking a reference to message_t and " + "recv_flags") + bool recv(message_t* msg_, int flags_ = 0) + { + int nbytes = zmq_msg_recv(msg_->handle(), _handle, flags_); + if (nbytes >= 0) + return true; + if (zmq_errno() == EAGAIN) + return false; + throw error_t(); + } #ifdef ZMQ_CPP11 - ZMQ_NODISCARD - recv_buffer_result_t recv(mutable_buffer buf, - recv_flags flags = recv_flags::none) + ZMQ_NODISCARD + recv_buffer_result_t recv(mutable_buffer buf, recv_flags flags = recv_flags::none) + { + const int nbytes = zmq_recv(_handle, buf.data(), buf.size(), static_cast(flags)); + if (nbytes >= 0) { - const int nbytes = - zmq_recv(_handle, buf.data(), buf.size(), static_cast(flags)); - if (nbytes >= 0) { - return recv_buffer_size{ - (std::min)(static_cast(nbytes), buf.size()), - static_cast(nbytes)}; - } - if (zmq_errno() == EAGAIN) - return {}; - throw error_t(); + return recv_buffer_size{ (std::min)(static_cast(nbytes), buf.size()), + static_cast(nbytes) }; } + if (zmq_errno() == EAGAIN) + return {}; + throw error_t(); + } - ZMQ_NODISCARD - recv_result_t recv(message_t &msg, recv_flags flags = recv_flags::none) + ZMQ_NODISCARD + recv_result_t recv(message_t& msg, recv_flags flags = recv_flags::none) + { + const int nbytes = zmq_msg_recv(msg.handle(), _handle, static_cast(flags)); + if (nbytes >= 0) { - const int nbytes = - zmq_msg_recv(msg.handle(), _handle, static_cast(flags)); - if (nbytes >= 0) { - assert(msg.size() == static_cast(nbytes)); - return static_cast(nbytes); - } - if (zmq_errno() == EAGAIN) - return {}; - throw error_t(); + assert(msg.size() == static_cast(nbytes)); + return static_cast(nbytes); } + if (zmq_errno() == EAGAIN) + return {}; + throw error_t(); + } #endif #if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0) - void join(const char *group) - { - int rc = zmq_join(_handle, group); - if (rc != 0) - throw error_t(); - } - - void leave(const char *group) - { - int rc = zmq_leave(_handle, group); - if (rc != 0) - throw error_t(); - } -#endif - - ZMQ_NODISCARD void *handle() ZMQ_NOTHROW { return _handle; } - ZMQ_NODISCARD const void *handle() const ZMQ_NOTHROW { return _handle; } - - ZMQ_EXPLICIT operator bool() const ZMQ_NOTHROW { return _handle != ZMQ_NULLPTR; } - // note: non-const operator bool can be removed once - // operator void* is removed from socket_t - ZMQ_EXPLICIT operator bool() ZMQ_NOTHROW { return _handle != ZMQ_NULLPTR; } - - protected: - void *_handle; + void join(const char* group) + { + int rc = zmq_join(_handle, group); + if (rc != 0) + throw error_t(); + } - private: - void set_option(int option_, const void *optval_, size_t optvallen_) - { - int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_); - if (rc != 0) - throw error_t(); - } + void leave(const char* group) + { + int rc = zmq_leave(_handle, group); + if (rc != 0) + throw error_t(); + } +#endif + + ZMQ_NODISCARD void* handle() ZMQ_NOTHROW + { + return _handle; + } + ZMQ_NODISCARD const void* handle() const ZMQ_NOTHROW + { + return _handle; + } + + ZMQ_EXPLICIT operator bool() const ZMQ_NOTHROW + { + return _handle != ZMQ_NULLPTR; + } + // note: non-const operator bool can be removed once + // operator void* is removed from socket_t + ZMQ_EXPLICIT operator bool() ZMQ_NOTHROW + { + return _handle != ZMQ_NULLPTR; + } + +protected: + void* _handle; + +private: + void set_option(int option_, const void* optval_, size_t optvallen_) + { + int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_); + if (rc != 0) + throw error_t(); + } - void get_option(int option_, void *optval_, size_t *optvallen_) const - { - int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_); - if (rc != 0) - throw error_t(); - } + void get_option(int option_, void* optval_, size_t* optvallen_) const + { + int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_); + if (rc != 0) + throw error_t(); + } }; -} // namespace detail +} // namespace detail #ifdef ZMQ_CPP11 enum class socket_type : int { - req = ZMQ_REQ, - rep = ZMQ_REP, - dealer = ZMQ_DEALER, - router = ZMQ_ROUTER, - pub = ZMQ_PUB, - sub = ZMQ_SUB, - xpub = ZMQ_XPUB, - xsub = ZMQ_XSUB, - push = ZMQ_PUSH, - pull = ZMQ_PULL, + req = ZMQ_REQ, + rep = ZMQ_REP, + dealer = ZMQ_DEALER, + router = ZMQ_ROUTER, + pub = ZMQ_PUB, + sub = ZMQ_SUB, + xpub = ZMQ_XPUB, + xsub = ZMQ_XSUB, + push = ZMQ_PUSH, + pull = ZMQ_PULL, #if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0) - server = ZMQ_SERVER, - client = ZMQ_CLIENT, - radio = ZMQ_RADIO, - dish = ZMQ_DISH, + server = ZMQ_SERVER, + client = ZMQ_CLIENT, + radio = ZMQ_RADIO, + dish = ZMQ_DISH, #endif #if ZMQ_VERSION_MAJOR >= 4 - stream = ZMQ_STREAM, + stream = ZMQ_STREAM, #endif - pair = ZMQ_PAIR + pair = ZMQ_PAIR }; #endif struct from_handle_t { - struct _private - { - }; // disabling use other than with from_handle - ZMQ_CONSTEXPR_FN ZMQ_EXPLICIT from_handle_t(_private /*p*/) ZMQ_NOTHROW {} + struct _private + { + }; // disabling use other than with from_handle + ZMQ_CONSTEXPR_FN ZMQ_EXPLICIT from_handle_t(_private /*p*/) ZMQ_NOTHROW + { + } }; -ZMQ_CONSTEXPR_VAR from_handle_t from_handle = - from_handle_t(from_handle_t::_private()); +ZMQ_CONSTEXPR_VAR from_handle_t from_handle = from_handle_t(from_handle_t::_private()); // A non-owning nullable reference to a socket. // The reference is invalidated on socket close or destruction. class socket_ref : public detail::socket_base { - public: - socket_ref() ZMQ_NOTHROW : detail::socket_base() {} +public: + socket_ref() ZMQ_NOTHROW : detail::socket_base() + { + } #ifdef ZMQ_CPP11 - socket_ref(std::nullptr_t) ZMQ_NOTHROW : detail::socket_base() {} + socket_ref(std::nullptr_t) ZMQ_NOTHROW : detail::socket_base() + { + } #endif - socket_ref(from_handle_t /*fh*/, void *handle) ZMQ_NOTHROW - : detail::socket_base(handle) - { - } + socket_ref(from_handle_t /*fh*/, void* handle) ZMQ_NOTHROW : detail::socket_base(handle) + { + } }; #ifdef ZMQ_CPP11 inline bool operator==(socket_ref sr, std::nullptr_t /*p*/) ZMQ_NOTHROW { - return sr.handle() == nullptr; + return sr.handle() == nullptr; } inline bool operator==(std::nullptr_t /*p*/, socket_ref sr) ZMQ_NOTHROW { - return sr.handle() == nullptr; + return sr.handle() == nullptr; } inline bool operator!=(socket_ref sr, std::nullptr_t /*p*/) ZMQ_NOTHROW { - return !(sr == nullptr); + return !(sr == nullptr); } inline bool operator!=(std::nullptr_t /*p*/, socket_ref sr) ZMQ_NOTHROW { - return !(sr == nullptr); + return !(sr == nullptr); } #endif inline bool operator==(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return std::equal_to()(a.handle(), b.handle()); + return std::equal_to()(a.handle(), b.handle()); } inline bool operator!=(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return !(a == b); + return !(a == b); } inline bool operator<(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return std::less()(a.handle(), b.handle()); + return std::less()(a.handle(), b.handle()); } inline bool operator>(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return b < a; + return b < a; } inline bool operator<=(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return !(a > b); + return !(a > b); } inline bool operator>=(socket_ref a, socket_ref b) ZMQ_NOTHROW { - return !(a < b); + return !(a < b); } -} // namespace zmq +} // namespace zmq #ifdef ZMQ_CPP11 namespace std { -template<> struct hash +template <> +struct hash { - size_t operator()(zmq::socket_ref sr) const ZMQ_NOTHROW - { - return hash()(sr.handle()); - } + size_t operator()(zmq::socket_ref sr) const ZMQ_NOTHROW + { + return hash()(sr.handle()); + } }; -} // namespace std +} // namespace std #endif namespace zmq { class socket_t : public detail::socket_base { - friend class monitor_t; + friend class monitor_t; - public: - socket_t() ZMQ_NOTHROW : detail::socket_base(ZMQ_NULLPTR), ctxptr(ZMQ_NULLPTR) {} +public: + socket_t() ZMQ_NOTHROW : detail::socket_base(ZMQ_NULLPTR), ctxptr(ZMQ_NULLPTR) + { + } - socket_t(context_t &context_, int type_) : - detail::socket_base(zmq_socket(context_.handle(), type_)), - ctxptr(context_.handle()) - { - if (_handle == ZMQ_NULLPTR) - throw error_t(); - } + socket_t(context_t& context_, int type_) + : detail::socket_base(zmq_socket(context_.handle(), type_)), ctxptr(context_.handle()) + { + if (_handle == ZMQ_NULLPTR) + throw error_t(); + } #ifdef ZMQ_CPP11 - socket_t(context_t &context_, socket_type type_) : - socket_t(context_, static_cast(type_)) - { - } + socket_t(context_t& context_, socket_type type_) + : socket_t(context_, static_cast(type_)) + { + } #endif #ifdef ZMQ_HAS_RVALUE_REFS - socket_t(socket_t &&rhs) ZMQ_NOTHROW : detail::socket_base(rhs._handle), - ctxptr(rhs.ctxptr) - { - rhs._handle = ZMQ_NULLPTR; - rhs.ctxptr = ZMQ_NULLPTR; - } - socket_t &operator=(socket_t &&rhs) ZMQ_NOTHROW - { - close(); - std::swap(_handle, rhs._handle); - std::swap(ctxptr, rhs.ctxptr); - return *this; - } -#endif - - ~socket_t() ZMQ_NOTHROW { close(); } - - operator void *() ZMQ_NOTHROW { return _handle; } - - operator void const *() const ZMQ_NOTHROW { return _handle; } - - void close() ZMQ_NOTHROW - { - if (_handle == ZMQ_NULLPTR) - // already closed - return; - int rc = zmq_close(_handle); - ZMQ_ASSERT(rc == 0); - _handle = ZMQ_NULLPTR; - ctxptr = ZMQ_NULLPTR; - } - - void swap(socket_t &other) ZMQ_NOTHROW - { - std::swap(_handle, other._handle); - std::swap(ctxptr, other.ctxptr); - } - - operator socket_ref() ZMQ_NOTHROW { return socket_ref(from_handle, _handle); } - - private: - void *ctxptr; - - socket_t(const socket_t &) ZMQ_DELETED_FUNCTION; - void operator=(const socket_t &) ZMQ_DELETED_FUNCTION; - - // used by monitor_t - socket_t(void *context_, int type_) : - detail::socket_base(zmq_socket(context_, type_)), ctxptr(context_) - { - if (_handle == ZMQ_NULLPTR) - throw error_t(); - if (ctxptr == ZMQ_NULLPTR) - throw error_t(); - } + socket_t(socket_t&& rhs) ZMQ_NOTHROW : detail::socket_base(rhs._handle), + ctxptr(rhs.ctxptr) + { + rhs._handle = ZMQ_NULLPTR; + rhs.ctxptr = ZMQ_NULLPTR; + } + socket_t& operator=(socket_t&& rhs) ZMQ_NOTHROW + { + close(); + std::swap(_handle, rhs._handle); + std::swap(ctxptr, rhs.ctxptr); + return *this; + } +#endif + + ~socket_t() ZMQ_NOTHROW + { + close(); + } + + operator void*() ZMQ_NOTHROW + { + return _handle; + } + + operator void const*() const ZMQ_NOTHROW + { + return _handle; + } + + void close() ZMQ_NOTHROW + { + if (_handle == ZMQ_NULLPTR) + // already closed + return; + int rc = zmq_close(_handle); + ZMQ_ASSERT(rc == 0); + _handle = ZMQ_NULLPTR; + ctxptr = ZMQ_NULLPTR; + } + + void swap(socket_t& other) ZMQ_NOTHROW + { + std::swap(_handle, other._handle); + std::swap(ctxptr, other.ctxptr); + } + + operator socket_ref() ZMQ_NOTHROW + { + return socket_ref(from_handle, _handle); + } + +private: + void* ctxptr; + + socket_t(const socket_t&) ZMQ_DELETED_FUNCTION; + void operator=(const socket_t&) ZMQ_DELETED_FUNCTION; + + // used by monitor_t + socket_t(void* context_, int type_) + : detail::socket_base(zmq_socket(context_, type_)), ctxptr(context_) + { + if (_handle == ZMQ_NULLPTR) + throw error_t(); + if (ctxptr == ZMQ_NULLPTR) + throw error_t(); + } }; -inline void swap(socket_t &a, socket_t &b) ZMQ_NOTHROW +inline void swap(socket_t& a, socket_t& b) ZMQ_NOTHROW { - a.swap(b); + a.swap(b); } ZMQ_DEPRECATED("from 4.3.1, use proxy taking socket_t objects") -inline void proxy(void *frontend, void *backend, void *capture) +inline void proxy(void* frontend, void* backend, void* capture) { - int rc = zmq_proxy(frontend, backend, capture); - if (rc != 0) - throw error_t(); + int rc = zmq_proxy(frontend, backend, capture); + if (rc != 0) + throw error_t(); } -inline void -proxy(socket_ref frontend, socket_ref backend, socket_ref capture = socket_ref()) +inline void proxy(socket_ref frontend, socket_ref backend, + socket_ref capture = socket_ref()) { - int rc = zmq_proxy(frontend.handle(), backend.handle(), capture.handle()); - if (rc != 0) - throw error_t(); + int rc = zmq_proxy(frontend.handle(), backend.handle(), capture.handle()); + if (rc != 0) + throw error_t(); } #ifdef ZMQ_HAS_PROXY_STEERABLE ZMQ_DEPRECATED("from 4.3.1, use proxy_steerable taking socket_t objects") -inline void -proxy_steerable(void *frontend, void *backend, void *capture, void *control) +inline void proxy_steerable(void* frontend, void* backend, void* capture, void* control) { - int rc = zmq_proxy_steerable(frontend, backend, capture, control); - if (rc != 0) - throw error_t(); + int rc = zmq_proxy_steerable(frontend, backend, capture, control); + if (rc != 0) + throw error_t(); } -inline void proxy_steerable(socket_ref frontend, - socket_ref backend, - socket_ref capture, +inline void proxy_steerable(socket_ref frontend, socket_ref backend, socket_ref capture, socket_ref control) { - int rc = zmq_proxy_steerable(frontend.handle(), backend.handle(), - capture.handle(), control.handle()); - if (rc != 0) - throw error_t(); + int rc = zmq_proxy_steerable(frontend.handle(), backend.handle(), capture.handle(), + control.handle()); + if (rc != 0) + throw error_t(); } #endif class monitor_t { - public: - monitor_t() : _socket(), _monitor_socket() {} +public: + monitor_t() : _socket(), _monitor_socket() + { + } - virtual ~monitor_t() { close(); } + virtual ~monitor_t() + { + close(); + } #ifdef ZMQ_HAS_RVALUE_REFS - monitor_t(monitor_t &&rhs) ZMQ_NOTHROW : _socket(), _monitor_socket() - { - std::swap(_socket, rhs._socket); - std::swap(_monitor_socket, rhs._monitor_socket); - } + monitor_t(monitor_t&& rhs) ZMQ_NOTHROW : _socket(), _monitor_socket() + { + std::swap(_socket, rhs._socket); + std::swap(_monitor_socket, rhs._monitor_socket); + } + + monitor_t& operator=(monitor_t&& rhs) ZMQ_NOTHROW + { + close(); + _socket = socket_ref(); + std::swap(_socket, rhs._socket); + std::swap(_monitor_socket, rhs._monitor_socket); + return *this; + } +#endif + + void monitor(socket_t& socket, std::string const& addr, int events = ZMQ_EVENT_ALL) + { + monitor(socket, addr.c_str(), events); + } + + void monitor(socket_t& socket, const char* addr_, int events = ZMQ_EVENT_ALL) + { + init(socket, addr_, events); + while (true) + { + check_event(-1); + } + } + + void init(socket_t& socket, std::string const& addr, int events = ZMQ_EVENT_ALL) + { + init(socket, addr.c_str(), events); + } + + void init(socket_t& socket, const char* addr_, int events = ZMQ_EVENT_ALL) + { + int rc = zmq_socket_monitor(socket.handle(), addr_, events); + if (rc != 0) + throw error_t(); - monitor_t &operator=(monitor_t &&rhs) ZMQ_NOTHROW - { - close(); - _socket = socket_ref(); - std::swap(_socket, rhs._socket); - std::swap(_monitor_socket, rhs._monitor_socket); - return *this; - } -#endif + _socket = socket; + _monitor_socket = socket_t(socket.ctxptr, ZMQ_PAIR); + _monitor_socket.connect(addr_); + on_monitor_started(); + } - void - monitor(socket_t &socket, std::string const &addr, int events = ZMQ_EVENT_ALL) - { - monitor(socket, addr.c_str(), events); - } + bool check_event(int timeout = 0) + { + assert(_monitor_socket); - void monitor(socket_t &socket, const char *addr_, int events = ZMQ_EVENT_ALL) - { - init(socket, addr_, events); - while (true) { - check_event(-1); - } - } - - void init(socket_t &socket, std::string const &addr, int events = ZMQ_EVENT_ALL) - { - init(socket, addr.c_str(), events); - } + zmq_msg_t eventMsg; + zmq_msg_init(&eventMsg); - void init(socket_t &socket, const char *addr_, int events = ZMQ_EVENT_ALL) - { - int rc = zmq_socket_monitor(socket.handle(), addr_, events); - if (rc != 0) - throw error_t(); + zmq::pollitem_t items[] = { + { _monitor_socket.handle(), 0, ZMQ_POLLIN, 0 }, + }; - _socket = socket; - _monitor_socket = socket_t(socket.ctxptr, ZMQ_PAIR); - _monitor_socket.connect(addr_); + zmq::poll(&items[0], 1, timeout); - on_monitor_started(); + if (items[0].revents & ZMQ_POLLIN) + { + int rc = zmq_msg_recv(&eventMsg, _monitor_socket.handle(), 0); + if (rc == -1 && zmq_errno() == ETERM) + return false; + assert(rc != -1); } - - bool check_event(int timeout = 0) + else { - assert(_monitor_socket); - - zmq_msg_t eventMsg; - zmq_msg_init(&eventMsg); - - zmq::pollitem_t items[] = { - {_monitor_socket.handle(), 0, ZMQ_POLLIN, 0}, - }; - - zmq::poll(&items[0], 1, timeout); - - if (items[0].revents & ZMQ_POLLIN) { - int rc = zmq_msg_recv(&eventMsg, _monitor_socket.handle(), 0); - if (rc == -1 && zmq_errno() == ETERM) - return false; - assert(rc != -1); - - } else { - zmq_msg_close(&eventMsg); - return false; - } + zmq_msg_close(&eventMsg); + return false; + } #if ZMQ_VERSION_MAJOR >= 4 - const char *data = static_cast(zmq_msg_data(&eventMsg)); - zmq_event_t msgEvent; - memcpy(&msgEvent.event, data, sizeof(uint16_t)); - data += sizeof(uint16_t); - memcpy(&msgEvent.value, data, sizeof(int32_t)); - zmq_event_t *event = &msgEvent; + const char* data = static_cast(zmq_msg_data(&eventMsg)); + zmq_event_t msgEvent; + memcpy(&msgEvent.event, data, sizeof(uint16_t)); + data += sizeof(uint16_t); + memcpy(&msgEvent.value, data, sizeof(int32_t)); + zmq_event_t* event = &msgEvent; #else - zmq_event_t *event = static_cast(zmq_msg_data(&eventMsg)); + zmq_event_t* event = static_cast(zmq_msg_data(&eventMsg)); #endif #ifdef ZMQ_NEW_MONITOR_EVENT_LAYOUT - zmq_msg_t addrMsg; - zmq_msg_init(&addrMsg); - int rc = zmq_msg_recv(&addrMsg, _monitor_socket.handle(), 0); - if (rc == -1 && zmq_errno() == ETERM) { - zmq_msg_close(&eventMsg); - return false; - } + zmq_msg_t addrMsg; + zmq_msg_init(&addrMsg); + int rc = zmq_msg_recv(&addrMsg, _monitor_socket.handle(), 0); + if (rc == -1 && zmq_errno() == ETERM) + { + zmq_msg_close(&eventMsg); + return false; + } - assert(rc != -1); - const char *str = static_cast(zmq_msg_data(&addrMsg)); - std::string address(str, str + zmq_msg_size(&addrMsg)); - zmq_msg_close(&addrMsg); + assert(rc != -1); + const char* str = static_cast(zmq_msg_data(&addrMsg)); + std::string address(str, str + zmq_msg_size(&addrMsg)); + zmq_msg_close(&addrMsg); #else - // Bit of a hack, but all events in the zmq_event_t union have the same layout so this will work for all event types. - std::string address = event->data.connected.addr; + // Bit of a hack, but all events in the zmq_event_t union have the same layout so this + // will work for all event types. + std::string address = event->data.connected.addr; #endif #ifdef ZMQ_EVENT_MONITOR_STOPPED - if (event->event == ZMQ_EVENT_MONITOR_STOPPED) { - zmq_msg_close(&eventMsg); - return false; - } - -#endif - - switch (event->event) { - case ZMQ_EVENT_CONNECTED: - on_event_connected(*event, address.c_str()); - break; - case ZMQ_EVENT_CONNECT_DELAYED: - on_event_connect_delayed(*event, address.c_str()); - break; - case ZMQ_EVENT_CONNECT_RETRIED: - on_event_connect_retried(*event, address.c_str()); - break; - case ZMQ_EVENT_LISTENING: - on_event_listening(*event, address.c_str()); - break; - case ZMQ_EVENT_BIND_FAILED: - on_event_bind_failed(*event, address.c_str()); - break; - case ZMQ_EVENT_ACCEPTED: - on_event_accepted(*event, address.c_str()); - break; - case ZMQ_EVENT_ACCEPT_FAILED: - on_event_accept_failed(*event, address.c_str()); - break; - case ZMQ_EVENT_CLOSED: - on_event_closed(*event, address.c_str()); - break; - case ZMQ_EVENT_CLOSE_FAILED: - on_event_close_failed(*event, address.c_str()); - break; - case ZMQ_EVENT_DISCONNECTED: - on_event_disconnected(*event, address.c_str()); - break; + if (event->event == ZMQ_EVENT_MONITOR_STOPPED) + { + zmq_msg_close(&eventMsg); + return false; + } + +#endif + + switch (event->event) + { + case ZMQ_EVENT_CONNECTED: + on_event_connected(*event, address.c_str()); + break; + case ZMQ_EVENT_CONNECT_DELAYED: + on_event_connect_delayed(*event, address.c_str()); + break; + case ZMQ_EVENT_CONNECT_RETRIED: + on_event_connect_retried(*event, address.c_str()); + break; + case ZMQ_EVENT_LISTENING: + on_event_listening(*event, address.c_str()); + break; + case ZMQ_EVENT_BIND_FAILED: + on_event_bind_failed(*event, address.c_str()); + break; + case ZMQ_EVENT_ACCEPTED: + on_event_accepted(*event, address.c_str()); + break; + case ZMQ_EVENT_ACCEPT_FAILED: + on_event_accept_failed(*event, address.c_str()); + break; + case ZMQ_EVENT_CLOSED: + on_event_closed(*event, address.c_str()); + break; + case ZMQ_EVENT_CLOSE_FAILED: + on_event_close_failed(*event, address.c_str()); + break; + case ZMQ_EVENT_DISCONNECTED: + on_event_disconnected(*event, address.c_str()); + break; #ifdef ZMQ_BUILD_DRAFT_API #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3) - case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL: - on_event_handshake_failed_no_detail(*event, address.c_str()); - break; - case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL: - on_event_handshake_failed_protocol(*event, address.c_str()); - break; - case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH: - on_event_handshake_failed_auth(*event, address.c_str()); - break; - case ZMQ_EVENT_HANDSHAKE_SUCCEEDED: - on_event_handshake_succeeded(*event, address.c_str()); - break; + case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL: + on_event_handshake_failed_no_detail(*event, address.c_str()); + break; + case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL: + on_event_handshake_failed_protocol(*event, address.c_str()); + break; + case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH: + on_event_handshake_failed_auth(*event, address.c_str()); + break; + case ZMQ_EVENT_HANDSHAKE_SUCCEEDED: + on_event_handshake_succeeded(*event, address.c_str()); + break; #elif ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 1) - case ZMQ_EVENT_HANDSHAKE_FAILED: - on_event_handshake_failed(*event, address.c_str()); - break; - case ZMQ_EVENT_HANDSHAKE_SUCCEED: - on_event_handshake_succeed(*event, address.c_str()); - break; + case ZMQ_EVENT_HANDSHAKE_FAILED: + on_event_handshake_failed(*event, address.c_str()); + break; + case ZMQ_EVENT_HANDSHAKE_SUCCEED: + on_event_handshake_succeed(*event, address.c_str()); + break; #endif #endif - default: - on_event_unknown(*event, address.c_str()); - break; - } - zmq_msg_close(&eventMsg); - - return true; + default: + on_event_unknown(*event, address.c_str()); + break; } + zmq_msg_close(&eventMsg); -#ifdef ZMQ_EVENT_MONITOR_STOPPED - void abort() - { - if (_socket) - zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0); + return true; + } - _socket = socket_ref(); - } -#endif - virtual void on_monitor_started() {} - virtual void on_event_connected(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_connect_delayed(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_connect_retried(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_listening(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_bind_failed(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_accepted(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_accept_failed(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_closed(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_close_failed(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_disconnected(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } +#ifdef ZMQ_EVENT_MONITOR_STOPPED + void abort() + { + if (_socket) + zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0); + + _socket = socket_ref(); + } +#endif + virtual void on_monitor_started() + { + } + virtual void on_event_connected(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_connect_delayed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_connect_retried(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_listening(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_bind_failed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_accepted(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_accept_failed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_closed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_close_failed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_disconnected(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3) - virtual void on_event_handshake_failed_no_detail(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_handshake_failed_protocol(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_handshake_failed_auth(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_handshake_succeeded(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } + virtual void on_event_handshake_failed_no_detail(const zmq_event_t& event_, + const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_handshake_failed_protocol(const zmq_event_t& event_, + const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_handshake_failed_auth(const zmq_event_t& event_, + const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_handshake_succeeded(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } #elif ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 1) - virtual void on_event_handshake_failed(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } - virtual void on_event_handshake_succeed(const zmq_event_t &event_, - const char *addr_) - { - (void) event_; - (void) addr_; - } -#endif - virtual void on_event_unknown(const zmq_event_t &event_, const char *addr_) - { - (void) event_; - (void) addr_; - } - - private: - monitor_t(const monitor_t &) ZMQ_DELETED_FUNCTION; - void operator=(const monitor_t &) ZMQ_DELETED_FUNCTION; - - socket_ref _socket; - socket_t _monitor_socket; - - void close() ZMQ_NOTHROW - { - if (_socket) - zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0); - _monitor_socket.close(); - } + virtual void on_event_handshake_failed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + virtual void on_event_handshake_succeed(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } +#endif + virtual void on_event_unknown(const zmq_event_t& event_, const char* addr_) + { + (void)event_; + (void)addr_; + } + +private: + monitor_t(const monitor_t&) ZMQ_DELETED_FUNCTION; + void operator=(const monitor_t&) ZMQ_DELETED_FUNCTION; + + socket_ref _socket; + socket_t _monitor_socket; + + void close() ZMQ_NOTHROW + { + if (_socket) + zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0); + _monitor_socket.close(); + } }; #if defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER) @@ -2552,135 +2707,135 @@ class monitor_t // polling events enum class event_flags : short { - none = 0, - pollin = ZMQ_POLLIN, - pollout = ZMQ_POLLOUT, - pollerr = ZMQ_POLLERR, - pollpri = ZMQ_POLLPRI + none = 0, + pollin = ZMQ_POLLIN, + pollout = ZMQ_POLLOUT, + pollerr = ZMQ_POLLERR, + pollpri = ZMQ_POLLPRI }; constexpr event_flags operator|(event_flags a, event_flags b) noexcept { - return detail::enum_bit_or(a, b); + return detail::enum_bit_or(a, b); } constexpr event_flags operator&(event_flags a, event_flags b) noexcept { - return detail::enum_bit_and(a, b); + return detail::enum_bit_and(a, b); } constexpr event_flags operator^(event_flags a, event_flags b) noexcept { - return detail::enum_bit_xor(a, b); + return detail::enum_bit_xor(a, b); } constexpr event_flags operator~(event_flags a) noexcept { - return detail::enum_bit_not(a); + return detail::enum_bit_not(a); } struct no_user_data; // layout compatible with zmq_poller_event_t -template struct poller_event +template +struct poller_event { - socket_ref socket; + socket_ref socket; #ifdef _WIN32 - SOCKET fd; + SOCKET fd; #else - int fd; + int fd; #endif - T *user_data; - event_flags events; + T* user_data; + event_flags events; }; -template class poller_t +template +class poller_t { - public: - using event_type = poller_event; +public: + using event_type = poller_event; - poller_t() : poller_ptr(zmq_poller_new()) - { - if (!poller_ptr) - throw error_t(); - } + poller_t() : poller_ptr(zmq_poller_new()) + { + if (!poller_ptr) + throw error_t(); + } - template< - typename Dummy = void, - typename = - typename std::enable_if::value, Dummy>::type> - void add(zmq::socket_ref socket, event_flags events, T *user_data) - { - add_impl(socket, events, user_data); - } + template ::value, + Dummy>::type> + void add(zmq::socket_ref socket, event_flags events, T* user_data) + { + add_impl(socket, events, user_data); + } - void add(zmq::socket_ref socket, event_flags events) - { - add_impl(socket, events, nullptr); - } + void add(zmq::socket_ref socket, event_flags events) + { + add_impl(socket, events, nullptr); + } - void remove(zmq::socket_ref socket) + void remove(zmq::socket_ref socket) + { + if (0 != zmq_poller_remove(poller_ptr.get(), socket.handle())) { - if (0 != zmq_poller_remove(poller_ptr.get(), socket.handle())) { - throw error_t(); - } + throw error_t(); } + } - void modify(zmq::socket_ref socket, event_flags events) + void modify(zmq::socket_ref socket, event_flags events) + { + if (0 != + zmq_poller_modify(poller_ptr.get(), socket.handle(), static_cast(events))) { - if (0 - != zmq_poller_modify(poller_ptr.get(), socket.handle(), - static_cast(events))) { - throw error_t(); - } + throw error_t(); } + } - size_t wait_all(std::vector &poller_events, - const std::chrono::milliseconds timeout) - { - int rc = zmq_poller_wait_all( - poller_ptr.get(), - reinterpret_cast(poller_events.data()), - static_cast(poller_events.size()), - static_cast(timeout.count())); - if (rc > 0) - return static_cast(rc); + size_t wait_all(std::vector& poller_events, + const std::chrono::milliseconds timeout) + { + int rc = zmq_poller_wait_all( + poller_ptr.get(), reinterpret_cast(poller_events.data()), + static_cast(poller_events.size()), static_cast(timeout.count())); + if (rc > 0) + return static_cast(rc); #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3) - if (zmq_errno() == EAGAIN) + if (zmq_errno() == EAGAIN) #else - if (zmq_errno() == ETIMEDOUT) + if (zmq_errno() == ETIMEDOUT) #endif - return 0; + return 0; - throw error_t(); - } + throw error_t(); + } - private: - struct destroy_poller_t +private: + struct destroy_poller_t + { + void operator()(void* ptr) noexcept { - void operator()(void *ptr) noexcept - { - int rc = zmq_poller_destroy(&ptr); - ZMQ_ASSERT(rc == 0); - } - }; + int rc = zmq_poller_destroy(&ptr); + ZMQ_ASSERT(rc == 0); + } + }; - std::unique_ptr poller_ptr; + std::unique_ptr poller_ptr; - void add_impl(zmq::socket_ref socket, event_flags events, T *user_data) + void add_impl(zmq::socket_ref socket, event_flags events, T* user_data) + { + if (0 != zmq_poller_add(poller_ptr.get(), socket.handle(), user_data, + static_cast(events))) { - if (0 - != zmq_poller_add(poller_ptr.get(), socket.handle(), user_data, - static_cast(events))) { - throw error_t(); - } + throw error_t(); } + } }; -#endif // defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER) +#endif // defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER) -inline std::ostream &operator<<(std::ostream &os, const message_t &msg) +inline std::ostream& operator<<(std::ostream& os, const message_t& msg) { - return os << msg.str(); + return os << msg.str(); } -} // namespace zmq +} // namespace zmq -#endif // __ZMQ_HPP_INCLUDED__ +#endif // __ZMQ_HPP_INCLUDED__ diff --git a/plotjuggler_plugins/ParserDataTamer/datatamer_parser.cpp b/plotjuggler_plugins/ParserDataTamer/datatamer_parser.cpp index 0496c2977..ef181b8a6 100644 --- a/plotjuggler_plugins/ParserDataTamer/datatamer_parser.cpp +++ b/plotjuggler_plugins/ParserDataTamer/datatamer_parser.cpp @@ -7,16 +7,12 @@ using namespace PJ; - -class MsgParserImpl: public MessageParser +class MsgParserImpl : public MessageParser { - public: - MsgParserImpl(const std::string &topic_name, - const std::string &type_name, - const std::string &schema, - PJ::PlotDataMapRef &data): - MessageParser(topic_name, data), - topic_name_(topic_name) +public: + MsgParserImpl(const std::string& topic_name, const std::string& type_name, + const std::string& schema, PJ::PlotDataMapRef& data) + : MessageParser(topic_name, data), topic_name_(topic_name) { schema_ = DataTamerParser::BuilSchemaFromText(schema); } @@ -24,22 +20,20 @@ class MsgParserImpl: public MessageParser bool parseMessage(const MessageRef serialized_msg, double& timestamp) override { auto callback = [this, timestamp](const std::string& series_name, - const DataTamerParser::VarNumber& var) - { + const DataTamerParser::VarNumber& var) { auto name = fmt::format("{}/{}", topic_name_, series_name); auto& plot_data = _plot_data.getOrCreateNumeric(name); - double value = std::visit([](auto&& v) { return static_cast(v); }, - var); + double value = std::visit([](auto&& v) { return static_cast(v); }, var); - plot_data.pushBack({timestamp, value}); + plot_data.pushBack({ timestamp, value }); }; DataTamerParser::SnapshotView snapshot; snapshot.schema_hash = schema_.hash; - DataTamerParser::BufferSpan msg_buffer = - { serialized_msg.data(), serialized_msg.size() }; + DataTamerParser::BufferSpan msg_buffer = { serialized_msg.data(), + serialized_msg.size() }; const uint32_t mask_size = DataTamerParser::Deserialize(msg_buffer); snapshot.active_mask.data = msg_buffer.data; @@ -54,11 +48,11 @@ class MsgParserImpl: public MessageParser return true; } - private: - +private: DataTamerParser::Schema schema_; - struct TimeSeries { + struct TimeSeries + { std::string name; DataTamerParser::BasicType type; PlotData* plot_data = nullptr; @@ -68,11 +62,10 @@ class MsgParserImpl: public MessageParser std::vector timeseries_; }; - -MessageParserPtr ParserDataTamer::createParser(const std::string &topic_name, - const std::string &type_name, - const std::string &schema, - PJ::PlotDataMapRef &data) +MessageParserPtr ParserDataTamer::createParser(const std::string& topic_name, + const std::string& type_name, + const std::string& schema, + PJ::PlotDataMapRef& data) { return std::make_shared(topic_name, type_name, schema, data); } diff --git a/plotjuggler_plugins/ParserDataTamer/datatamer_parser.h b/plotjuggler_plugins/ParserDataTamer/datatamer_parser.h index f915e2934..926ede7b3 100644 --- a/plotjuggler_plugins/ParserDataTamer/datatamer_parser.h +++ b/plotjuggler_plugins/ParserDataTamer/datatamer_parser.h @@ -6,14 +6,13 @@ #include #include - class ParserDataTamer : public PJ::ParserFactoryPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "facontidavide.PlotJuggler3.ParserFactoryPlugin") Q_INTERFACES(PJ::ParserFactoryPlugin) - public: +public: ParserDataTamer() = default; const char* name() const override @@ -30,6 +29,3 @@ class ParserDataTamer : public PJ::ParserFactoryPlugin const std::string& schema, PJ::PlotDataMapRef& data) override; }; - - - diff --git a/plotjuggler_plugins/ParserProtobuf/error_collectors.cpp b/plotjuggler_plugins/ParserProtobuf/error_collectors.cpp index 3a8ce8831..761e0b739 100644 --- a/plotjuggler_plugins/ParserProtobuf/error_collectors.cpp +++ b/plotjuggler_plugins/ParserProtobuf/error_collectors.cpp @@ -2,37 +2,38 @@ #include #include -void FileErrorCollector::AddError(const std::string &filename, int line, int, const std::string &message) +void FileErrorCollector::AddError(const std::string& filename, int line, int, + const std::string& message) { auto msg = QString("File: [%1] Line: [%2] Message: %3\n\n") - .arg(QString::fromStdString(filename)) - .arg(line) - .arg(QString::fromStdString(message)); + .arg(QString::fromStdString(filename)) + .arg(line) + .arg(QString::fromStdString(message)); _errors.push_back(msg); } -void FileErrorCollector::AddWarning(const std::string &filename, int line, int, const std::string &message) +void FileErrorCollector::AddWarning(const std::string& filename, int line, int, + const std::string& message) { auto msg = QString("Warning [%1] line %2: %3") - .arg(QString::fromStdString(filename)) - .arg(line) - .arg(QString::fromStdString(message)); + .arg(QString::fromStdString(filename)) + .arg(line) + .arg(QString::fromStdString(message)); qDebug() << msg; } void IoErrorCollector::AddError(int line, google::protobuf::io::ColumnNumber, - const std::string &message) + const std::string& message) { - _errors.push_back(QString("Line: [%1] Message: %2\n") - .arg(line) - .arg(QString::fromStdString(message)) ); + _errors.push_back( + QString("Line: [%1] Message: %2\n").arg(line).arg(QString::fromStdString(message))); } -void IoErrorCollector::AddWarning(int line, google::protobuf::io::ColumnNumber column, const std::string &message) +void IoErrorCollector::AddWarning(int line, google::protobuf::io::ColumnNumber column, + const std::string& message) { - qDebug() << QString("Line: [%1] Message: %2\n") - .arg(line) - .arg(QString::fromStdString(message)); + qDebug() << QString("Line: [%1] Message: %2\n") + .arg(line) + .arg(QString::fromStdString(message)); } - diff --git a/plotjuggler_plugins/ParserProtobuf/error_collectors.h b/plotjuggler_plugins/ParserProtobuf/error_collectors.h index 752321904..f70a881f5 100644 --- a/plotjuggler_plugins/ParserProtobuf/error_collectors.h +++ b/plotjuggler_plugins/ParserProtobuf/error_collectors.h @@ -1,13 +1,12 @@ #ifndef ERROR_COLLECTORS_H #define ERROR_COLLECTORS_H - #include #include #include -class IoErrorCollector: public google::protobuf::io::ErrorCollector +class IoErrorCollector : public google::protobuf::io::ErrorCollector { public: void AddError(int line, google::protobuf::io::ColumnNumber column, @@ -25,7 +24,7 @@ class IoErrorCollector: public google::protobuf::io::ErrorCollector QStringList _errors; }; -class FileErrorCollector: public google::protobuf::compiler::MultiFileErrorCollector +class FileErrorCollector : public google::protobuf::compiler::MultiFileErrorCollector { public: void AddError(const std::string& filename, int line, int, @@ -43,4 +42,4 @@ class FileErrorCollector: public google::protobuf::compiler::MultiFileErrorColle QStringList _errors; }; -#endif // ERROR_COLLECTORS_H +#endif // ERROR_COLLECTORS_H diff --git a/plotjuggler_plugins/ParserProtobuf/protobuf_factory.cpp b/plotjuggler_plugins/ParserProtobuf/protobuf_factory.cpp index 54cddecdf..f521d7155 100644 --- a/plotjuggler_plugins/ParserProtobuf/protobuf_factory.cpp +++ b/plotjuggler_plugins/ParserProtobuf/protobuf_factory.cpp @@ -8,7 +8,6 @@ namespace gp = google::protobuf; - ParserFactoryProtobuf::ParserFactoryProtobuf() { _widget = new QWidget(nullptr); @@ -24,30 +23,32 @@ ParserFactoryProtobuf::ParserFactoryProtobuf() QString theme = settings.value("Preferences::theme", "light").toString(); ui->pushButtonRemove->setIcon(LoadSvg(":/resources/svg/trash.svg", theme)); - connect( ui->pushButtonInclude, &QPushButton::clicked, this, &ParserFactoryProtobuf::onIncludeDirectory); - connect( ui->pushButtonLoad, &QPushButton::clicked, this, &ParserFactoryProtobuf::onLoadFile); - connect( ui->pushButtonRemove, &QPushButton::clicked, this, &ParserFactoryProtobuf::onRemoveInclude); + connect(ui->pushButtonInclude, &QPushButton::clicked, this, + &ParserFactoryProtobuf::onIncludeDirectory); + connect(ui->pushButtonLoad, &QPushButton::clicked, this, + &ParserFactoryProtobuf::onLoadFile); + connect(ui->pushButtonRemove, &QPushButton::clicked, this, + &ParserFactoryProtobuf::onRemoveInclude); QString last_type = settings.value("ProtobufParserCreator.lastType").toString(); int combo_index = ui->comboBox->findText(last_type, Qt::MatchExactly); - if( !last_type.isEmpty() && combo_index != -1) + if (!last_type.isEmpty() && combo_index != -1) { ui->comboBox->setCurrentIndex(combo_index); onComboChanged(last_type); } - connect( ui->comboBox, qOverload(&QComboBox::currentIndexChanged), - this, &ParserFactoryProtobuf::onComboChanged ); + connect(ui->comboBox, qOverload(&QComboBox::currentIndexChanged), this, + &ParserFactoryProtobuf::onComboChanged); } void ParserFactoryProtobuf::importFile(QString filename) { QFile file(filename); - if( !file.exists() ) + if (!file.exists()) { QMessageBox::warning(nullptr, tr("Error loading file"), - tr("File %1 does not exist").arg(filename), - QMessageBox::Cancel); + tr("File %1 does not exist").arg(filename), QMessageBox::Cancel); return; } file.open(QIODevice::ReadOnly); @@ -63,16 +64,15 @@ void ParserFactoryProtobuf::importFile(QString filename) FileErrorCollector error_collector; - _importer.reset( new gp::compiler::Importer(&_source_tree, &error_collector) ); + _importer.reset(new gp::compiler::Importer(&_source_tree, &error_collector)); info.file_descriptor = _importer->Import(file_basename.toStdString()); - if( !info.file_descriptor ) + if (!info.file_descriptor) { - if(error_collector.errors().size() > 0) + if (error_collector.errors().size() > 0) { QMessageBox::warning(nullptr, "Error parsing Proto file", - error_collector.errors().front(), - QMessageBox::Cancel); + error_collector.errors().front(), QMessageBox::Cancel); } return; } @@ -81,12 +81,12 @@ void ParserFactoryProtobuf::importFile(QString filename) ui->protoPreview->setText(info.proto_text); ui->comboBox->clear(); - for(int i=0; i < info.file_descriptor->message_type_count(); i++) + for (int i = 0; i < info.file_descriptor->message_type_count(); i++) { const std::string& type_name = info.file_descriptor->message_type(i)->name(); auto descriptor = info.file_descriptor->FindMessageTypeByName(type_name); QString type_qname = QString::fromStdString(type_name); - info.descriptors.insert({type_qname, descriptor }); + info.descriptors.insert({ type_qname, descriptor }); ui->comboBox->addItem(type_qname); } _loaded_file = std::move(info); @@ -100,7 +100,7 @@ void ParserFactoryProtobuf::loadSettings() QSettings settings; auto include_list = settings.value("ProtobufParserCreator.include_dirs").toStringList(); - for (const auto& include_dir: include_list) + for (const auto& include_dir : include_list) { QDir path_dir(include_dir); if (path_dir.exists()) @@ -112,7 +112,8 @@ void ParserFactoryProtobuf::loadSettings() ui->listWidget->sortItems(); auto filename = settings.value("ProtobufParserCreator.protofile").toString(); - if( !filename.isEmpty() ){ + if (!filename.isEmpty()) + { importFile(filename); } } @@ -121,7 +122,7 @@ void ParserFactoryProtobuf::saveSettings() { QSettings settings; QStringList include_list; - for (int row=0; rowlistWidget->count(); row++) + for (int row = 0; row < ui->listWidget->count(); row++) { include_list += ui->listWidget->item(row)->text(); } @@ -139,18 +140,17 @@ MessageParserPtr ParserFactoryProtobuf::createParser(const std::string& topic_na const std::string& schema, PlotDataMapRef& data) { - QString descriptor_name = type_name.empty() ? - ui->comboBox->currentText() : - QString::fromStdString(type_name); - if( schema.empty() ) + QString descriptor_name = + type_name.empty() ? ui->comboBox->currentText() : QString::fromStdString(type_name); + if (schema.empty()) { auto descr_it = _loaded_file.descriptors.find(descriptor_name); - if( descr_it == _loaded_file.descriptors.end()) + if (descr_it == _loaded_file.descriptors.end()) { throw std::runtime_error("ParserFactoryProtobuf: can't find the descriptor"); } auto selected_descriptor = descr_it->second; - return std::make_shared(topic_name, selected_descriptor, data ); + return std::make_shared(topic_name, selected_descriptor, data); } else { @@ -160,7 +160,7 @@ MessageParserPtr ParserFactoryProtobuf::createParser(const std::string& topic_na throw std::runtime_error("failed to parse schema data"); } - return std::make_shared(topic_name, type_name, field_set, data ); + return std::make_shared(topic_name, type_name, field_set, data); } } @@ -168,17 +168,19 @@ void ParserFactoryProtobuf::onIncludeDirectory() { QSettings settings; QString directory_path = - settings.value("ProtobufParserCreator.loadDirectory", QDir::currentPath()).toString(); + settings.value("ProtobufParserCreator.loadDirectory", QDir::currentPath()) + .toString(); - QString dirname = QFileDialog::getExistingDirectory(_widget, tr("Load StyleSheet"), directory_path); + QString dirname = + QFileDialog::getExistingDirectory(_widget, tr("Load StyleSheet"), directory_path); if (dirname.isEmpty()) { return; } settings.setValue("ProtobufParserCreator.loadDirectory", dirname); - if( ui->listWidget->findItems(dirname, Qt::MatchExactly).empty() ) + if (ui->listWidget->findItems(dirname, Qt::MatchExactly).empty()) { - ui->listWidget->addItem( dirname ); + ui->listWidget->addItem(dirname); ui->listWidget->sortItems(); } } @@ -188,7 +190,8 @@ void ParserFactoryProtobuf::onLoadFile() QSettings settings; QString directory_path = - settings.value("ProtobufParserCreator.loadDirectory", QDir::currentPath()).toString(); + settings.value("ProtobufParserCreator.loadDirectory", QDir::currentPath()) + .toString(); QString filename = QFileDialog::getOpenFileName(_widget, tr("Load StyleSheet"), directory_path, tr("(*.proto)")); @@ -209,7 +212,7 @@ void ParserFactoryProtobuf::onRemoveInclude() { auto selected = ui->listWidget->selectedItems(); - while(!selected.isEmpty()) + while (!selected.isEmpty()) { auto item = selected.front(); delete ui->listWidget->takeItem(ui->listWidget->row(item)); @@ -219,16 +222,12 @@ void ParserFactoryProtobuf::onRemoveInclude() loadSettings(); } - void ParserFactoryProtobuf::onComboChanged(const QString& text) { auto descr_it = _loaded_file.descriptors.find(text); - if( descr_it != _loaded_file.descriptors.end()) + if (descr_it != _loaded_file.descriptors.end()) { QSettings settings; settings.setValue("ProtobufParserCreator.lastType", text); } } - - - diff --git a/plotjuggler_plugins/ParserProtobuf/protobuf_factory.h b/plotjuggler_plugins/ParserProtobuf/protobuf_factory.h index 20090b323..8dabce24e 100644 --- a/plotjuggler_plugins/ParserProtobuf/protobuf_factory.h +++ b/plotjuggler_plugins/ParserProtobuf/protobuf_factory.h @@ -27,8 +27,7 @@ class ParserFactoryProtobuf : public PJ::ParserFactoryPlugin } MessageParserPtr createParser(const std::string& topic_name, - const std::string& type_name, - const std::string& schema, + const std::string& type_name, const std::string& schema, PlotDataMapRef& data) override; QWidget* optionsWidget() override @@ -37,7 +36,6 @@ class ParserFactoryProtobuf : public PJ::ParserFactoryPlugin } protected: - Ui::ProtobufLoader* ui; QWidget* _widget; @@ -49,7 +47,7 @@ class ParserFactoryProtobuf : public PJ::ParserFactoryPlugin QString file_path; QByteArray proto_text; const google::protobuf::FileDescriptor* file_descriptor = nullptr; - std::map descriptors; + std::map descriptors; }; FileInfo _loaded_file; @@ -69,8 +67,7 @@ private slots: void onRemoveInclude(); - void onComboChanged(const QString &text); + void onComboChanged(const QString& text); }; - -#endif // PROTOBUF_FACTORY_H +#endif // PROTOBUF_FACTORY_H diff --git a/plotjuggler_plugins/ParserProtobuf/protobuf_parser.cpp b/plotjuggler_plugins/ParserProtobuf/protobuf_parser.cpp index 99c33348b..251141e21 100644 --- a/plotjuggler_plugins/ParserProtobuf/protobuf_parser.cpp +++ b/plotjuggler_plugins/ParserProtobuf/protobuf_parser.cpp @@ -4,17 +4,13 @@ #include "PlotJuggler/fmt/format.h" #include "PlotJuggler/svg_util.h" - namespace gp = google::protobuf; -ProtobufParser::ProtobufParser(const std::string &topic_name, - const std::string type_name, - const gp::FileDescriptorSet &descriptor_set, - PlotDataMapRef &data) - : MessageParser(topic_name, data) - , _proto_pool(&_proto_database) +ProtobufParser::ProtobufParser(const std::string& topic_name, const std::string type_name, + const gp::FileDescriptorSet& descriptor_set, + PlotDataMapRef& data) + : MessageParser(topic_name, data), _proto_pool(&_proto_database) { - gp::FileDescriptorProto unused; for (int i = 0; i < descriptor_set.file_size(); ++i) @@ -25,8 +21,7 @@ ProtobufParser::ProtobufParser(const std::string &topic_name, if (!_proto_database.Add(file)) { throw std::runtime_error( - fmt::format("failed to add definition {} to protoDB", - file.name())); + fmt::format("failed to add definition {} to protoDB", file.name())); } } } @@ -39,44 +34,46 @@ ProtobufParser::ProtobufParser(const std::string &topic_name, } } -bool ProtobufParser::parseMessage(const MessageRef serialized_msg, - double ×tamp) +bool ProtobufParser::parseMessage(const MessageRef serialized_msg, double& timestamp) { const google::protobuf::Message* prototype_msg = _msg_factory.GetPrototype(_msg_descriptor); google::protobuf::Message* mutable_msg = prototype_msg->New(); - if (!mutable_msg->ParseFromArray(serialized_msg.data(), - serialized_msg.size())) + if (!mutable_msg->ParseFromArray(serialized_msg.data(), serialized_msg.size())) { return false; } - std::function ParseImpl; + std::function + ParseImpl; - ParseImpl = [&](const google::protobuf::Message& msg, const std::string& prefix, const bool is_map) - { + ParseImpl = [&](const google::protobuf::Message& msg, const std::string& prefix, + const bool is_map) { const gp::Reflection* reflection = msg.GetReflection(); const gp::Descriptor* descriptor = msg.GetDescriptor(); // std::vector reflection_fields; // reflection->ListFields(msg, &reflection_fields); - for (int index=0; index < descriptor->field_count(); index++) + for (int index = 0; index < descriptor->field_count(); index++) { auto field = descriptor->field(index); - std::string key = prefix.empty() ? - field->name(): - fmt::format("{}/{}", prefix, field->name() ); - if (is_map) { - // Map messages only have 2 fields: key and value. The key will be represented in the - // series name so skip it, and don't uselessly append "value" to the series name for - // the value. - if (field->name() == "key") { - continue; - } else { - key = prefix; - } + std::string key = + prefix.empty() ? field->name() : fmt::format("{}/{}", prefix, field->name()); + if (is_map) + { + // Map messages only have 2 fields: key and value. The key will be represented in + // the series name so skip it, and don't uselessly append "value" to the series + // name for the value. + if (field->name() == "key") + { + continue; + } + else + { + key = prefix; + } } std::string suffix; @@ -94,133 +91,149 @@ bool ProtobufParser::parseMessage(const MessageRef serialized_msg, repeated = true; } - if( repeated && count > maxArraySize() ) + if (repeated && count > maxArraySize()) { - if(clampLargeArray()) + if (clampLargeArray()) { count = std::max(count, maxArraySize()); } - else{ + else + { continue; } } - for(unsigned index = 0; index < count ; index++) + for (unsigned index = 0; index < count; index++) { - if(repeated) + if (repeated) { suffix = fmt::format("[{}]", index); } bool is_double = true; double value = 0; - switch(field->cpp_type()) + switch (field->cpp_type()) { - case gp::FieldDescriptor::CPPTYPE_DOUBLE:{ + case gp::FieldDescriptor::CPPTYPE_DOUBLE: { value = !repeated ? reflection->GetDouble(msg, field) : reflection->GetRepeatedDouble(msg, field, index); - }break; - case gp::FieldDescriptor::CPPTYPE_FLOAT:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_FLOAT: { auto tmp = !repeated ? reflection->GetFloat(msg, field) : reflection->GetRepeatedFloat(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_UINT32:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_UINT32: { auto tmp = !repeated ? reflection->GetUInt32(msg, field) : reflection->GetRepeatedUInt32(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_UINT64:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_UINT64: { auto tmp = !repeated ? reflection->GetUInt64(msg, field) : reflection->GetRepeatedUInt64(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_BOOL:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_BOOL: { auto tmp = !repeated ? reflection->GetBool(msg, field) : reflection->GetRepeatedBool(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_INT32:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_INT32: { auto tmp = !repeated ? reflection->GetInt32(msg, field) : reflection->GetRepeatedInt32(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_INT64:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_INT64: { auto tmp = !repeated ? reflection->GetInt64(msg, field) : reflection->GetRepeatedInt64(msg, field, index); value = static_cast(tmp); - }break; - case gp::FieldDescriptor::CPPTYPE_ENUM:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_ENUM: { auto tmp = !repeated ? reflection->GetEnum(msg, field) : reflection->GetRepeatedEnum(msg, field, index); auto& series = this->getStringSeries(key + suffix); - series.pushBack({timestamp, tmp->name()}); + series.pushBack({ timestamp, tmp->name() }); is_double = false; - }break; - case gp::FieldDescriptor::CPPTYPE_STRING:{ + } + break; + case gp::FieldDescriptor::CPPTYPE_STRING: { auto tmp = !repeated ? reflection->GetString(msg, field) : reflection->GetRepeatedString(msg, field, index); - if( tmp.size() > 100 ) + if (tmp.size() > 100) { // probably a blob, skip it continue; } auto& series = this->getStringSeries(key + suffix); - series.pushBack({timestamp, tmp}); + series.pushBack({ timestamp, tmp }); is_double = false; - }break; - case gp::FieldDescriptor::CPPTYPE_MESSAGE: - { + } + break; + case gp::FieldDescriptor::CPPTYPE_MESSAGE: { // Fix macro issue in Windows #pragma push_macro("GetMessage") #undef GetMessage const auto& new_msg = repeated ? - reflection->GetRepeatedMessage(msg, field, index) : - reflection->GetMessage(msg, field); + reflection->GetRepeatedMessage(msg, field, index) : + reflection->GetMessage(msg, field); #pragma pop_macro("GetMessage") - if (field->is_map()) { - // A protobuf map looks just like a message but with a "key" and - // "value" field, extract the key so we can set a useful suffix. - const auto* map_descriptor = new_msg.GetDescriptor(); - const auto* map_reflection = new_msg.GetReflection(); - const auto* key_field = map_descriptor->FindFieldByName("key"); - switch(key_field->cpp_type()) - { - // A map's key is a scalar type (except floats and bytes) or a string - case gp::FieldDescriptor::CPPTYPE_STRING:{ - suffix = fmt::format( - "/{}", map_reflection->GetString(new_msg, key_field)); - }break; - case gp::FieldDescriptor::CPPTYPE_INT32:{ - suffix = fmt::format( - "/{}", map_reflection->GetInt32(new_msg, key_field)); - }break; - case gp::FieldDescriptor::CPPTYPE_INT64:{ - suffix = fmt::format( - "/{}", map_reflection->GetInt64(new_msg, key_field)); - }break; - case gp::FieldDescriptor::CPPTYPE_UINT32:{ - suffix = fmt::format( - "/{}", map_reflection->GetUInt32(new_msg, key_field)); - }break; - case gp::FieldDescriptor::CPPTYPE_UINT64:{ - suffix = fmt::format( - "/{}", map_reflection->GetUInt64(new_msg, key_field)); - }break; + if (field->is_map()) + { + // A protobuf map looks just like a message but with a "key" and + // "value" field, extract the key so we can set a useful suffix. + const auto* map_descriptor = new_msg.GetDescriptor(); + const auto* map_reflection = new_msg.GetReflection(); + const auto* key_field = map_descriptor->FindFieldByName("key"); + switch (key_field->cpp_type()) + { + // A map's key is a scalar type (except floats and bytes) or a string + case gp::FieldDescriptor::CPPTYPE_STRING: { + suffix = + fmt::format("/{}", map_reflection->GetString(new_msg, key_field)); } + break; + case gp::FieldDescriptor::CPPTYPE_INT32: { + suffix = + fmt::format("/{}", map_reflection->GetInt32(new_msg, key_field)); + } + break; + case gp::FieldDescriptor::CPPTYPE_INT64: { + suffix = + fmt::format("/{}", map_reflection->GetInt64(new_msg, key_field)); + } + break; + case gp::FieldDescriptor::CPPTYPE_UINT32: { + suffix = + fmt::format("/{}", map_reflection->GetUInt32(new_msg, key_field)); + } + break; + case gp::FieldDescriptor::CPPTYPE_UINT64: { + suffix = + fmt::format("/{}", map_reflection->GetUInt64(new_msg, key_field)); + } + break; + } } ParseImpl(new_msg, key + suffix, field->is_map()); is_double = false; - }break; + } + break; } - if( is_double ) + if (is_double) { auto& series = this->getSeries(key + suffix); - series.pushBack({timestamp, value}); + series.pushBack({ timestamp, value }); } } } @@ -228,8 +241,7 @@ bool ProtobufParser::parseMessage(const MessageRef serialized_msg, // start recursion ParseImpl(*mutable_msg, _topic_name, false); - + delete mutable_msg; return true; } - diff --git a/plotjuggler_plugins/ParserProtobuf/protobuf_parser.h b/plotjuggler_plugins/ParserProtobuf/protobuf_parser.h index fd8549f3a..44f06f873 100644 --- a/plotjuggler_plugins/ParserProtobuf/protobuf_parser.h +++ b/plotjuggler_plugins/ParserProtobuf/protobuf_parser.h @@ -1,6 +1,5 @@ #pragma once - #include #include @@ -19,30 +18,23 @@ class ProtobufParser : public MessageParser { public: ProtobufParser(const std::string& topic_name, - const google::protobuf::Descriptor* descriptor, - PlotDataMapRef& data) + const google::protobuf::Descriptor* descriptor, PlotDataMapRef& data) : MessageParser(topic_name, data) , _proto_pool(&_proto_database) , _msg_descriptor(descriptor) { } - ProtobufParser(const std::string& topic_name, - const std::string type_name, + ProtobufParser(const std::string& topic_name, const std::string type_name, const google::protobuf::FileDescriptorSet& descriptor_set, PlotDataMapRef& data); bool parseMessage(const MessageRef serialized_msg, double& timestamp) override; protected: - google::protobuf::SimpleDescriptorDatabase _proto_database; google::protobuf::DescriptorPool _proto_pool; google::protobuf::DynamicMessageFactory _msg_factory; const google::protobuf::Descriptor* _msg_descriptor = nullptr; - }; - - - diff --git a/plotjuggler_plugins/ParserROS/ros1_parser.h b/plotjuggler_plugins/ParserROS/ros1_parser.h index df88be5be..1dd0d68c0 100644 --- a/plotjuggler_plugins/ParserROS/ros1_parser.h +++ b/plotjuggler_plugins/ParserROS/ros1_parser.h @@ -31,18 +31,15 @@ class ParserFactoryROS1 : public ParserFactoryPlugin } MessageParserPtr createParser(const std::string& topic_name, - const std::string& type_name, - const std::string& schema, + const std::string& type_name, const std::string& schema, PlotDataMapRef& data) override { - if(schema.empty()) + if (schema.empty()) { - throw std::runtime_error("ParserFactoryROS1 requires a schema (message definition)"); + throw std::runtime_error("ParserFactoryROS1 requires a schema (message " + "definition)"); } - return std::make_shared(topic_name, type_name, schema, + return std::make_shared(topic_name, type_name, schema, new RosMsgParser::ROS_Deserializer(), data); } }; - - - diff --git a/plotjuggler_plugins/ParserROS/ros2_parser.h b/plotjuggler_plugins/ParserROS/ros2_parser.h index ffc53afff..1ff5e87a4 100644 --- a/plotjuggler_plugins/ParserROS/ros2_parser.h +++ b/plotjuggler_plugins/ParserROS/ros2_parser.h @@ -31,20 +31,18 @@ class ParserFactoryROS2 : public ParserFactoryPlugin } MessageParserPtr createParser(const std::string& topic_name, - const std::string& type_name, - const std::string& schema, + const std::string& type_name, const std::string& schema, PlotDataMapRef& data) override { - if(schema.empty()) + if (schema.empty()) { - throw std::runtime_error("ParserFactoryROS2 requires a schema (message definition)"); + throw std::runtime_error("ParserFactoryROS2 requires a schema (message " + "definition)"); } - std::string msg_type = QString::fromStdString(type_name).replace("/msg/", "/").toStdString(); + std::string msg_type = + QString::fromStdString(type_name).replace("/msg/", "/").toStdString(); return std::make_shared(topic_name, msg_type, schema, new RosMsgParser::ROS2_Deserializer, data); } }; - - - diff --git a/plotjuggler_plugins/ParserROS/ros_parser.cpp b/plotjuggler_plugins/ParserROS/ros_parser.cpp index 6715a0c94..19f9acf78 100644 --- a/plotjuggler_plugins/ParserROS/ros_parser.cpp +++ b/plotjuggler_plugins/ParserROS/ros_parser.cpp @@ -5,79 +5,78 @@ using namespace PJ; using namespace RosMsgParser; -static ROSType quaternion_type( Msg::Quaternion::id() ); +static ROSType quaternion_type(Msg::Quaternion::id()); constexpr double RAD_TO_DEG = 180.0 / M_PI; static std::unordered_map _global_data_tamer_schemas; -ParserROS::ParserROS(const std::string& topic_name, - const std::string& type_name, - const std::string& schema, - RosMsgParser::Deserializer* deserializer, +ParserROS::ParserROS(const std::string& topic_name, const std::string& type_name, + const std::string& schema, RosMsgParser::Deserializer* deserializer, PlotDataMapRef& data) : MessageParser(topic_name, data) - ,_parser(topic_name, type_name, schema) - ,_deserializer(deserializer) - ,_topic(topic_name) + , _parser(topic_name, type_name, schema) + , _deserializer(deserializer) + , _topic(topic_name) { - auto policy = clampLargeArray() ? Parser::KEEP_LARGE_ARRAYS : - Parser::DISCARD_LARGE_ARRAYS; + auto policy = + clampLargeArray() ? Parser::KEEP_LARGE_ARRAYS : Parser::DISCARD_LARGE_ARRAYS; - _parser.setMaxArrayPolicy( policy, maxArraySize() ); + _parser.setMaxArrayPolicy(policy, maxArraySize()); using std::placeholders::_1; using std::placeholders::_2; - if( Msg::DiagnosticStatus::id() == type_name) + if (Msg::DiagnosticStatus::id() == type_name) { _customized_parser = std::bind(&ParserROS::parseDiagnosticMsg, this, _1, _2); } - else if( Msg::JointState::id() == type_name) + else if (Msg::JointState::id() == type_name) { _customized_parser = std::bind(&ParserROS::parseJointStateMsg, this, _1, _2); } - else if( Msg::TFMessage::id() == type_name) + else if (Msg::TFMessage::id() == type_name) { _customized_parser = std::bind(&ParserROS::parseTF2Msg, this, _1, _2); } - else if( Msg::DataTamerSchemas::id() == type_name) + else if (Msg::DataTamerSchemas::id() == type_name) { _customized_parser = std::bind(&ParserROS::parseDataTamerSchemasMsg, this, _1, _2); } - else if( Msg::DataTamerSnapshot::id() == type_name) + else if (Msg::DataTamerSnapshot::id() == type_name) { _customized_parser = std::bind(&ParserROS::parseDataTamerSnapshotMsg, this, _1, _2); } - else if( Msg::Imu::id() == type_name) + else if (Msg::Imu::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parseImu, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parseImu, this, _1, _2); } - else if( Msg::Pose::id() == type_name) + else if (Msg::Pose::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parsePose, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parsePose, this, _1, _2); } - else if( Msg::PoseStamped::id() == type_name) + else if (Msg::PoseStamped::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parsePoseStamped, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parsePoseStamped, this, _1, _2); } - else if( Msg::Odometry::id() == type_name) + else if (Msg::Odometry::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parseOdometry, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parseOdometry, this, _1, _2); } - else if( Msg::Transform::id() == type_name) + else if (Msg::Transform::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parseTransform, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parseTransform, this, _1, _2); } - else if( Msg::TransformStamped::id() == type_name) + else if (Msg::TransformStamped::id() == type_name) { - _customized_parser = std::bind(&ParserROS::parseTransformStamped, this, _1, _2); + _customized_parser = std::bind(&ParserROS::parseTransformStamped, this, _1, _2); } } -bool ParserROS::parseMessage(const PJ::MessageRef serialized_msg, double ×tamp) +bool ParserROS::parseMessage(const PJ::MessageRef serialized_msg, double& timestamp) { - if( _customized_parser ) + if (_customized_parser) { - _deserializer->init( Span(serialized_msg.data(), serialized_msg.size()) ); + _deserializer->init( + Span(serialized_msg.data(), serialized_msg.size())); _customized_parser(_topic_name, timestamp); return true; } @@ -86,18 +85,18 @@ bool ParserROS::parseMessage(const PJ::MessageRef serialized_msg, double ×t std::string series_name; - for(const auto& [key, str]: _flat_msg.name) + for (const auto& [key, str] : _flat_msg.name) { key.toStr(series_name); StringSeries& data = getStringSeries(series_name); - data.pushBack( {timestamp, str } ); + data.pushBack({ timestamp, str }); } - for(const auto& [key, value]: _flat_msg.value) + for (const auto& [key, value] : _flat_msg.value) { key.toStr(series_name); PlotData& data = getSeries(series_name); - data.pushBack( {timestamp, value.convert() } ); + data.pushBack({ timestamp, value.convert() }); } return true; } @@ -107,160 +106,159 @@ void ParserROS::setLargeArraysPolicy(bool clamp, unsigned max_size) auto policy = clamp ? RosMsgParser::Parser::KEEP_LARGE_ARRAYS : RosMsgParser::Parser::DISCARD_LARGE_ARRAYS; - _parser.setMaxArrayPolicy( policy, max_size ); + _parser.setMaxArrayPolicy(policy, max_size); MessageParser::setLargeArraysPolicy(clamp, max_size); } //------------------------------------------------------------------------ -Msg::Header ParserROS::parseHeader(const std::string &prefix, double& timestamp) +Msg::Header ParserROS::parseHeader(const std::string& prefix, double& timestamp) { - Msg::Header header; - const bool is_ros1 = dynamic_cast(_deserializer.get()) != nullptr; - // only ROS1 as the files header.seq - if( is_ros1 ) - { - header.seq = _deserializer->deserializeUInt32(); - } + Msg::Header header; + const bool is_ros1 = dynamic_cast(_deserializer.get()) != nullptr; + // only ROS1 as the files header.seq + if (is_ros1) + { + header.seq = _deserializer->deserializeUInt32(); + } - header.stamp.sec = _deserializer->deserializeUInt32(); - header.stamp.nanosec = _deserializer->deserializeUInt32(); + header.stamp.sec = _deserializer->deserializeUInt32(); + header.stamp.nanosec = _deserializer->deserializeUInt32(); - const double ts = double(header.stamp.sec) + 1e-9*double(header.stamp.nanosec); - if(useEmbeddedTimestamp()) { - timestamp = ts; - } + const double ts = double(header.stamp.sec) + 1e-9 * double(header.stamp.nanosec); + if (useEmbeddedTimestamp()) + { + timestamp = ts; + } - _deserializer->deserializeString(header.frame_id); + _deserializer->deserializeString(header.frame_id); - getSeries(prefix + "/header/stamp").pushBack( {timestamp, ts} ); - if( is_ros1 ) - { - getSeries(prefix + "/header/seq").pushBack( {timestamp, double(header.seq)} ); - } - getStringSeries(prefix + "/header/frame_id").pushBack( {timestamp, header.frame_id} ); + getSeries(prefix + "/header/stamp").pushBack({ timestamp, ts }); + if (is_ros1) + { + getSeries(prefix + "/header/seq").pushBack({ timestamp, double(header.seq) }); + } + getStringSeries(prefix + "/header/frame_id").pushBack({ timestamp, header.frame_id }); - return header; + return header; } -void ParserROS::parseVector3(const std::string &prefix, double& timestamp) +void ParserROS::parseVector3(const std::string& prefix, double& timestamp) { - auto x = _deserializer->deserialize(FLOAT64).convert(); - auto y = _deserializer->deserialize(FLOAT64).convert(); - auto z = _deserializer->deserialize(FLOAT64).convert(); - getSeries(prefix + "/x").pushBack( {timestamp, x} ); - getSeries(prefix + "/y").pushBack( {timestamp, y} ); - getSeries(prefix + "/z").pushBack( {timestamp, z} ); + auto x = _deserializer->deserialize(FLOAT64).convert(); + auto y = _deserializer->deserialize(FLOAT64).convert(); + auto z = _deserializer->deserialize(FLOAT64).convert(); + getSeries(prefix + "/x").pushBack({ timestamp, x }); + getSeries(prefix + "/y").pushBack({ timestamp, y }); + getSeries(prefix + "/z").pushBack({ timestamp, z }); } -void ParserROS::parsePoint(const std::string &prefix, double& timestamp) +void ParserROS::parsePoint(const std::string& prefix, double& timestamp) { - auto x = _deserializer->deserialize(FLOAT64).convert(); - auto y = _deserializer->deserialize(FLOAT64).convert(); - auto z = _deserializer->deserialize(FLOAT64).convert(); - getSeries(prefix + "/x").pushBack( {timestamp, x} ); - getSeries(prefix + "/y").pushBack( {timestamp, y} ); - getSeries(prefix + "/z").pushBack( {timestamp, z} ); + auto x = _deserializer->deserialize(FLOAT64).convert(); + auto y = _deserializer->deserialize(FLOAT64).convert(); + auto z = _deserializer->deserialize(FLOAT64).convert(); + getSeries(prefix + "/x").pushBack({ timestamp, x }); + getSeries(prefix + "/y").pushBack({ timestamp, y }); + getSeries(prefix + "/z").pushBack({ timestamp, z }); } -void ParserROS::parseQuaternion(const std::string &prefix, double& timestamp) +void ParserROS::parseQuaternion(const std::string& prefix, double& timestamp) { - PJ::Msg::Quaternion quat; - quat.x = _deserializer->deserialize(FLOAT64).convert(); - quat.y = _deserializer->deserialize(FLOAT64).convert(); - quat.z = _deserializer->deserialize(FLOAT64).convert(); - quat.w = _deserializer->deserialize(FLOAT64).convert(); - getSeries(prefix + "/x").pushBack( {timestamp, quat.x} ); - getSeries(prefix + "/y").pushBack( {timestamp, quat.y} ); - getSeries(prefix + "/z").pushBack( {timestamp, quat.z} ); - getSeries(prefix + "/z").pushBack( {timestamp, quat.w} ); - - auto rpy = Msg::QuaternionToRPY( quat ); - getSeries(prefix + "/roll").pushBack( {timestamp, rpy.roll} ); - getSeries(prefix + "/pitch").pushBack( {timestamp, rpy.pitch} ); - getSeries(prefix + "/yaw").pushBack( {timestamp, rpy.yaw} ); + PJ::Msg::Quaternion quat; + quat.x = _deserializer->deserialize(FLOAT64).convert(); + quat.y = _deserializer->deserialize(FLOAT64).convert(); + quat.z = _deserializer->deserialize(FLOAT64).convert(); + quat.w = _deserializer->deserialize(FLOAT64).convert(); + getSeries(prefix + "/x").pushBack({ timestamp, quat.x }); + getSeries(prefix + "/y").pushBack({ timestamp, quat.y }); + getSeries(prefix + "/z").pushBack({ timestamp, quat.z }); + getSeries(prefix + "/z").pushBack({ timestamp, quat.w }); + + auto rpy = Msg::QuaternionToRPY(quat); + getSeries(prefix + "/roll").pushBack({ timestamp, rpy.roll }); + getSeries(prefix + "/pitch").pushBack({ timestamp, rpy.pitch }); + getSeries(prefix + "/yaw").pushBack({ timestamp, rpy.yaw }); } - -void ParserROS::parseTwist(const std::string &prefix, double& timestamp) +void ParserROS::parseTwist(const std::string& prefix, double& timestamp) { - parseVector3(prefix + "/linear", timestamp); - parseVector3(prefix + "/angular", timestamp); + parseVector3(prefix + "/linear", timestamp); + parseVector3(prefix + "/angular", timestamp); } - -void ParserROS::parseTwistWithCovariance(const std::string &prefix, double& timestamp) +void ParserROS::parseTwistWithCovariance(const std::string& prefix, double& timestamp) { - parseTwist(prefix + "/twist", timestamp); - parseCovariance<6>(prefix + "/covariance", timestamp); + parseTwist(prefix + "/twist", timestamp); + parseCovariance<6>(prefix + "/covariance", timestamp); } -void ParserROS::parseTransform(const std::string &prefix, double& timestamp) +void ParserROS::parseTransform(const std::string& prefix, double& timestamp) { - parsePoint(prefix + "/translation", timestamp); - parseQuaternion(prefix + "/rotation", timestamp); + parsePoint(prefix + "/translation", timestamp); + parseQuaternion(prefix + "/rotation", timestamp); } -void ParserROS::parseTransformStamped(const std::string &prefix, double& timestamp) +void ParserROS::parseTransformStamped(const std::string& prefix, double& timestamp) { - parseHeader(prefix + "/header", timestamp); + parseHeader(prefix + "/header", timestamp); - std::string child_frame_id; - _deserializer->deserializeString(child_frame_id); - getStringSeries(prefix + "/child_frame_id").pushBack( {timestamp, child_frame_id} ); + std::string child_frame_id; + _deserializer->deserializeString(child_frame_id); + getStringSeries(prefix + "/child_frame_id").pushBack({ timestamp, child_frame_id }); - parseTransform(prefix + "/transform", timestamp); + parseTransform(prefix + "/transform", timestamp); } -void ParserROS::parsePose(const std::string &prefix, double ×tamp) +void ParserROS::parsePose(const std::string& prefix, double& timestamp) { - parseVector3(prefix + "/position", timestamp); - parseQuaternion(prefix + "/orientation", timestamp); + parseVector3(prefix + "/position", timestamp); + parseQuaternion(prefix + "/orientation", timestamp); } -void ParserROS::parsePoseStamped(const std::string &prefix, double ×tamp) +void ParserROS::parsePoseStamped(const std::string& prefix, double& timestamp) { - parseHeader(prefix + "/header", timestamp); - parsePose(prefix + "/pose", timestamp); + parseHeader(prefix + "/header", timestamp); + parsePose(prefix + "/pose", timestamp); } -void ParserROS::parsePoseWithCovariance(const std::string &prefix, double ×tamp) +void ParserROS::parsePoseWithCovariance(const std::string& prefix, double& timestamp) { - parsePose(prefix + "/pose", timestamp); - parseCovariance<6>(prefix + "/covariance", timestamp); + parsePose(prefix + "/pose", timestamp); + parseCovariance<6>(prefix + "/covariance", timestamp); } -void ParserROS::parseImu(const std::string &prefix, double ×tamp) +void ParserROS::parseImu(const std::string& prefix, double& timestamp) { - parseHeader(prefix + "/header", timestamp); + parseHeader(prefix + "/header", timestamp); - parseQuaternion(prefix + "/orientation", timestamp); - parseCovariance<3>(prefix + "/orientation_covariance", timestamp); + parseQuaternion(prefix + "/orientation", timestamp); + parseCovariance<3>(prefix + "/orientation_covariance", timestamp); - parseVector3(prefix + "/angular_velocity", timestamp); - parseCovariance<3>(prefix + "/angular_velocity_covariance", timestamp); + parseVector3(prefix + "/angular_velocity", timestamp); + parseCovariance<3>(prefix + "/angular_velocity_covariance", timestamp); - parseVector3(prefix + "/linear_acceleration", timestamp); - parseCovariance<3>(prefix + "/linear_acceleration_covariance", timestamp); + parseVector3(prefix + "/linear_acceleration", timestamp); + parseCovariance<3>(prefix + "/linear_acceleration_covariance", timestamp); } -void ParserROS::parseOdometry(const std::string &prefix, double ×tamp) +void ParserROS::parseOdometry(const std::string& prefix, double& timestamp) { - parseHeader(prefix + "/header", timestamp); - parsePoseWithCovariance(prefix + "/pose", timestamp); - parseTwistWithCovariance(prefix + "/twist", timestamp); + parseHeader(prefix + "/header", timestamp); + parsePoseWithCovariance(prefix + "/pose", timestamp); + parseTwistWithCovariance(prefix + "/twist", timestamp); } -void ParserROS::parseDiagnosticMsg(const std::string &prefix, double ×tamp) +void ParserROS::parseDiagnosticMsg(const std::string& prefix, double& timestamp) { thread_local Msg::DiagnosticArray msg; parseHeader(prefix + "/header", timestamp); size_t status_count = _deserializer->deserializeUInt32(); - msg.status.resize( status_count ); + msg.status.resize(status_count); - for(size_t st = 0; st < status_count; st++) + for (size_t st = 0; st < status_count; st++) { auto& status = msg.status[st]; status.level = _deserializer->deserialize(BYTE).convert(); @@ -273,11 +271,11 @@ void ParserROS::parseDiagnosticMsg(const std::string &prefix, double ×tamp) size_t key_value_count = _deserializer->deserializeUInt32(); std::string key; std::string value_str; - for(size_t kv = 0; kv < key_value_count; kv++) + for (size_t kv = 0; kv < key_value_count; kv++) { _deserializer->deserializeString(key); _deserializer->deserializeString(value_str); - status.key_value.push_back( {key, value_str} ); + status.key_value.push_back({ key, value_str }); } } @@ -291,12 +289,12 @@ void ParserROS::parseDiagnosticMsg(const std::string &prefix, double ×tamp) { if (status.hardware_id.empty()) { - series_name = fmt::format("{}/{}/{}", - prefix, status.name, kv.first); + series_name = fmt::format("{}/{}/{}", prefix, status.name, kv.first); } - else { - series_name = fmt::format("{}/{}/{}/{}", - prefix, status.hardware_id, status.name, kv.first); + else + { + series_name = + fmt::format("{}/{}/{}/{}", prefix, status.hardware_id, status.name, kv.first); } bool ok; @@ -306,14 +304,15 @@ void ParserROS::parseDiagnosticMsg(const std::string &prefix, double ×tamp) { getSeries(series_name).pushBack({ timestamp, value }); } - else { + else + { getStringSeries(series_name).pushBack({ timestamp, kv.second }); } } } } -void ParserROS::parseJointStateMsg(const std::string &prefix, double ×tamp) +void ParserROS::parseJointStateMsg(const std::string& prefix, double& timestamp) { thread_local Msg::JointState msg; @@ -325,10 +324,10 @@ void ParserROS::parseJointStateMsg(const std::string &prefix, double ×tamp) parseHeader(prefix, timestamp); size_t name_size = _deserializer->deserializeUInt32(); - if( name_size > 0 ) + if (name_size > 0) { - msg.name.resize( name_size ); - for(auto& name: msg.name) + msg.name.resize(name_size); + for (auto& name : msg.name) { _deserializer->deserializeString(name); } @@ -336,63 +335,63 @@ void ParserROS::parseJointStateMsg(const std::string &prefix, double ×tamp) //----------- size_t pos_size = _deserializer->deserializeUInt32(); - if( pos_size > 0 ) + if (pos_size > 0) { - msg.position.resize( pos_size ); - for(auto& pos: msg.position) + msg.position.resize(pos_size); + for (auto& pos : msg.position) { pos = _deserializer->deserialize(FLOAT64).convert(); } } //----------- size_t vel_size = _deserializer->deserializeUInt32(); - if( vel_size > 0 ) + if (vel_size > 0) { - msg.velocity.resize( vel_size ); - for(auto& vel: msg.velocity) + msg.velocity.resize(vel_size); + for (auto& vel : msg.velocity) { vel = _deserializer->deserialize(FLOAT64).convert(); } } //----------- size_t eff_size = _deserializer->deserializeUInt32(); - if( eff_size > 0 ) + if (eff_size > 0) { - msg.effort.resize( eff_size ); - for(auto& eff: msg.effort) + msg.effort.resize(eff_size); + for (auto& eff : msg.effort) { eff = _deserializer->deserialize(FLOAT64).convert(); } } //--------------------------- std::string series_name; - for(size_t i=0; i < std::max(name_size, pos_size); i++) + for (size_t i = 0; i < std::max(name_size, pos_size); i++) { series_name = fmt::format("{}/{}/position", _topic, msg.name[i]); getSeries(series_name).pushBack({ timestamp, msg.position[i] }); } - for(size_t i=0; i < std::max(name_size, vel_size); i++) + for (size_t i = 0; i < std::max(name_size, vel_size); i++) { series_name = fmt::format("{}/{}/velocity", _topic, msg.name[i]); getSeries(series_name).pushBack({ timestamp, msg.velocity[i] }); } - for(size_t i=0; i < std::max(name_size, eff_size); i++) + for (size_t i = 0; i < std::max(name_size, eff_size); i++) { series_name = fmt::format("{}/{}/effort", _topic, msg.name[i]); getSeries(series_name).pushBack({ timestamp, msg.effort[i] }); } } -void ParserROS::parseTF2Msg(const std::string &prefix, double ×tamp) +void ParserROS::parseTF2Msg(const std::string& prefix, double& timestamp) { const size_t transform_size = _deserializer->deserializeUInt32(); - if( transform_size == 0) + if (transform_size == 0) { return; } - for(size_t i=0; ideserializeUInt32(); - for(size_t i=0; ideserialize(BuiltinType::UINT64).convert(); @@ -425,40 +425,39 @@ void ParserROS::parseDataTamerSchemasMsg(const std::string &prefix, double &time auto dt_schema = DataTamerParser::BuilSchemaFromText(schema_text); dt_schema.channel_name = channel_name; - _global_data_tamer_schemas.insert({dt_schema.hash, dt_schema}); + _global_data_tamer_schemas.insert({ dt_schema.hash, dt_schema }); } } -void ParserROS::parseDataTamerSnapshotMsg(const std::string &prefix, double ×tamp) +void ParserROS::parseDataTamerSnapshotMsg(const std::string& prefix, double& timestamp) { DataTamerParser::SnapshotView snapshot; - snapshot.timestamp = _deserializer->deserialize(BuiltinType::UINT64).convert(); - snapshot.schema_hash = _deserializer->deserialize(BuiltinType::UINT64).convert(); + snapshot.timestamp = + _deserializer->deserialize(BuiltinType::UINT64).convert(); + snapshot.schema_hash = + _deserializer->deserialize(BuiltinType::UINT64).convert(); auto active_mask = _deserializer->deserializeByteSequence(); - snapshot.active_mask = {active_mask.data(), active_mask.size()}; + snapshot.active_mask = { active_mask.data(), active_mask.size() }; auto payload = _deserializer->deserializeByteSequence(); - snapshot.payload = {payload.data(), payload.size()}; + snapshot.payload = { payload.data(), payload.size() }; auto it = _global_data_tamer_schemas.find(snapshot.schema_hash); - if(it == _global_data_tamer_schemas.end()) + if (it == _global_data_tamer_schemas.end()) { return; } const auto& dt_schema = it->second; - const auto toDouble = [](const auto& value) { - return static_cast(value); - }; + const auto toDouble = [](const auto& value) { return static_cast(value); }; auto callback = [&](const std::string& name_field, - const DataTamerParser::VarNumber& value) - { + const DataTamerParser::VarNumber& value) { double timestamp = double(snapshot.timestamp) * 1e-9; - auto name = fmt::format("{}/{}/{}", _topic_name, dt_schema.channel_name, name_field); - getSeries(name).pushBack( {timestamp, std::visit(toDouble, value)} ); + auto name = fmt::format("{}/{}/{}", _topic_name, dt_schema.channel_name, name_field); + getSeries(name).pushBack({ timestamp, std::visit(toDouble, value) }); }; DataTamerParser::ParseSnapshot(dt_schema, snapshot, callback); diff --git a/plotjuggler_plugins/ParserROS/ros_parser.h b/plotjuggler_plugins/ParserROS/ros_parser.h index 7528c6dc2..23085a45e 100644 --- a/plotjuggler_plugins/ParserROS/ros_parser.h +++ b/plotjuggler_plugins/ParserROS/ros_parser.h @@ -9,10 +9,8 @@ class ParserROS : public PJ::MessageParser { public: - ParserROS(const std::string& topic_name, - const std::string& type_name, - const std::string& schema, - RosMsgParser::Deserializer *deserializer, + ParserROS(const std::string& topic_name, const std::string& type_name, + const std::string& schema, RosMsgParser::Deserializer* deserializer, PJ::PlotDataMapRef& data); bool parseMessage(const PJ::MessageRef serialized_msg, double& timestamp) override; @@ -59,25 +57,23 @@ class ParserROS : public PJ::MessageParser bool _has_header = false; }; -template inline -void ParserROS::parseCovariance(const std::string &prefix, double ×tamp) +template +inline void ParserROS::parseCovariance(const std::string& prefix, double& timestamp) { - std::array cov; - for(auto& val: cov) + std::array cov; + for (auto& val : cov) + { + _deserializer->deserialize(RosMsgParser::FLOAT64).convert(); + } + for (int i = 0; i < N; i++) + { + for (int j = i; j < N; j++) { - _deserializer->deserialize(RosMsgParser::FLOAT64).convert(); - } - for(int i=0; i #else #include -#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ +#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ #if HAVE_CXX0X #include -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X -namespace eprosima { -namespace fastcdr { +namespace eprosima +{ +namespace fastcdr +{ /*! - * @brief This class offers an interface to serialize/deserialize some basic types using CDR protocol inside an eprosima::fastcdr::FastBuffer. + * @brief This class offers an interface to serialize/deserialize some basic types using + * CDR protocol inside an eprosima::fastcdr::FastBuffer. * @ingroup FASTCDRAPIREFERENCE */ class Cdr_DllAPI Cdr { public: - - //! @brief This enumeration represents the two kinds of CDR serialization supported by eprosima::fastcdr::CDR. - typedef enum - { - //! @brief Common CORBA CDR serialization. - CORBA_CDR, - //! @brief DDS CDR serialization. - DDS_CDR - } CdrType; - - //! @brief This enumeration represents the two posible values of the flag that points if the content is a parameter list (only in DDS CDR). + //! @brief This enumeration represents the two kinds of CDR serialization supported by + //! eprosima::fastcdr::CDR. + typedef enum + { + //! @brief Common CORBA CDR serialization. + CORBA_CDR, + //! @brief DDS CDR serialization. + DDS_CDR + } CdrType; + + //! @brief This enumeration represents the two posible values of the flag that points if + //! the content is a parameter list (only in DDS CDR). #ifdef HAVE_CXX0X - typedef enum : uint8_t + typedef enum : uint8_t #else - typedef enum -#endif // ifdef HAVE_CXX0X - { - //! @brief Specifies that the content is not a parameter list. - DDS_CDR_WITHOUT_PL = 0x0, - //! @brief Specifies that the content is a parameter list. - DDS_CDR_WITH_PL = 0x2 - } DDSCdrPlFlag; - - /*! - * @brief This enumeration represents endianness types. - */ + typedef enum +#endif // ifdef HAVE_CXX0X + { + //! @brief Specifies that the content is not a parameter list. + DDS_CDR_WITHOUT_PL = 0x0, + //! @brief Specifies that the content is a parameter list. + DDS_CDR_WITH_PL = 0x2 + } DDSCdrPlFlag; + + /*! + * @brief This enumeration represents endianness types. + */ #ifdef HAVE_CXX0X - typedef enum : uint8_t + typedef enum : uint8_t #else - typedef enum -#endif // ifdef HAVE_CXX0X - { - //! @brief Big endianness. - BIG_ENDIANNESS = 0x0, - //! @brief Little endianness. - LITTLE_ENDIANNESS = 0x1 - } Endianness; - - //! @brief Default endiness in the system. - static const Endianness DEFAULT_ENDIAN; - - /*! - * @brief This class stores the current state of a CDR serialization. - */ - class Cdr_DllAPI state - { - friend class Cdr; - - public: - - /*! - * @brief Default constructor. - */ - state( - const Cdr& cdr); - - /*! - * @brief Copy constructor. - */ - state( - const state&); - - private: - - state& operator =( - const state&) = delete; - - //! @brief The position in the buffer when the state was created. - const FastBuffer::iterator m_currentPosition; - - //! @brief The position from the aligment is calculated, when the state was created.. - const FastBuffer::iterator m_alignPosition; - - //! @brief This attribute specified if it is needed to swap the bytes when the state was created.. - bool m_swapBytes; - - //! @brief Stores the last datasize serialized/deserialized when the state was created. - size_t m_lastDataSize; - }; - - /*! - * @brief This constructor creates an eprosima::fastcdr::Cdr object that can serialize/deserialize - * the assigned buffer. - * - * @param cdrBuffer A reference to the buffer that contains (or will contain) the CDR representation. - * @param endianness The initial endianness that will be used. The default value is the endianness of the system. - * @param cdrType Represents the type of CDR that will be used in serialization/deserialization. The default value is CORBA CDR. - */ - Cdr( - FastBuffer& cdrBuffer, - const Endianness endianness = DEFAULT_ENDIAN, - const CdrType cdrType = CORBA_CDR); - - /*! - * @brief This function reads the encapsulation of the CDR stream. - * If the CDR stream contains an encapsulation, then this function should be called before starting to deserialize. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - Cdr& read_encapsulation(); - - /*! - * @brief This function writes the encapsulation of the CDR stream. - * If the CDR stream should contain an encapsulation, then this function should be called before starting to serialize. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize_encapsulation(); - - /*! - * @brief This function returns the parameter list flag when the CDR type is eprosima::fastcdr::DDS_CDR. - * @return The flag that specifies if the content is a parameter list. - */ - DDSCdrPlFlag getDDSCdrPlFlag() const; - - /*! - * @brief This function sets the parameter list flag when the CDR type is eprosima::fastcdr::DDS_CDR. - * @param plFlag New value for the flag that specifies if the content is a parameter list. - */ - void setDDSCdrPlFlag( - DDSCdrPlFlag plFlag); - - /*! - * @brief This function returns the option flags when the CDR type is eprosima::fastcdr::DDS_CDR. - * @return The option flags. - */ - uint16_t getDDSCdrOptions() const; - - /*! - * @brief This function sets the option flags when the CDR type is eprosima::fastcdr::DDS_CDR. - * @param options New value for the option flags. - */ - void setDDSCdrOptions( - uint16_t options); - - /*! - * @brief This function sets the current endianness used by the CDR type. - * @param endianness The new endianness value. - */ - void changeEndianness( - Endianness endianness); + typedef enum +#endif // ifdef HAVE_CXX0X + { + //! @brief Big endianness. + BIG_ENDIANNESS = 0x0, + //! @brief Little endianness. + LITTLE_ENDIANNESS = 0x1 + } Endianness; - /*! - * @brief This function returns the current endianness used by the CDR type. - * @return The endianness. - */ - Endianness endianness() const - { - return static_cast(m_endianness); - } - - /*! - * @brief This function skips a number of bytes in the CDR stream buffer. - * @param numBytes The number of bytes that will be jumped. - * @return True is returned when it works successfully. Otherwise, false is returned. - */ - bool jump( - size_t numBytes); - - /*! - * @brief This function resets the current position in the buffer to the beginning. - */ - void reset(); - - /*! - * @brief This function returns the pointer to the current used buffer. - * @return Pointer to the starting position of the buffer. - */ - char* getBufferPointer(); - - /*! - * @brief This function returns the current position in the CDR stream. - * @return Pointer to the current position in the buffer. - */ - char* getCurrentPosition(); + //! @brief Default endiness in the system. + static const Endianness DEFAULT_ENDIAN; - /*! - * @brief This function returns the length of the serialized data inside the stream. - * @return The length of the serialized data. - */ - inline size_t getSerializedDataLength() const - { - return m_currentPosition - m_cdrBuffer.begin(); - } + /*! + * @brief This class stores the current state of a CDR serialization. + */ + class Cdr_DllAPI state + { + friend class Cdr; + public: /*! - * @brief Get the number of bytes needed to align a position to certain data size. - * @param current_alignment Position to be aligned. - * @param dataSize Size of next data to process (should be power of two). - * @return Number of required alignment bytes. + * @brief Default constructor. */ - inline static size_t alignment( - size_t current_alignment, - size_t dataSize) - { - return (dataSize - (current_alignment % dataSize)) & (dataSize - 1); - } + state(const Cdr& cdr); /*! - * @brief This function returns the current state of the CDR serialization process. - * @return The current state of the CDR serialization process. + * @brief Copy constructor. */ - state getState(); + state(const state&); - /*! - * @brief This function sets a previous state of the CDR serialization process; - * @param state Previous state that will be set. - */ - void setState( - state& state); + private: + state& operator=(const state&) = delete; - /*! - * @brief This function moves the alignment forward. - * @param numBytes The number of bytes the alignment should advance. - * @return True If alignment was moved successfully. - */ - bool moveAlignmentForward( - size_t numBytes); + //! @brief The position in the buffer when the state was created. + const FastBuffer::iterator m_currentPosition; - /*! - * @brief This function resets the alignment to the current position in the buffer. - */ - inline void resetAlignment() - { - m_alignPosition = m_currentPosition; - } + //! @brief The position from the aligment is calculated, when the state was created.. + const FastBuffer::iterator m_alignPosition; - /*! - * @brief This operator serializes an octet. - * @param octet_t The value of the octet that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const uint8_t octet_t) - { - return serialize(octet_t); - } + //! @brief This attribute specified if it is needed to swap the bytes when the state + //! was created.. + bool m_swapBytes; - /*! - * @brief This operator serializes a character. - * @param char_t The value of the character that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const char char_t) - { - return serialize(char_t); - } + //! @brief Stores the last datasize serialized/deserialized when the state was + //! created. + size_t m_lastDataSize; + }; + + /*! + * @brief This constructor creates an eprosima::fastcdr::Cdr object that can + * serialize/deserialize the assigned buffer. + * + * @param cdrBuffer A reference to the buffer that contains (or will contain) the CDR + * representation. + * @param endianness The initial endianness that will be used. The default value is the + * endianness of the system. + * @param cdrType Represents the type of CDR that will be used in + * serialization/deserialization. The default value is CORBA CDR. + */ + Cdr(FastBuffer& cdrBuffer, const Endianness endianness = DEFAULT_ENDIAN, + const CdrType cdrType = CORBA_CDR); + + /*! + * @brief This function reads the encapsulation of the CDR stream. + * If the CDR stream contains an encapsulation, then this function should be + * called before starting to deserialize. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + Cdr& read_encapsulation(); + + /*! + * @brief This function writes the encapsulation of the CDR stream. + * If the CDR stream should contain an encapsulation, then this function should + * be called before starting to serialize. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize_encapsulation(); + + /*! + * @brief This function returns the parameter list flag when the CDR type is + * eprosima::fastcdr::DDS_CDR. + * @return The flag that specifies if the content is a parameter list. + */ + DDSCdrPlFlag getDDSCdrPlFlag() const; + + /*! + * @brief This function sets the parameter list flag when the CDR type is + * eprosima::fastcdr::DDS_CDR. + * @param plFlag New value for the flag that specifies if the content is a parameter + * list. + */ + void setDDSCdrPlFlag(DDSCdrPlFlag plFlag); + + /*! + * @brief This function returns the option flags when the CDR type is + * eprosima::fastcdr::DDS_CDR. + * @return The option flags. + */ + uint16_t getDDSCdrOptions() const; + + /*! + * @brief This function sets the option flags when the CDR type is + * eprosima::fastcdr::DDS_CDR. + * @param options New value for the option flags. + */ + void setDDSCdrOptions(uint16_t options); + + /*! + * @brief This function sets the current endianness used by the CDR type. + * @param endianness The new endianness value. + */ + void changeEndianness(Endianness endianness); + + /*! + * @brief This function returns the current endianness used by the CDR type. + * @return The endianness. + */ + Endianness endianness() const + { + return static_cast(m_endianness); + } + + /*! + * @brief This function skips a number of bytes in the CDR stream buffer. + * @param numBytes The number of bytes that will be jumped. + * @return True is returned when it works successfully. Otherwise, false is returned. + */ + bool jump(size_t numBytes); + + /*! + * @brief This function resets the current position in the buffer to the beginning. + */ + void reset(); + + /*! + * @brief This function returns the pointer to the current used buffer. + * @return Pointer to the starting position of the buffer. + */ + char* getBufferPointer(); + + /*! + * @brief This function returns the current position in the CDR stream. + * @return Pointer to the current position in the buffer. + */ + char* getCurrentPosition(); + + /*! + * @brief This function returns the length of the serialized data inside the stream. + * @return The length of the serialized data. + */ + inline size_t getSerializedDataLength() const + { + return m_currentPosition - m_cdrBuffer.begin(); + } + + /*! + * @brief Get the number of bytes needed to align a position to certain data size. + * @param current_alignment Position to be aligned. + * @param dataSize Size of next data to process (should be power of two). + * @return Number of required alignment bytes. + */ + inline static size_t alignment(size_t current_alignment, size_t dataSize) + { + return (dataSize - (current_alignment % dataSize)) & (dataSize - 1); + } + + /*! + * @brief This function returns the current state of the CDR serialization process. + * @return The current state of the CDR serialization process. + */ + state getState(); + + /*! + * @brief This function sets a previous state of the CDR serialization process; + * @param state Previous state that will be set. + */ + void setState(state& state); + + /*! + * @brief This function moves the alignment forward. + * @param numBytes The number of bytes the alignment should advance. + * @return True If alignment was moved successfully. + */ + bool moveAlignmentForward(size_t numBytes); + + /*! + * @brief This function resets the alignment to the current position in the buffer. + */ + inline void resetAlignment() + { + m_alignPosition = m_currentPosition; + } + + /*! + * @brief This operator serializes an octet. + * @param octet_t The value of the octet that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const uint8_t octet_t) + { + return serialize(octet_t); + } + + /*! + * @brief This operator serializes a character. + * @param char_t The value of the character that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const char char_t) + { + return serialize(char_t); + } + + /*! + * @brief This operator serializes a int8_t. + * @param int8 The value of the int8_t that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const int8_t int8) + { + return serialize(int8); + } + + /*! + * @brief This operator serializes an unsigned short. + * @param ushort_t The value of the unsigned short that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const uint16_t ushort_t) + { + return serialize(ushort_t); + } + + /*! + * @brief This operator serializes a short. + * @param short_t The value of the short that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const int16_t short_t) + { + return serialize(short_t); + } + + /*! + * @brief This operator serializes an unsigned long. + * @param ulong_t The value of the unsigned long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const uint32_t ulong_t) + { + return serialize(ulong_t); + } + + /*! + * @brief This operator serializes a long. + * @param long_t The value of the long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const int32_t long_t) + { + return serialize(long_t); + } + + /*! + * @brief This operator serializes a wide-char. + * @param wchar The value of the wide-char that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const wchar_t wchar) + { + return serialize(wchar); + } + + /*! + * @brief This operator serializes an unsigned long long. + * @param ulonglong_t The value of the unsigned long long that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const uint64_t ulonglong_t) + { + return serialize(ulonglong_t); + } + + /*! + * @brief This operator serializes a long long. + * @param longlong_t The value of the long long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const int64_t longlong_t) + { + return serialize(longlong_t); + } + + /*! + * @brief This operator serializes a float. + * @param float_t The value of the float that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const float float_t) + { + return serialize(float_t); + } + + /*! + * @brief This operator serializes a double. + * @param double_t The value of the double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const double double_t) + { + return serialize(double_t); + } + + /*! + * @brief This operator serializes a long double. + * @param ldouble_t The value of the long double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const long double ldouble_t) + { + return serialize(ldouble_t); + } + + /*! + * @brief This operator serializes a boolean. + * @param bool_t The value of the boolean that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const bool bool_t) + { + return serialize(bool_t); + } + + /*! + * @brief This operator serializes a null-terminated c-string. + * @param string_t Pointer to the begining of the string that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const char* string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a null-terminated c-string. + * @param string_t Pointer to the begining of the string that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(char* string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a string. + * @param string_t The string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const std::string& string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a wstring. + * @param string_t The wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& operator<<(const std::wstring& string_t) + { + return serialize(string_t); + } - /*! - * @brief This operator serializes a int8_t. - * @param int8 The value of the int8_t that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const int8_t int8) - { - return serialize(int8); - } +#if HAVE_CXX0X + /*! + * @brief This operator template is used to serialize arrays. + * @param array_t The array that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator<<(const std::array<_T, _Size>& array_t) + { + return serialize<_T, _Size>(array_t); + } + +#endif // if HAVE_CXX0X + + /*! + * @brief This operator template is used to serialize sequences. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator<<(const std::vector<_T>& vector_t) + { + return serialize<_T>(vector_t); + } + + /*! + * @brief This operator template is used to serialize maps. + * @param map_t The map that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator<<(const std::map<_K, _T>& map_t) + { + return serialize<_K, _T>(map_t); + } + + /*! + * @brief This operator template is used to serialize any other non-basic type. + * @param type_t A reference to the object that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator<<(const _T& type_t) + { + type_t.serialize(*this); + return *this; + } + + /*! + * @brief This operator deserializes an octet. + * @param octet_t The variable that will store the octet read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(uint8_t& octet_t) + { + return deserialize(octet_t); + } + + /*! + * @brief This operator deserializes a character. + * @param char_t The variable that will store the character read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(char& char_t) + { + return deserialize(char_t); + } + + /*! + * @brief This operator deserializes a int8_t. + * @param int8 The variable that will store the int8_t read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(int8_t& int8) + { + return deserialize(int8); + } + + /*! + * @brief This operator deserializes an unsigned short. + * @param ushort_t The variable that will store the unsigned short read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(uint16_t& ushort_t) + { + return deserialize(ushort_t); + } + + /*! + * @brief This operator deserializes a short. + * @param short_t The variable that will store the short read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(int16_t& short_t) + { + return deserialize(short_t); + } + + /*! + * @brief This operator deserializes an unsigned long. + * @param ulong_t The variable that will store the unsigned long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(uint32_t& ulong_t) + { + return deserialize(ulong_t); + } + + /*! + * @brief This operator deserializes a long. + * @param long_t The variable that will store the long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(int32_t& long_t) + { + return deserialize(long_t); + } + + // TODO in FastCdr + /*! + * @brief This operator deserializes a wide-char. + * @param wchar The variable that will store the wide-char read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(wchar_t& wchar) + { + return deserialize(wchar); + } + + /*! + * @brief This operator deserializes a unsigned long long. + * @param ulonglong_t The variable that will store the unsigned long long read from the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(uint64_t& ulonglong_t) + { + return deserialize(ulonglong_t); + } + + /*! + * @brief This operator deserializes a long long. + * @param longlong_t The variable that will store the long long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(int64_t& longlong_t) + { + return deserialize(longlong_t); + } + + /*! + * @brief This operator deserializes a float. + * @param float_t The variable that will store the float read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(float& float_t) + { + return deserialize(float_t); + } + + /*! + * @brief This operator deserializes a double. + * @param double_t The variable that will store the double read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(double& double_t) + { + return deserialize(double_t); + } + + /*! + * @brief This operator deserializes a long double. + * @param ldouble_t The variable that will store the long double read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(long double& ldouble_t) + { + return deserialize(ldouble_t); + } + + /*! + * @brief This operator deserializes a boolean. + * @param bool_t The variable that will store the boolean read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + inline Cdr& operator>>(bool& bool_t) + { + return deserialize(bool_t); + } + + /*! + * @brief This operator deserializes a null-terminated c-string. + * @param string_t The variable that will store the c-string read from the buffer. + * Please note that a newly allocated string will be returned. + * The caller should free the returned pointer when appropiate. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + inline Cdr& operator>>(char*& string_t) + { + return deserialize(string_t); + } + + /*! + * @brief This operator deserializes a string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(std::string& string_t) + { + return deserialize(string_t); + } + + /*! + * @brief This operator deserializes a string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& operator>>(std::wstring& string_t) + { + return deserialize(string_t); + } - /*! - * @brief This operator serializes an unsigned short. - * @param ushort_t The value of the unsigned short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const uint16_t ushort_t) - { - return serialize(ushort_t); - } +#if HAVE_CXX0X + /*! + * @brief This operator template is used to deserialize arrays. + * @param array_t The variable that will store the array read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator>>(std::array<_T, _Size>& array_t) + { + return deserialize<_T, _Size>(array_t); + } + +#endif // if HAVE_CXX0X + + /*! + * @brief This operator template is used to deserialize sequences. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator>>(std::vector<_T>& vector_t) + { + return deserialize<_T>(vector_t); + } + + /*! + * @brief This operator template is used to deserialize maps. + * @param map_t The variable that will store the map read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator>>(std::map<_K, _T>& map_t) + { + return deserialize<_K, _T>(map_t); + } + + /*! + * @brief This operator template is used to deserialize any other non-basic type. + * @param type_t The variable that will store the object read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& operator>>(_T& type_t) + { + type_t.deserialize(*this); + return *this; + } + + /*! + * @brief This function serializes an octet. + * @param octet_t The value of the octet that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint8_t octet_t) + { + return serialize(static_cast(octet_t)); + } + + /*! + * @brief This function serializes an octet with a different endianness. + * @param octet_t The value of the octet that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint8_t octet_t, Endianness endianness) + { + return serialize(static_cast(octet_t), endianness); + } + + /*! + * @brief This function serializes a character. + * @param char_t The value of the character that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const char char_t); + + /*! + * @brief This function serializes a character with a different endianness. + * @param char_t The value of the character that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const char char_t, Endianness endianness) + { + (void)endianness; + return serialize(char_t); + } + + /*! + * @brief This function serializes an int8_t. + * @param int8 The value of the int8_t that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const int8_t int8) + { + return serialize(static_cast(int8)); + } + + /*! + * @brief This function serializes an int8_t with a different endianness. + * @param int8 The value of the int8_t that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const int8_t int8, Endianness endianness) + { + return serialize(static_cast(int8), endianness); + } + + /*! + * @brief This function serializes an unsigned short. + * @param ushort_t The value of the unsigned short that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint16_t ushort_t) + { + return serialize(static_cast(ushort_t)); + } + + /*! + * @brief This function serializes an unsigned short with a different endianness. + * @param ushort_t The value of the unsigned short that will be serialized in the + * buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint16_t ushort_t, Endianness endianness) + { + return serialize(static_cast(ushort_t), endianness); + } + + /*! + * @brief This function serializes a short. + * @param short_t The value of the short that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int16_t short_t); + + /*! + * @brief This function serializes a short with a different endianness. + * @param short_t The value of the short that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int16_t short_t, Endianness endianness); + + /*! + * @brief This function serializes an unsigned long. + * @param ulong_t The value of the unsigned long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint32_t ulong_t) + { + return serialize(static_cast(ulong_t)); + } + + /*! + * @brief This function serializes an unsigned long with a different endianness. + * @param ulong_t The value of the unsigned long that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint32_t ulong_t, Endianness endianness) + { + return serialize(static_cast(ulong_t), endianness); + } + + /*! + * @brief This function serializes a long. + * @param long_t The value of the long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int32_t long_t); + + /*! + * @brief This function serializes a long with a different endianness. + * @param long_t The value of the long that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int32_t long_t, Endianness endianness); + + /*! + * @brief This function serializes a wide-char. + * @param wchar The value of the wide-char that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const wchar_t wchar) + { + return serialize(static_cast(wchar)); + } + + /*! + * @brief This function serializes a wide-char with a different endianness. + * @param wchar The value of the wide-char that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const wchar_t wchar, Endianness endianness) + { + return serialize(static_cast(wchar), endianness); + } + + /*! + * @brief This function serializes an unsigned long long. + * @param ulonglong_t The value of the unsigned long long that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint64_t ulonglong_t) + { + return serialize(static_cast(ulonglong_t)); + } + + /*! + * @brief This function serializes an unsigned long long with a different endianness. + * @param ulonglong_t The value of the unsigned long long that will be serialized in the + * buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const uint64_t ulonglong_t, Endianness endianness) + { + return serialize(static_cast(ulonglong_t), endianness); + } + + /*! + * @brief This function serializes a long long. + * @param longlong_t The value of the long long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int64_t longlong_t); + + /*! + * @brief This function serializes a long long with a different endianness. + * @param longlong_t The value of the long long that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const int64_t longlong_t, Endianness endianness); + + /*! + * @brief This function serializes a float. + * @param float_t The value of the float that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const float float_t); + + /*! + * @brief This function serializes a float with a different endianness. + * @param float_t The value of the float that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const float float_t, Endianness endianness); + + /*! + * @brief This function serializes a double. + * @param double_t The value of the double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const double double_t); + + /*! + * @brief This function serializes a double with a different endianness. + * @param double_t The value of the double that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const double double_t, Endianness endianness); + + /*! + * @brief This function serializes a long double. + * @param ldouble_t The value of the long double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + * @note Due to internal representation differences, WIN32 and *NIX like systems are not + * compatible. + */ + Cdr& serialize(const long double ldouble_t); + + /*! + * @brief This function serializes a long double with a different endianness. + * @param ldouble_t The value of the long double that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + * @note Due to internal representation differences, WIN32 and *NIX like systems are not + * compatible. + */ + Cdr& serialize(const long double ldouble_t, Endianness endianness); + + /*! + * @brief This function serializes a boolean. + * @param bool_t The value of the boolean that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const bool bool_t); + + /*! + * @brief This function serializes a boolean with a different endianness. + * @param bool_t The value of the boolean that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const bool bool_t, Endianness endianness) + { + (void)endianness; + return serialize(bool_t); + } + + /*! + * @brief This function serializes a string. + * @param string_t The pointer to the string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(char* string_t) + { + return serialize(static_cast(string_t)); + } + + /*! + * @brief This function serializes a string. + * @param string_t The pointer to the string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const char* string_t); + + /*! + * @brief This function serializes a wstring. + * @param string_t The pointer to the wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const wchar_t* string_t); + + /*! + * @brief This function serializes a string with a different endianness. + * @param string_t The pointer to the string that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const char* string_t, Endianness endianness); + + /*! + * @brief This function serializes a wstring with a different endianness. + * @param string_t The pointer to the wstring that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serialize(const wchar_t* string_t, Endianness endianness); + + /*! + * @brief This function serializes a std::string. + * @param string_t The string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const std::string& string_t) + { + return serialize(string_t.c_str()); + } + + /*! + * @brief This function serializes a std::wstring. + * @param string_t The wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const std::wstring& string_t) + { + return serialize(string_t.c_str()); + } + + /*! + * @brief This function serializes a std::string with a different endianness. + * @param string_t The string that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serialize(const std::string& string_t, Endianness endianness) + { + return serialize(string_t.c_str(), endianness); + } - /*! - * @brief This operator serializes a short. - * @param short_t The value of the short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const int16_t short_t) - { - return serialize(short_t); - } +#if HAVE_CXX0X + /*! + * @brief This function template serializes an array. + * @param array_t The array that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& serialize(const std::array<_T, _Size>& array_t) + { + return serializeArray(array_t.data(), array_t.size()); + } + + /*! + * @brief This function template serializes an array with a different endianness. + * @param array_t The array that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& serialize(const std::array<_T, _Size>& array_t, Endianness endianness) + { + return serializeArray(array_t.data(), array_t.size(), endianness); + } + +#endif // if HAVE_CXX0X - /*! - * @brief This operator serializes an unsigned long. - * @param ulong_t The value of the unsigned long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const uint32_t ulong_t) - { - return serialize(ulong_t); - } +#if !defined(_MSC_VER) && HAVE_CXX0X + /*! + * @brief This function template serializes a sequence of booleans. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serialize(const std::vector& vector_t) + { + return serializeBoolSequence(vector_t); + } - /*! - * @brief This operator serializes a long. - * @param long_t The value of the long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const int32_t long_t) - { - return serialize(long_t); - } +#endif // if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This operator serializes a wide-char. - * @param wchar The value of the wide-char that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const wchar_t wchar) - { - return serialize(wchar); - } + /*! + * @brief This function template serializes a sequence. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serialize(const std::vector<_T>& vector_t) + { + state state_before_error(*this); - /*! - * @brief This operator serializes an unsigned long long. - * @param ulonglong_t The value of the unsigned long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const uint64_t ulonglong_t) - { - return serialize(ulonglong_t); - } + *this << static_cast(vector_t.size()); - /*! - * @brief This operator serializes a long long. - * @param longlong_t The value of the long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const int64_t longlong_t) + try { - return serialize(longlong_t); + return serializeArray(vector_t.data(), vector_t.size()); } - - /*! - * @brief This operator serializes a float. - * @param float_t The value of the float that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const float float_t) + catch (eprosima::fastcdr::exception::Exception& ex) { - return serialize(float_t); + setState(state_before_error); + ex.raise(); } - /*! - * @brief This operator serializes a double. - * @param double_t The value of the double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const double double_t) - { - return serialize(double_t); - } + return *this; + } - /*! - * @brief This operator serializes a long double. - * @param ldouble_t The value of the long double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const long double ldouble_t) - { - return serialize(ldouble_t); - } + /*! + * @brief This function template serializes a map. + * @param map_t The map that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serialize(const std::map<_K, _T>& map_t) + { + state state_(*this); - /*! - * @brief This operator serializes a boolean. - * @param bool_t The value of the boolean that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const bool bool_t) - { - return serialize(bool_t); - } + *this << static_cast(map_t.size()); - /*! - * @brief This operator serializes a null-terminated c-string. - * @param string_t Pointer to the begining of the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const char* string_t) + try { - return serialize(string_t); + for (auto it_pair = map_t.begin(); it_pair != map_t.end(); ++it_pair) + { + *this << it_pair->first; + *this << it_pair->second; + } + // return serializeArray(map_t.data(), map_t.size()); } - - /*! - * @brief This operator serializes a null-terminated c-string. - * @param string_t Pointer to the begining of the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - char* string_t) + catch (eprosima::fastcdr::exception::Exception& ex) { - return serialize(string_t); + setState(state_); + ex.raise(); } - /*! - * @brief This operator serializes a string. - * @param string_t The string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const std::string& string_t) - { - return serialize(string_t); - } + return *this; + } - /*! - * @brief This operator serializes a wstring. - * @param string_t The wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& operator <<( - const std::wstring& string_t) - { - return serialize(string_t); - } +#ifdef _MSC_VER + /*! + * @brief This function template serializes a sequence of booleans. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template <> + Cdr& serialize(const std::vector& vector_t) + { + return serializeBoolSequence(vector_t); + } + +#endif // ifdef _MSC_VER + + /*! + * @brief This function template serializes a sequence with a different endianness. + * @param vector_t The sequence that will be serialized in the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serialize(const std::vector<_T>& vector_t, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + serialize(vector_t); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template serializes a non-basic object. + * @param type_t The object that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + inline Cdr& serialize(const _T& type_t) + { + type_t.serialize(*this); + return *this; + } + + /*! + * @brief This function serializes an array of octets. + * @param octet_t The sequence of octets that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint8_t* octet_t, size_t numElements) + { + return serializeArray(reinterpret_cast(octet_t), numElements); + } + + /*! + * @brief This function serializes an array of octets with a different endianness. + * @param octet_t The array of octets that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint8_t* octet_t, size_t numElements, + Endianness endianness) + { + (void)endianness; + return serializeArray(reinterpret_cast(octet_t), numElements); + } + + /*! + * @brief This function serializes an array of characters. + * @param char_t The array of characters that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const char* char_t, size_t numElements); + + /*! + * @brief This function serializes an array of characters with a different endianness. + * @param char_t The array of characters that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const char* char_t, size_t numElements, + Endianness endianness) + { + (void)endianness; + return serializeArray(char_t, numElements); + } + + /*! + * @brief This function serializes an array of int8_t. + * @param int8 The sequence of int8_t that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const int8_t* int8, size_t numElements) + { + return serializeArray(reinterpret_cast(int8), numElements); + } + + /*! + * @brief This function serializes an array of int8_t with a different endianness. + * @param int8 The array of int8_t that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const int8_t* int8, size_t numElements, + Endianness endianness) + { + (void)endianness; + return serializeArray(reinterpret_cast(int8), numElements); + } + + /*! + * @brief This function serializes an array of unsigned shorts. + * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint16_t* ushort_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ushort_t), numElements); + } + + /*! + * @brief This function serializes an array of unsigned shorts with a different + * endianness. + * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint16_t* ushort_t, size_t numElements, + Endianness endianness) + { + return serializeArray(reinterpret_cast(ushort_t), numElements, + endianness); + } + + /*! + * @brief This function serializes an array of shorts. + * @param short_t The array of shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int16_t* short_t, size_t numElements); + + /*! + * @brief This function serializes an array of shorts with a different endianness. + * @param short_t The array of shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int16_t* short_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function serializes an array of unsigned longs. + * @param ulong_t The array of unsigned longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint32_t* ulong_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ulong_t), numElements); + } + + /*! + * @brief This function serializes an array of unsigned longs with a different + * endianness. + * @param ulong_t The array of unsigned longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint32_t* ulong_t, size_t numElements, + Endianness endianness) + { + return serializeArray(reinterpret_cast(ulong_t), numElements, + endianness); + } + + /*! + * @brief This function serializes an array of longs. + * @param long_t The array of longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int32_t* long_t, size_t numElements); + + /*! + * @brief This function serializes an array of longs with a different endianness. + * @param long_t The array of longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int32_t* long_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function serializes an array of wide-chars. + * @param wchar The array of wide-chars that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const wchar_t* wchar, size_t numElements); + + /*! + * @brief This function serializes an array of wide-chars with a different endianness. + * @param wchar The array of longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const wchar_t* wchar, size_t numElements, Endianness endianness); + + /*! + * @brief This function serializes an array of unsigned long longs. + * @param ulonglong_t The array of unsigned long longs that will be serialized in the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint64_t* ulonglong_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ulonglong_t), numElements); + } + + /*! + * @brief This function serializes an array of unsigned long longs with a different + * endianness. + * @param ulonglong_t The array of unsigned long longs that will be serialized in the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const uint64_t* ulonglong_t, size_t numElements, + Endianness endianness) + { + return serializeArray(reinterpret_cast(ulonglong_t), numElements, + endianness); + } + + /*! + * @brief This function serializes an array of long longs. + * @param longlong_t The array of long longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int64_t* longlong_t, size_t numElements); + + /*! + * @brief This function serializes an array of long longs with a different endianness. + * @param longlong_t The array of long longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const int64_t* longlong_t, size_t numElements, + Endianness endianness); + + /*! + * @brief This function serializes an array of floats. + * @param float_t The array of floats that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const float* float_t, size_t numElements); + + /*! + * @brief This function serializes an array of floats with a different endianness. + * @param float_t The array of floats that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const float* float_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function serializes an array of doubles. + * @param double_t The array of doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const double* double_t, size_t numElements); + + /*! + * @brief This function serializes an array of doubles with a different endianness. + * @param double_t The array of doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const double* double_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function serializes an array of long doubles. + * @param ldouble_t The array of long doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const long double* ldouble_t, size_t numElements); + + /*! + * @brief This function serializes an array of long doubles with a different endianness. + * @param ldouble_t The array of long doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const long double* ldouble_t, size_t numElements, + Endianness endianness); + + /*! + * @brief This function serializes an array of booleans. + * @param bool_t The array of booleans that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + Cdr& serializeArray(const bool* bool_t, size_t numElements); + + /*! + * @brief This function serializes an array of booleans with a different endianness. + * @param bool_t The array of booleans that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const bool* bool_t, size_t numElements, + Endianness endianness) + { + (void)endianness; + return serializeArray(bool_t, numElements); + } + + /*! + * @brief This function serializes an array of strings. + * @param string_t The array of strings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const std::string* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(string_t[count].c_str()); + } + return *this; + } + + /*! + * @brief This function serializes an array of wide-strings. + * @param string_t The array of wide-strings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const std::wstring* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(string_t[count].c_str()); + } + return *this; + } + + /*! + * @brief This function serializes an array of strings with a different endianness. + * @param string_t The array of strings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const std::string* string_t, size_t numElements, + Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + serializeArray(string_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function serializes an array of wide-strings with a different endianness. + * @param string_t The array of wide-strings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + inline Cdr& serializeArray(const std::wstring* string_t, size_t numElements, + Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + serializeArray(string_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template serializes an array of sequences of objects. + * @param vector_t The array of sequences of objects that will be serialized in the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeArray(const std::vector<_T>* vector_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(vector_t[count]); + } + return *this; + } + + /*! + * @brief This function template serializes an array of non-basic objects. + * @param type_t The array of objects that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeArray(const _T* type_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + type_t[count].serialize(*this); + } + return *this; + } + + /*! + * @brief This function template serializes an array of non-basic objects with a + * different endianness. + * @param type_t The array of objects that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeArray(const _T* type_t, size_t numElements, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + serializeArray(type_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template serializes a raw sequence. + * @param sequence_t Pointer to the sequence that will be serialized in the buffer. + * @param numElements The number of elements contained in the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeSequence(const _T* sequence_t, size_t numElements) + { + state state_before_error(*this); + + serialize(static_cast(numElements)); + + try + { + return serializeArray(sequence_t, numElements); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + setState(state_before_error); + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template serializes a raw sequence with a different endianness. + * @param sequence_t Pointer to the sequence that will be serialized in the buffer. + * @param numElements The number of elements contained in the sequence. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeSequence(const _T* sequence_t, size_t numElements, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + serializeSequence(sequence_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function deserializes an octet. + * @param octet_t The variable that will store the octet read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint8_t& octet_t) + { + return deserialize(reinterpret_cast(octet_t)); + } + + /*! + * @brief This function deserializes an octet with a different endianness. + * @param octet_t The variable that will store the octet read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint8_t& octet_t, Endianness endianness) + { + return deserialize(reinterpret_cast(octet_t), endianness); + } + + /*! + * @brief This function deserializes a character. + * @param char_t The variable that will store the character read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(char& char_t); + + /*! + * @brief This function deserializes a character with a different endianness. + * @param char_t The variable that will store the character read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(char& char_t, Endianness endianness) + { + (void)endianness; + return deserialize(char_t); + } + + /*! + * @brief This function deserializes an int8_t. + * @param int8 The variable that will store the int8_t read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(int8_t& int8) + { + return deserialize(reinterpret_cast(int8)); + } + + /*! + * @brief This function deserializes an int8_t with a different endianness. + * @param int8 The variable that will store the int8_t read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(int8_t& int8, Endianness endianness) + { + return deserialize(reinterpret_cast(int8), endianness); + } + + /*! + * @brief This function deserializes an unsigned short. + * @param ushort_t The variable that will store the unsigned short read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint16_t& ushort_t) + { + return deserialize(reinterpret_cast(ushort_t)); + } + + /*! + * @brief This function deserializes an unsigned short with a different endianness. + * @param ushort_t The variable that will store the unsigned short read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint16_t& ushort_t, Endianness endianness) + { + return deserialize(reinterpret_cast(ushort_t), endianness); + } + + /*! + * @brief This function deserializes a short. + * @param short_t The variable that will store the short read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int16_t& short_t); + + /*! + * @brief This function deserializes a short with a different endianness. + * @param short_t The variable that will store the short read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int16_t& short_t, Endianness endianness); + + /*! + * @brief This function deserializes an unsigned long. + * @param ulong_t The variable that will store the unsigned long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint32_t& ulong_t) + { + return deserialize(reinterpret_cast(ulong_t)); + } + + /*! + * @brief This function deserializes an unsigned long with a different endianness. + * @param ulong_t The variable that will store the unsigned long read from the buffer.. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint32_t& ulong_t, Endianness endianness) + { + return deserialize(reinterpret_cast(ulong_t), endianness); + } + + /*! + * @brief This function deserializes a long. + * @param long_t The variable that will store the long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int32_t& long_t); + + /*! + * @brief This function deserializes a long with a different endianness. + * @param long_t The variable that will store the long read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int32_t& long_t, Endianness endianness); + + /*! + * @brief This function deserializes a wide-char. + * @param wchar The variable that will store the wide-char read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(wchar_t& wchar) + { + uint32_t ret; + deserialize(ret); + wchar = static_cast(ret); + return *this; + } + + /*! + * @brief This function deserializes a wide-char with a different endianness. + * @param wchar The variable that will store the wide-char read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(wchar_t& wchar, Endianness endianness) + { + uint32_t ret; + deserialize(ret, endianness); + wchar = static_cast(ret); + return *this; + } + + /*! + * @brief This function deserializes an unsigned long long. + * @param ulonglong_t The variable that will store the unsigned long long read from the + * buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint64_t& ulonglong_t) + { + return deserialize(reinterpret_cast(ulonglong_t)); + } + + /*! + * @brief This function deserializes an unsigned long long with a different endianness. + * @param ulonglong_t The variable that will store the unsigned long long read from the + * buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(uint64_t& ulonglong_t, Endianness endianness) + { + return deserialize(reinterpret_cast(ulonglong_t), endianness); + } + + /*! + * @brief This function deserializes a long long. + * @param longlong_t The variable that will store the long long read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int64_t& longlong_t); + + /*! + * @brief This function deserializes a long long with a different endianness. + * @param longlong_t The variable that will store the long long read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(int64_t& longlong_t, Endianness endianness); + + /*! + * @brief This function deserializes a float. + * @param float_t The variable that will store the float read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(float& float_t); + + /*! + * @brief This function deserializes a float with a different endianness. + * @param float_t The variable that will store the float read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(float& float_t, Endianness endianness); + + /*! + * @brief This function deserializes a double. + * @param double_t The variable that will store the double read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(double& double_t); + + /*! + * @brief This function deserializes a double with a different endianness. + * @param double_t The variable that will store the double read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(double& double_t, Endianness endianness); + + /*! + * @brief This function deserializes a long double. + * @param ldouble_t The variable that will store the long double read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @note Due to internal representation differences, WIN32 and *NIX like systems are not + * compatible. + */ + Cdr& deserialize(long double& ldouble_t); + + /*! + * @brief This function deserializes a long double with a different endianness. + * @param ldouble_t The variable that will store the long double read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @note Due to internal representation differences, WIN32 and *NIX like systems are not + * compatible. + */ + Cdr& deserialize(long double& ldouble_t, Endianness endianness); + + /*! + * @brief This function deserializes a boolean. + * @param bool_t The variable that will store the boolean read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + Cdr& deserialize(bool& bool_t); + + /*! + * @brief This function deserializes a boolean with a different endianness. + * @param bool_t The variable that will store the boolean read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + inline Cdr& deserialize(bool& bool_t, Endianness endianness) + { + (void)endianness; + return deserialize(bool_t); + } + + /*! + * @brief This function deserializes a string. + * This function allocates memory to store the string. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param string_t The pointer that will point to the string read from the buffer. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(char*& string_t); + + /*! + * @brief This function deserializes a wide string. + * This function allocates memory to store the wide string. The user pointer will be set + * to point this allocated memory. The user will have to free this allocated memory + * using free() + * @param string_t The pointer that will point to the wide string read from the buffer. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(wchar_t*& string_t); + + /*! + * @brief This function deserializes a string with a different endianness. + * This function allocates memory to store the string. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param string_t The pointer that will point to the string read from the buffer. + * @param endianness Endianness that will be used in the deserialization of this value. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(char*& string_t, Endianness endianness); + + /*! + * @brief This function deserializes a wide string with a different endianness. + * This function allocates memory to store the wide string. The user pointer will be set + * to point this allocated memory. The user will have to free this allocated memory + * using free() + * @param string_t The pointer that will point to the wide string read from the buffer. + * @param endianness Endianness that will be used in the deserialization of this value. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserialize(wchar_t*& string_t, Endianness endianness); + + /*! + * @brief This function deserializes a std::string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(std::string& string_t) + { + uint32_t length = 0; + const char* str = readString(length); + string_t = std::string(str, length); + return *this; + } + + /*! + * @brief This function deserializes a std::string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(std::wstring& string_t) + { + uint32_t length = 0; + string_t = readWString(length); + return *this; + } + + /*! + * @brief This function deserializes a string with a different endianness. + * @param string_t The variable that will store the string read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(std::string& string_t, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserialize(string_t); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function deserializes a string with a different endianness. + * @param string_t The variable that will store the string read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserialize(std::wstring& string_t, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserialize(string_t); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } #if HAVE_CXX0X - /*! - * @brief This operator template is used to serialize arrays. - * @param array_t The array that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator <<( - const std::array<_T, _Size>& array_t) - { - return serialize<_T, _Size>(array_t); - } - -#endif // if HAVE_CXX0X - - /*! - * @brief This operator template is used to serialize sequences. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator <<( - const std::vector<_T>& vector_t) - { - return serialize<_T>(vector_t); - } - - /*! - * @brief This operator template is used to serialize maps. - * @param map_t The map that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator <<( - const std::map<_K, _T>& map_t) - { - return serialize<_K, _T>(map_t); - } - - /*! - * @brief This operator template is used to serialize any other non-basic type. - * @param type_t A reference to the object that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator <<( - const _T& type_t) - { - type_t.serialize(*this); - return *this; - } + /*! + * @brief This function template deserializes an array. + * @param array_t The variable that will store the array read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& deserialize(std::array<_T, _Size>& array_t) + { + return deserializeArray(array_t.data(), array_t.size()); + } + + /*! + * @brief This function template deserializes an array with a different endianness. + * @param array_t The variable that will store the array read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& deserialize(std::array<_T, _Size>& array_t, Endianness endianness) + { + return deserializeArray(array_t.data(), array_t.size(), endianness); + } + +#endif // if HAVE_CXX0X - /*! - * @brief This operator deserializes an octet. - * @param octet_t The variable that will store the octet read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - uint8_t& octet_t) - { - return deserialize(octet_t); - } +#if !defined(_MSC_VER) && HAVE_CXX0X + /*! + * @brief This function template deserializes a sequence. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserialize(std::vector& vector_t) + { + return deserializeBoolSequence(vector_t); + } - /*! - * @brief This operator deserializes a character. - * @param char_t The variable that will store the character read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - char& char_t) - { - return deserialize(char_t); - } +#endif // if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This operator deserializes a int8_t. - * @param int8 The variable that will store the int8_t read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - int8_t& int8) - { - return deserialize(int8); - } + /*! + * @brief This function template deserializes a sequence. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserialize(std::vector<_T>& vector_t) + { + uint32_t seqLength = 0; + state state_before_error(*this); - /*! - * @brief This operator deserializes an unsigned short. - * @param ushort_t The variable that will store the unsigned short read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - uint16_t& ushort_t) - { - return deserialize(ushort_t); - } + *this >> seqLength; - /*! - * @brief This operator deserializes a short. - * @param short_t The variable that will store the short read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - int16_t& short_t) + if (seqLength == 0) { - return deserialize(short_t); + vector_t.clear(); + return *this; } - /*! - * @brief This operator deserializes an unsigned long. - * @param ulong_t The variable that will store the unsigned long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - uint32_t& ulong_t) + if ((m_lastPosition - m_currentPosition) < seqLength) { - return deserialize(ulong_t); + setState(state_before_error); + throw eprosima::fastcdr::exception::NotEnoughMemoryException( + eprosima::fastcdr::exception::NotEnoughMemoryException:: + NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } - /*! - * @brief This operator deserializes a long. - * @param long_t The variable that will store the long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - int32_t& long_t) + try { - return deserialize(long_t); + vector_t.resize(seqLength); + return deserializeArray(vector_t.data(), vector_t.size()); } - - // TODO in FastCdr - /*! - * @brief This operator deserializes a wide-char. - * @param wchar The variable that will store the wide-char read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - wchar_t& wchar) + catch (eprosima::fastcdr::exception::Exception& ex) { - return deserialize(wchar); + setState(state_before_error); + ex.raise(); } - /*! - * @brief This operator deserializes a unsigned long long. - * @param ulonglong_t The variable that will store the unsigned long long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - uint64_t& ulonglong_t) - { - return deserialize(ulonglong_t); - } + return *this; + } - /*! - * @brief This operator deserializes a long long. - * @param longlong_t The variable that will store the long long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - int64_t& longlong_t) - { - return deserialize(longlong_t); - } + /*! + * @brief This function template deserializes a map. + * @param map_t The variable that will store the map read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserialize(std::map<_K, _T>& map_t) + { + uint32_t seqLength = 0; + state state_(*this); - /*! - * @brief This operator deserializes a float. - * @param float_t The variable that will store the float read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - float& float_t) - { - return deserialize(float_t); - } + *this >> seqLength; - /*! - * @brief This operator deserializes a double. - * @param double_t The variable that will store the double read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - double& double_t) + try { - return deserialize(double_t); + for (uint32_t i = 0; i < seqLength; ++i) + { + _K key; + _T value; + *this >> key; + *this >> value; + map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); + } } - - /*! - * @brief This operator deserializes a long double. - * @param ldouble_t The variable that will store the long double read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - long double& ldouble_t) + catch (eprosima::fastcdr::exception::Exception& ex) { - return deserialize(ldouble_t); + setState(state_); + ex.raise(); } - /*! - * @brief This operator deserializes a boolean. - * @param bool_t The variable that will store the boolean read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - inline Cdr& operator >>( - bool& bool_t) - { - return deserialize(bool_t); - } + return *this; + } - /*! - * @brief This operator deserializes a null-terminated c-string. - * @param string_t The variable that will store the c-string read from the buffer. - * Please note that a newly allocated string will be returned. - * The caller should free the returned pointer when appropiate. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - inline Cdr& operator >>( - char*& string_t) - { - return deserialize(string_t); - } +#ifdef _MSC_VER + /*! + * @brief This function template deserializes a sequence. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template <> + Cdr& deserialize(std::vector& vector_t) + { + return deserializeBoolSequence(vector_t); + } + +#endif // ifdef _MSC_VER + + /*! + * @brief This function template deserializes a sequence with a different endianness. + * @param vector_t The variable that will store the sequence read from the buffer. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserialize(std::vector<_T>& vector_t, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserialize(vector_t); + m_swapBytes = auxSwap; + } + catch (exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function template deserializes a non-basic object. + * @param type_t The variable that will store the object read from the buffer. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + inline Cdr& deserialize(_T& type_t) + { + type_t.deserialize(*this); + return *this; + } + + /*! + * @brief This function deserializes an array of octets. + * @param octet_t The variable that will store the array of octets read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint8_t* octet_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(octet_t), numElements); + } + + /*! + * @brief This function deserializes an array of octets with a different endianness. + * @param octet_t The variable that will store the array of octets read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint8_t* octet_t, size_t numElements, + Endianness endianness) + { + return deserializeArray(reinterpret_cast(octet_t), numElements, endianness); + } + + /*! + * @brief This function deserializes an array of characters. + * @param char_t The variable that will store the array of characters read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(char* char_t, size_t numElements); + + /*! + * @brief This function deserializes an array of characters with a different endianness. + * @param char_t The variable that will store the array of characters read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(char* char_t, size_t numElements, Endianness endianness) + { + (void)endianness; + return deserializeArray(char_t, numElements); + } + + /*! + * @brief This function deserializes an array of int8_t. + * @param int8 The variable that will store the array of int8_t read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(int8_t* int8, size_t numElements) + { + return deserializeArray(reinterpret_cast(int8), numElements); + } + + /*! + * @brief This function deserializes an array of int8_t with a different endianness. + * @param int8 The variable that will store the array of int8_t read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(int8_t* int8, size_t numElements, Endianness endianness) + { + return deserializeArray(reinterpret_cast(int8), numElements, endianness); + } + + /*! + * @brief This function deserializes an array of unsigned shorts. + * @param ushort_t The variable that will store the array of unsigned shorts read from + * the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint16_t* ushort_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ushort_t), numElements); + } + + /*! + * @brief This function deserializes an array of unsigned shorts with a different + * endianness. + * @param ushort_t The variable that will store the array of unsigned shorts read from + * the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint16_t* ushort_t, size_t numElements, + Endianness endianness) + { + return deserializeArray(reinterpret_cast(ushort_t), numElements, + endianness); + } + + /*! + * @brief This function deserializes an array of shorts. + * @param short_t The variable that will store the array of shorts read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int16_t* short_t, size_t numElements); + + /*! + * @brief This function deserializes an array of shorts with a different endianness. + * @param short_t The variable that will store the array of shorts read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int16_t* short_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of unsigned longs. + * @param ulong_t The variable that will store the array of unsigned longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint32_t* ulong_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ulong_t), numElements); + } + + /*! + * @brief This function deserializes an array of unsigned longs with a different + * endianness. + * @param ulong_t The variable that will store the array of unsigned longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint32_t* ulong_t, size_t numElements, + Endianness endianness) + { + return deserializeArray(reinterpret_cast(ulong_t), numElements, endianness); + } + + /*! + * @brief This function deserializes an array of longs. + * @param long_t The variable that will store the array of longs read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int32_t* long_t, size_t numElements); + + /*! + * @brief This function deserializes an array of longs with a different endianness. + * @param long_t The variable that will store the array of longs read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int32_t* long_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of wide-chars. + * @param wchar The variable that will store the array of wide-chars read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(wchar_t* wchar, size_t numElements); + + /*! + * @brief This function deserializes an array of wide-chars with a different endianness. + * @param wchar The variable that will store the array of wide-chars read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(wchar_t* wchar, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of unsigned long longs. + * @param ulonglong_t The variable that will store the array of unsigned long longs read + * from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint64_t* ulonglong_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ulonglong_t), numElements); + } + + /*! + * @brief This function deserializes an array of unsigned long longs with a different + * endianness. + * @param ulonglong_t The variable that will store the array of unsigned long longs read + * from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(uint64_t* ulonglong_t, size_t numElements, + Endianness endianness) + { + return deserializeArray(reinterpret_cast(ulonglong_t), numElements, + endianness); + } + + /*! + * @brief This function deserializes an array of long longs. + * @param longlong_t The variable that will store the array of long longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int64_t* longlong_t, size_t numElements); + + /*! + * @brief This function deserializes an array of long longs with a different endianness. + * @param longlong_t The variable that will store the array of long longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(int64_t* longlong_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of floats. + * @param float_t The variable that will store the array of floats read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(float* float_t, size_t numElements); + + /*! + * @brief This function deserializes an array of floats with a different endianness. + * @param float_t The variable that will store the array of floats read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(float* float_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of doubles. + * @param double_t The variable that will store the array of doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(double* double_t, size_t numElements); + + /*! + * @brief This function deserializes an array of doubles with a different endianness. + * @param double_t The variable that will store the array of doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(double* double_t, size_t numElements, Endianness endianness); + + /*! + * @brief This function deserializes an array of long doubles. + * @param ldouble_t The variable that will store the array of long doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(long double* ldouble_t, size_t numElements); + + /*! + * @brief This function deserializes an array of long doubles with a different + * endianness. + * @param ldouble_t The variable that will store the array of long doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(long double* ldouble_t, size_t numElements, + Endianness endianness); + + /*! + * @brief This function deserializes an array of booleans. + * @param bool_t The variable that will store the array of booleans read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + Cdr& deserializeArray(bool* bool_t, size_t numElements); + + /*! + * @brief This function deserializes an array of booleans with a different endianness. + * @param bool_t The variable that will store the array of booleans read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(bool* bool_t, size_t numElements, Endianness endianness) + { + (void)endianness; + return deserializeArray(bool_t, numElements); + } + + /*! + * @brief This function deserializes an array of strings. + * @param string_t The variable that will store the array of strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(std::string* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(string_t[count]); + } + return *this; + } + + /*! + * @brief This function deserializes an array of wide-strings. + * @param string_t The variable that will store the array of wide-strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(std::wstring* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(string_t[count]); + } + return *this; + } + + /*! + * @brief This function deserializes an array of strings with a different endianness. + * @param string_t The variable that will store the array of strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(std::string* string_t, size_t numElements, + Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserializeArray(string_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function deserializes an array of wide-strings with a different + * endianness. + * @param string_t The variable that will store the array of wide-strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + inline Cdr& deserializeArray(std::wstring* string_t, size_t numElements, + Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserializeArray(string_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function deserializes an array of sequences of objects. + * @param vector_t The variable that will store the array of sequences of objects read + * from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeArray(std::vector<_T>* vector_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(vector_t[count]); + } + return *this; + } + + /*! + * @brief This function template deserializes an array of non-basic objects. + * @param type_t The variable that will store the array of objects read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeArray(_T* type_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + type_t[count].deserialize(*this); + } + return *this; + } + + /*! + * @brief This function template deserializes an array of non-basic objects with a + * different endianness. + * @param type_t The variable that will store the array of objects read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeArray(_T* type_t, size_t numElements, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserializeArray(type_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } - /*! - * @brief This operator deserializes a string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - std::string& string_t) - { - return deserialize(string_t); - } +#if !defined(_MSC_VER) && HAVE_CXX0X + /*! + * @brief This function template deserializes a string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeSequence(std::string*& sequence_t, size_t& numElements) + { + return deserializeStringSequence(sequence_t, numElements); + } + + /*! + * @brief This function template deserializes a wide-string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeSequence(std::wstring*& sequence_t, size_t& numElements) + { + return deserializeWStringSequence(sequence_t, numElements); + } + +#endif // if !defined(_MSC_VER) && HAVE_CXX0X + + /*! + * @brief This function template deserializes a raw sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeSequence(_T*& sequence_t, size_t& numElements) + { + uint32_t seqLength = 0; + state state_before_error(*this); + + deserialize(seqLength); + + try + { + sequence_t = reinterpret_cast<_T*>(calloc(seqLength, sizeof(_T))); + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + free(sequence_t); + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } + + numElements = seqLength; + return *this; + } - /*! - * @brief This operator deserializes a string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline Cdr& operator >>( - std::wstring& string_t) - { - return deserialize(string_t); - } +#ifdef _MSC_VER + /*! + * @brief This function template deserializes a string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template <> + Cdr& deserializeSequence(std::string*& sequence_t, size_t& numElements) + { + return deserializeStringSequence(sequence_t, numElements); + } + + /*! + * @brief This function template deserializes a wide-string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template <> + Cdr& deserializeSequence(std::wstring*& sequence_t, size_t& numElements) + { + return deserializeWStringSequence(sequence_t, numElements); + } + +#endif // ifdef _MSC_VER + + /*! + * @brief This function template deserializes a raw sequence with a different + * endianness. This function allocates memory to store the sequence. The user pointer + * will be set to point this allocated memory. The user will have to free this allocated + * memory using free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @param endianness Endianness that will be used in the deserialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeSequence(_T*& sequence_t, size_t& numElements, Endianness endianness) + { + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); + + try + { + deserializeSequence(sequence_t, numElements); + m_swapBytes = auxSwap; + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; + } -#if HAVE_CXX0X - /*! - * @brief This operator template is used to deserialize arrays. - * @param array_t The variable that will store the array read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator >>( - std::array<_T, _Size>& array_t) - { - return deserialize<_T, _Size>(array_t); - } +private: + Cdr(const Cdr&) = delete; -#endif // if HAVE_CXX0X + Cdr& operator=(const Cdr&) = delete; - /*! - * @brief This operator template is used to deserialize sequences. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator >>( - std::vector<_T>& vector_t) - { - return deserialize<_T>(vector_t); - } + Cdr& serializeBoolSequence(const std::vector& vector_t); - /*! - * @brief This operator template is used to deserialize maps. - * @param map_t The variable that will store the map read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator >>( - std::map<_K, _T>& map_t) - { - return deserialize<_K, _T>(map_t); - } + Cdr& deserializeBoolSequence(std::vector& vector_t); - /*! - * @brief This operator template is used to deserialize any other non-basic type. - * @param type_t The variable that will store the object read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& operator >>( - _T& type_t) - { - type_t.deserialize(*this); - return *this; - } + Cdr& deserializeStringSequence(std::string*& sequence_t, size_t& numElements); - /*! - * @brief This function serializes an octet. - * @param octet_t The value of the octet that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint8_t octet_t) - { - return serialize(static_cast(octet_t)); - } - - /*! - * @brief This function serializes an octet with a different endianness. - * @param octet_t The value of the octet that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint8_t octet_t, - Endianness endianness) - { - return serialize(static_cast(octet_t), endianness); - } - - /*! - * @brief This function serializes a character. - * @param char_t The value of the character that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const char char_t); - - /*! - * @brief This function serializes a character with a different endianness. - * @param char_t The value of the character that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const char char_t, - Endianness endianness) - { - (void) endianness; - return serialize(char_t); - } - - /*! - * @brief This function serializes an int8_t. - * @param int8 The value of the int8_t that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const int8_t int8) - { - return serialize(static_cast(int8)); - } - - /*! - * @brief This function serializes an int8_t with a different endianness. - * @param int8 The value of the int8_t that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const int8_t int8, - Endianness endianness) - { - return serialize(static_cast(int8), endianness); - } - - /*! - * @brief This function serializes an unsigned short. - * @param ushort_t The value of the unsigned short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint16_t ushort_t) - { - return serialize(static_cast(ushort_t)); - } - - /*! - * @brief This function serializes an unsigned short with a different endianness. - * @param ushort_t The value of the unsigned short that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint16_t ushort_t, - Endianness endianness) - { - return serialize(static_cast(ushort_t), endianness); - } - - /*! - * @brief This function serializes a short. - * @param short_t The value of the short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int16_t short_t); - - /*! - * @brief This function serializes a short with a different endianness. - * @param short_t The value of the short that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int16_t short_t, - Endianness endianness); - - /*! - * @brief This function serializes an unsigned long. - * @param ulong_t The value of the unsigned long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint32_t ulong_t) - { - return serialize(static_cast(ulong_t)); - } - - /*! - * @brief This function serializes an unsigned long with a different endianness. - * @param ulong_t The value of the unsigned long that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint32_t ulong_t, - Endianness endianness) - { - return serialize(static_cast(ulong_t), endianness); - } - - /*! - * @brief This function serializes a long. - * @param long_t The value of the long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int32_t long_t); - - /*! - * @brief This function serializes a long with a different endianness. - * @param long_t The value of the long that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int32_t long_t, - Endianness endianness); - - /*! - * @brief This function serializes a wide-char. - * @param wchar The value of the wide-char that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const wchar_t wchar) - { - return serialize(static_cast(wchar)); - } - - /*! - * @brief This function serializes a wide-char with a different endianness. - * @param wchar The value of the wide-char that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const wchar_t wchar, - Endianness endianness) - { - return serialize(static_cast(wchar), endianness); - } - - /*! - * @brief This function serializes an unsigned long long. - * @param ulonglong_t The value of the unsigned long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint64_t ulonglong_t) - { - return serialize(static_cast(ulonglong_t)); - } - - /*! - * @brief This function serializes an unsigned long long with a different endianness. - * @param ulonglong_t The value of the unsigned long long that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const uint64_t ulonglong_t, - Endianness endianness) - { - return serialize(static_cast(ulonglong_t), endianness); - } - - /*! - * @brief This function serializes a long long. - * @param longlong_t The value of the long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int64_t longlong_t); - - /*! - * @brief This function serializes a long long with a different endianness. - * @param longlong_t The value of the long long that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const int64_t longlong_t, - Endianness endianness); - - /*! - * @brief This function serializes a float. - * @param float_t The value of the float that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const float float_t); - - /*! - * @brief This function serializes a float with a different endianness. - * @param float_t The value of the float that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const float float_t, - Endianness endianness); - - /*! - * @brief This function serializes a double. - * @param double_t The value of the double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const double double_t); - - /*! - * @brief This function serializes a double with a different endianness. - * @param double_t The value of the double that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const double double_t, - Endianness endianness); - - - /*! - * @brief This function serializes a long double. - * @param ldouble_t The value of the long double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - * @note Due to internal representation differences, WIN32 and *NIX like systems are not compatible. - */ - Cdr& serialize( - const long double ldouble_t); - - /*! - * @brief This function serializes a long double with a different endianness. - * @param ldouble_t The value of the long double that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - * @note Due to internal representation differences, WIN32 and *NIX like systems are not compatible. - */ - Cdr& serialize( - const long double ldouble_t, - Endianness endianness); - - /*! - * @brief This function serializes a boolean. - * @param bool_t The value of the boolean that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const bool bool_t); - - /*! - * @brief This function serializes a boolean with a different endianness. - * @param bool_t The value of the boolean that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const bool bool_t, - Endianness endianness) - { - (void) endianness; - return serialize(bool_t); - } - - /*! - * @brief This function serializes a string. - * @param string_t The pointer to the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline Cdr& serialize( - char* string_t) - { - return serialize(static_cast(string_t)); - } - - /*! - * @brief This function serializes a string. - * @param string_t The pointer to the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const char* string_t); - - /*! - * @brief This function serializes a wstring. - * @param string_t The pointer to the wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const wchar_t* string_t); - - /*! - * @brief This function serializes a string with a different endianness. - * @param string_t The pointer to the string that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const char* string_t, - Endianness endianness); - - /*! - * @brief This function serializes a wstring with a different endianness. - * @param string_t The pointer to the wstring that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serialize( - const wchar_t* string_t, - Endianness endianness); - - /*! - * @brief This function serializes a std::string. - * @param string_t The string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const std::string& string_t) - { - return serialize(string_t.c_str()); - } - - /*! - * @brief This function serializes a std::wstring. - * @param string_t The wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const std::wstring& string_t) - { - return serialize(string_t.c_str()); - } - - /*! - * @brief This function serializes a std::string with a different endianness. - * @param string_t The string that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serialize( - const std::string& string_t, - Endianness endianness) - { - return serialize(string_t.c_str(), endianness); - } - -#if HAVE_CXX0X - /*! - * @brief This function template serializes an array. - * @param array_t The array that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& serialize( - const std::array<_T, _Size>& array_t) - { - return serializeArray(array_t.data(), array_t.size()); - } - - /*! - * @brief This function template serializes an array with a different endianness. - * @param array_t The array that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& serialize( - const std::array<_T, _Size>& array_t, - Endianness endianness) - { - return serializeArray(array_t.data(), array_t.size(), endianness); - } - -#endif // if HAVE_CXX0X - -#if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template serializes a sequence of booleans. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serialize( - const std::vector& vector_t) - { - return serializeBoolSequence(vector_t); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template serializes a sequence. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serialize( - const std::vector<_T>& vector_t) - { - state state_before_error(*this); - - *this << static_cast(vector_t.size()); - - try - { - return serializeArray(vector_t.data(), vector_t.size()); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template serializes a map. - * @param map_t The map that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serialize( - const std::map<_K, _T>& map_t) - { - state state_(*this); - - *this << static_cast(map_t.size()); - - try - { - for (auto it_pair = map_t.begin(); it_pair != map_t.end(); ++it_pair) - { - *this << it_pair->first; - *this << it_pair->second; - } - //return serializeArray(map_t.data(), map_t.size()); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_); - ex.raise(); - } - - return *this; - } - -#ifdef _MSC_VER - /*! - * @brief This function template serializes a sequence of booleans. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template<> - Cdr& serialize( - const std::vector& vector_t) - { - return serializeBoolSequence(vector_t); - } - -#endif // ifdef _MSC_VER - - /*! - * @brief This function template serializes a sequence with a different endianness. - * @param vector_t The sequence that will be serialized in the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serialize( - const std::vector<_T>& vector_t, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serialize(vector_t); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template serializes a non-basic object. - * @param type_t The object that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - inline Cdr& serialize( - const _T& type_t) - { - type_t.serialize(*this); - return *this; - } - - /*! - * @brief This function serializes an array of octets. - * @param octet_t The sequence of octets that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint8_t* octet_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(octet_t), numElements); - } - - /*! - * @brief This function serializes an array of octets with a different endianness. - * @param octet_t The array of octets that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint8_t* octet_t, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return serializeArray(reinterpret_cast(octet_t), numElements); - } - - /*! - * @brief This function serializes an array of characters. - * @param char_t The array of characters that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const char* char_t, - size_t numElements); - - /*! - * @brief This function serializes an array of characters with a different endianness. - * @param char_t The array of characters that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const char* char_t, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return serializeArray(char_t, numElements); - } - - /*! - * @brief This function serializes an array of int8_t. - * @param int8 The sequence of int8_t that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const int8_t* int8, - size_t numElements) - { - return serializeArray(reinterpret_cast(int8), numElements); - } - - /*! - * @brief This function serializes an array of int8_t with a different endianness. - * @param int8 The array of int8_t that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const int8_t* int8, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return serializeArray(reinterpret_cast(int8), numElements); - } - - /*! - * @brief This function serializes an array of unsigned shorts. - * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint16_t* ushort_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ushort_t), numElements); - } - - /*! - * @brief This function serializes an array of unsigned shorts with a different endianness. - * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint16_t* ushort_t, - size_t numElements, - Endianness endianness) - { - return serializeArray(reinterpret_cast(ushort_t), numElements, endianness); - } - - /*! - * @brief This function serializes an array of shorts. - * @param short_t The array of shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int16_t* short_t, - size_t numElements); - - /*! - * @brief This function serializes an array of shorts with a different endianness. - * @param short_t The array of shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int16_t* short_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of unsigned longs. - * @param ulong_t The array of unsigned longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint32_t* ulong_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ulong_t), numElements); - } - - /*! - * @brief This function serializes an array of unsigned longs with a different endianness. - * @param ulong_t The array of unsigned longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint32_t* ulong_t, - size_t numElements, - Endianness endianness) - { - return serializeArray(reinterpret_cast(ulong_t), numElements, endianness); - } - - /*! - * @brief This function serializes an array of longs. - * @param long_t The array of longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int32_t* long_t, - size_t numElements); - - /*! - * @brief This function serializes an array of longs with a different endianness. - * @param long_t The array of longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int32_t* long_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of wide-chars. - * @param wchar The array of wide-chars that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const wchar_t* wchar, - size_t numElements); - - /*! - * @brief This function serializes an array of wide-chars with a different endianness. - * @param wchar The array of longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const wchar_t* wchar, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of unsigned long longs. - * @param ulonglong_t The array of unsigned long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint64_t* ulonglong_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ulonglong_t), numElements); - } - - /*! - * @brief This function serializes an array of unsigned long longs with a different endianness. - * @param ulonglong_t The array of unsigned long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const uint64_t* ulonglong_t, - size_t numElements, - Endianness endianness) - { - return serializeArray(reinterpret_cast(ulonglong_t), numElements, endianness); - } - - /*! - * @brief This function serializes an array of long longs. - * @param longlong_t The array of long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int64_t* longlong_t, - size_t numElements); - - /*! - * @brief This function serializes an array of long longs with a different endianness. - * @param longlong_t The array of long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const int64_t* longlong_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of floats. - * @param float_t The array of floats that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const float* float_t, - size_t numElements); - - /*! - * @brief This function serializes an array of floats with a different endianness. - * @param float_t The array of floats that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const float* float_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of doubles. - * @param double_t The array of doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const double* double_t, - size_t numElements); - - /*! - * @brief This function serializes an array of doubles with a different endianness. - * @param double_t The array of doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const double* double_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of long doubles. - * @param ldouble_t The array of long doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const long double* ldouble_t, - size_t numElements); - - /*! - * @brief This function serializes an array of long doubles with a different endianness. - * @param ldouble_t The array of long doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const long double* ldouble_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function serializes an array of booleans. - * @param bool_t The array of booleans that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - Cdr& serializeArray( - const bool* bool_t, - size_t numElements); - - /*! - * @brief This function serializes an array of booleans with a different endianness. - * @param bool_t The array of booleans that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const bool* bool_t, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return serializeArray(bool_t, numElements); - } - - /*! - * @brief This function serializes an array of strings. - * @param string_t The array of strings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const std::string* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(string_t[count].c_str()); - } - return *this; - } - - /*! - * @brief This function serializes an array of wide-strings. - * @param string_t The array of wide-strings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const std::wstring* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(string_t[count].c_str()); - } - return *this; - } - - /*! - * @brief This function serializes an array of strings with a different endianness. - * @param string_t The array of strings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const std::string* string_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serializeArray(string_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function serializes an array of wide-strings with a different endianness. - * @param string_t The array of wide-strings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - inline - Cdr& serializeArray( - const std::wstring* string_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serializeArray(string_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template serializes an array of sequences of objects. - * @param vector_t The array of sequences of objects that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeArray( - const std::vector<_T>* vector_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(vector_t[count]); - } - return *this; - } - - /*! - * @brief This function template serializes an array of non-basic objects. - * @param type_t The array of objects that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeArray( - const _T* type_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - type_t[count].serialize(*this); - } - return *this; - } - - /*! - * @brief This function template serializes an array of non-basic objects with a different endianness. - * @param type_t The array of objects that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeArray( - const _T* type_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serializeArray(type_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template serializes a raw sequence. - * @param sequence_t Pointer to the sequence that will be serialized in the buffer. - * @param numElements The number of elements contained in the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeSequence( - const _T* sequence_t, - size_t numElements) - { - state state_before_error(*this); - - serialize(static_cast(numElements)); - - try - { - return serializeArray(sequence_t, numElements); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template serializes a raw sequence with a different endianness. - * @param sequence_t Pointer to the sequence that will be serialized in the buffer. - * @param numElements The number of elements contained in the sequence. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeSequence( - const _T* sequence_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serializeSequence(sequence_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function deserializes an octet. - * @param octet_t The variable that will store the octet read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint8_t& octet_t) - { - return deserialize(reinterpret_cast(octet_t)); - } - - /*! - * @brief This function deserializes an octet with a different endianness. - * @param octet_t The variable that will store the octet read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint8_t& octet_t, - Endianness endianness) - { - return deserialize(reinterpret_cast(octet_t), endianness); - } - - /*! - * @brief This function deserializes a character. - * @param char_t The variable that will store the character read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - char& char_t); - - /*! - * @brief This function deserializes a character with a different endianness. - * @param char_t The variable that will store the character read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - char& char_t, - Endianness endianness) - { - (void) endianness; - return deserialize(char_t); - } - - /*! - * @brief This function deserializes an int8_t. - * @param int8 The variable that will store the int8_t read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - int8_t& int8) - { - return deserialize(reinterpret_cast(int8)); - } - - /*! - * @brief This function deserializes an int8_t with a different endianness. - * @param int8 The variable that will store the int8_t read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - int8_t& int8, - Endianness endianness) - { - return deserialize(reinterpret_cast(int8), endianness); - } - - /*! - * @brief This function deserializes an unsigned short. - * @param ushort_t The variable that will store the unsigned short read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint16_t& ushort_t) - { - return deserialize(reinterpret_cast(ushort_t)); - } - - /*! - * @brief This function deserializes an unsigned short with a different endianness. - * @param ushort_t The variable that will store the unsigned short read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint16_t& ushort_t, - Endianness endianness) - { - return deserialize(reinterpret_cast(ushort_t), endianness); - } - - /*! - * @brief This function deserializes a short. - * @param short_t The variable that will store the short read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int16_t& short_t); - - /*! - * @brief This function deserializes a short with a different endianness. - * @param short_t The variable that will store the short read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int16_t& short_t, - Endianness endianness); - - /*! - * @brief This function deserializes an unsigned long. - * @param ulong_t The variable that will store the unsigned long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint32_t& ulong_t) - { - return deserialize(reinterpret_cast(ulong_t)); - } - - /*! - * @brief This function deserializes an unsigned long with a different endianness. - * @param ulong_t The variable that will store the unsigned long read from the buffer.. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint32_t& ulong_t, - Endianness endianness) - { - return deserialize(reinterpret_cast(ulong_t), endianness); - } - - /*! - * @brief This function deserializes a long. - * @param long_t The variable that will store the long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int32_t& long_t); - - /*! - * @brief This function deserializes a long with a different endianness. - * @param long_t The variable that will store the long read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int32_t& long_t, - Endianness endianness); - - /*! - * @brief This function deserializes a wide-char. - * @param wchar The variable that will store the wide-char read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - wchar_t& wchar) - { - uint32_t ret; - deserialize(ret); - wchar = static_cast(ret); - return *this; - } - - /*! - * @brief This function deserializes a wide-char with a different endianness. - * @param wchar The variable that will store the wide-char read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - wchar_t& wchar, - Endianness endianness) - { - uint32_t ret; - deserialize(ret, endianness); - wchar = static_cast(ret); - return *this; - } - - /*! - * @brief This function deserializes an unsigned long long. - * @param ulonglong_t The variable that will store the unsigned long long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint64_t& ulonglong_t) - { - return deserialize(reinterpret_cast(ulonglong_t)); - } - - /*! - * @brief This function deserializes an unsigned long long with a different endianness. - * @param ulonglong_t The variable that will store the unsigned long long read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - uint64_t& ulonglong_t, - Endianness endianness) - { - return deserialize(reinterpret_cast(ulonglong_t), endianness); - } - - /*! - * @brief This function deserializes a long long. - * @param longlong_t The variable that will store the long long read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int64_t& longlong_t); - - /*! - * @brief This function deserializes a long long with a different endianness. - * @param longlong_t The variable that will store the long long read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - int64_t& longlong_t, - Endianness endianness); - - /*! - * @brief This function deserializes a float. - * @param float_t The variable that will store the float read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - float& float_t); - - /*! - * @brief This function deserializes a float with a different endianness. - * @param float_t The variable that will store the float read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - float& float_t, - Endianness endianness); - - /*! - * @brief This function deserializes a double. - * @param double_t The variable that will store the double read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - double& double_t); - - /*! - * @brief This function deserializes a double with a different endianness. - * @param double_t The variable that will store the double read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - double& double_t, - Endianness endianness); - - /*! - * @brief This function deserializes a long double. - * @param ldouble_t The variable that will store the long double read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @note Due to internal representation differences, WIN32 and *NIX like systems are not compatible. - */ - Cdr& deserialize( - long double& ldouble_t); - - /*! - * @brief This function deserializes a long double with a different endianness. - * @param ldouble_t The variable that will store the long double read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @note Due to internal representation differences, WIN32 and *NIX like systems are not compatible. - */ - Cdr& deserialize( - long double& ldouble_t, - Endianness endianness); - - /*! - * @brief This function deserializes a boolean. - * @param bool_t The variable that will store the boolean read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - Cdr& deserialize( - bool& bool_t); - - /*! - * @brief This function deserializes a boolean with a different endianness. - * @param bool_t The variable that will store the boolean read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - inline - Cdr& deserialize( - bool& bool_t, - Endianness endianness) - { - (void) endianness; - return deserialize(bool_t); - } - - /*! - * @brief This function deserializes a string. - * This function allocates memory to store the string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the string read from the buffer. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - char*& string_t); - - /*! - * @brief This function deserializes a wide string. - * This function allocates memory to store the wide string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the wide string read from the buffer. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - wchar_t*& string_t); - - /*! - * @brief This function deserializes a string with a different endianness. - * This function allocates memory to store the string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the string read from the buffer. - * @param endianness Endianness that will be used in the deserialization of this value. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - char*& string_t, - Endianness endianness); - - /*! - * @brief This function deserializes a wide string with a different endianness. - * This function allocates memory to store the wide string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the wide string read from the buffer. - * @param endianness Endianness that will be used in the deserialization of this value. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserialize( - wchar_t*& string_t, - Endianness endianness); - - /*! - * @brief This function deserializes a std::string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - std::string& string_t) - { - uint32_t length = 0; - const char* str = readString(length); - string_t = std::string(str, length); - return *this; - } - - /*! - * @brief This function deserializes a std::string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - std::wstring& string_t) - { - uint32_t length = 0; - string_t = readWString(length); - return *this; - } - - /*! - * @brief This function deserializes a string with a different endianness. - * @param string_t The variable that will store the string read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - std::string& string_t, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserialize(string_t); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function deserializes a string with a different endianness. - * @param string_t The variable that will store the string read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserialize( - std::wstring& string_t, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserialize(string_t); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - -#if HAVE_CXX0X - /*! - * @brief This function template deserializes an array. - * @param array_t The variable that will store the array read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& deserialize( - std::array<_T, _Size>& array_t) - { - return deserializeArray(array_t.data(), array_t.size()); - } - - /*! - * @brief This function template deserializes an array with a different endianness. - * @param array_t The variable that will store the array read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& deserialize( - std::array<_T, _Size>& array_t, - Endianness endianness) - { - return deserializeArray(array_t.data(), array_t.size(), endianness); - } - -#endif // if HAVE_CXX0X - -#if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template deserializes a sequence. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserialize( - std::vector& vector_t) - { - return deserializeBoolSequence(vector_t); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template deserializes a sequence. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserialize( - std::vector<_T>& vector_t) - { - uint32_t seqLength = 0; - state state_before_error(*this); - - *this >> seqLength; - - if (seqLength == 0) - { - vector_t.clear(); - return *this; - } - - if ((m_lastPosition - m_currentPosition) < seqLength) - { - setState(state_before_error); - throw eprosima::fastcdr::exception::NotEnoughMemoryException( - eprosima::fastcdr::exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - try - { - vector_t.resize(seqLength); - return deserializeArray(vector_t.data(), vector_t.size()); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template deserializes a map. - * @param map_t The variable that will store the map read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserialize( - std::map<_K, _T>& map_t) - { - uint32_t seqLength = 0; - state state_(*this); - - *this >> seqLength; - - try - { - for (uint32_t i = 0; i < seqLength; ++i) - { - _K key; - _T value; - *this >> key; - *this >> value; - map_t.emplace(std::pair<_K, _T>(std::move(key), std::move(value))); - } - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_); - ex.raise(); - } - - return *this; - } - -#ifdef _MSC_VER - /*! - * @brief This function template deserializes a sequence. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template<> - Cdr& deserialize( - std::vector& vector_t) - { - return deserializeBoolSequence(vector_t); - } - -#endif // ifdef _MSC_VER - - /*! - * @brief This function template deserializes a sequence with a different endianness. - * @param vector_t The variable that will store the sequence read from the buffer. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserialize( - std::vector<_T>& vector_t, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserialize(vector_t); - m_swapBytes = auxSwap; - } - catch (exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function template deserializes a non-basic object. - * @param type_t The variable that will store the object read from the buffer. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - inline Cdr& deserialize( - _T& type_t) - { - type_t.deserialize(*this); - return *this; - } - - /*! - * @brief This function deserializes an array of octets. - * @param octet_t The variable that will store the array of octets read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint8_t* octet_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(octet_t), numElements); - } - - /*! - * @brief This function deserializes an array of octets with a different endianness. - * @param octet_t The variable that will store the array of octets read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint8_t* octet_t, - size_t numElements, - Endianness endianness) - { - return deserializeArray(reinterpret_cast(octet_t), numElements, endianness); - } - - /*! - * @brief This function deserializes an array of characters. - * @param char_t The variable that will store the array of characters read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - char* char_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of characters with a different endianness. - * @param char_t The variable that will store the array of characters read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - char* char_t, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return deserializeArray(char_t, numElements); - } - - /*! - * @brief This function deserializes an array of int8_t. - * @param int8 The variable that will store the array of int8_t read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - int8_t* int8, - size_t numElements) - { - return deserializeArray(reinterpret_cast(int8), numElements); - } - - /*! - * @brief This function deserializes an array of int8_t with a different endianness. - * @param int8 The variable that will store the array of int8_t read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - int8_t* int8, - size_t numElements, - Endianness endianness) - { - return deserializeArray(reinterpret_cast(int8), numElements, endianness); - } - - /*! - * @brief This function deserializes an array of unsigned shorts. - * @param ushort_t The variable that will store the array of unsigned shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint16_t* ushort_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ushort_t), numElements); - } - - /*! - * @brief This function deserializes an array of unsigned shorts with a different endianness. - * @param ushort_t The variable that will store the array of unsigned shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint16_t* ushort_t, - size_t numElements, - Endianness endianness) - { - return deserializeArray(reinterpret_cast(ushort_t), numElements, endianness); - } - - /*! - * @brief This function deserializes an array of shorts. - * @param short_t The variable that will store the array of shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int16_t* short_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of shorts with a different endianness. - * @param short_t The variable that will store the array of shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int16_t* short_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of unsigned longs. - * @param ulong_t The variable that will store the array of unsigned longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint32_t* ulong_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ulong_t), numElements); - } - - /*! - * @brief This function deserializes an array of unsigned longs with a different endianness. - * @param ulong_t The variable that will store the array of unsigned longs read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint32_t* ulong_t, - size_t numElements, - Endianness endianness) - { - return deserializeArray(reinterpret_cast(ulong_t), numElements, endianness); - } - - /*! - * @brief This function deserializes an array of longs. - * @param long_t The variable that will store the array of longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int32_t* long_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of longs with a different endianness. - * @param long_t The variable that will store the array of longs read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int32_t* long_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of wide-chars. - * @param wchar The variable that will store the array of wide-chars read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - wchar_t* wchar, - size_t numElements); - - /*! - * @brief This function deserializes an array of wide-chars with a different endianness. - * @param wchar The variable that will store the array of wide-chars read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - wchar_t* wchar, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of unsigned long longs. - * @param ulonglong_t The variable that will store the array of unsigned long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint64_t* ulonglong_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ulonglong_t), numElements); - } - - /*! - * @brief This function deserializes an array of unsigned long longs with a different endianness. - * @param ulonglong_t The variable that will store the array of unsigned long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - uint64_t* ulonglong_t, - size_t numElements, - Endianness endianness) - { - return deserializeArray(reinterpret_cast(ulonglong_t), numElements, endianness); - } - - /*! - * @brief This function deserializes an array of long longs. - * @param longlong_t The variable that will store the array of long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int64_t* longlong_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of long longs with a different endianness. - * @param longlong_t The variable that will store the array of long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - int64_t* longlong_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of floats. - * @param float_t The variable that will store the array of floats read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - float* float_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of floats with a different endianness. - * @param float_t The variable that will store the array of floats read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - float* float_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of doubles. - * @param double_t The variable that will store the array of doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - double* double_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of doubles with a different endianness. - * @param double_t The variable that will store the array of doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - double* double_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of long doubles. - * @param ldouble_t The variable that will store the array of long doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - long double* ldouble_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of long doubles with a different endianness. - * @param ldouble_t The variable that will store the array of long doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - long double* ldouble_t, - size_t numElements, - Endianness endianness); - - /*! - * @brief This function deserializes an array of booleans. - * @param bool_t The variable that will store the array of booleans read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - Cdr& deserializeArray( - bool* bool_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of booleans with a different endianness. - * @param bool_t The variable that will store the array of booleans read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - bool* bool_t, - size_t numElements, - Endianness endianness) - { - (void) endianness; - return deserializeArray(bool_t, numElements); - } - - /*! - * @brief This function deserializes an array of strings. - * @param string_t The variable that will store the array of strings read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - std::string* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(string_t[count]); - } - return *this; - } - - /*! - * @brief This function deserializes an array of wide-strings. - * @param string_t The variable that will store the array of wide-strings read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - std::wstring* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(string_t[count]); - } - return *this; - } - - /*! - * @brief This function deserializes an array of strings with a different endianness. - * @param string_t The variable that will store the array of strings read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - std::string* string_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserializeArray(string_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function deserializes an array of wide-strings with a different endianness. - * @param string_t The variable that will store the array of wide-strings read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - inline - Cdr& deserializeArray( - std::wstring* string_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserializeArray(string_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function deserializes an array of sequences of objects. - * @param vector_t The variable that will store the array of sequences of objects read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeArray( - std::vector<_T>* vector_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(vector_t[count]); - } - return *this; - } - - /*! - * @brief This function template deserializes an array of non-basic objects. - * @param type_t The variable that will store the array of objects read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeArray( - _T* type_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - type_t[count].deserialize(*this); - } - return *this; - } - - /*! - * @brief This function template deserializes an array of non-basic objects with a different endianness. - * @param type_t The variable that will store the array of objects read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeArray( - _T* type_t, - size_t numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserializeArray(type_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - -#if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template deserializes a string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeSequence( - std::string*& sequence_t, - size_t& numElements) - { - return deserializeStringSequence(sequence_t, numElements); - } - - /*! - * @brief This function template deserializes a wide-string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeSequence( - std::wstring*& sequence_t, - size_t& numElements) - { - return deserializeWStringSequence(sequence_t, numElements); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template deserializes a raw sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeSequence( - _T*& sequence_t, - size_t& numElements) - { - uint32_t seqLength = 0; - state state_before_error(*this); - - deserialize(seqLength); - - try - { - sequence_t = reinterpret_cast<_T*>(calloc(seqLength, sizeof(_T))); - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - free(sequence_t); - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } - - numElements = seqLength; - return *this; - } - -#ifdef _MSC_VER - /*! - * @brief This function template deserializes a string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template<> - Cdr& deserializeSequence( - std::string*& sequence_t, - size_t& numElements) - { - return deserializeStringSequence(sequence_t, numElements); - } - - /*! - * @brief This function template deserializes a wide-string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template<> - Cdr& deserializeSequence( - std::wstring*& sequence_t, - size_t& numElements) - { - return deserializeWStringSequence(sequence_t, numElements); - } - -#endif // ifdef _MSC_VER - - /*! - * @brief This function template deserializes a raw sequence with a different endianness. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @param endianness Endianness that will be used in the deserialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeSequence( - _T*& sequence_t, - size_t& numElements, - Endianness endianness) - { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserializeSequence(sequence_t, numElements); - m_swapBytes = auxSwap; - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - - return *this; - } - -private: - - Cdr( - const Cdr&) = delete; - - Cdr& operator =( - const Cdr&) = delete; - - Cdr& serializeBoolSequence( - const std::vector& vector_t); - - Cdr& deserializeBoolSequence( - std::vector& vector_t); - - Cdr& deserializeStringSequence( - std::string*& sequence_t, - size_t& numElements); - - Cdr& deserializeWStringSequence( - std::wstring*& sequence_t, - size_t& numElements); + Cdr& deserializeWStringSequence(std::wstring*& sequence_t, size_t& numElements); #if HAVE_CXX0X - /*! - * @brief This function template detects the content type of the STD container array and serializes the array. - * @param array_t The array that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeArray( - const std::array<_T, _Size>* array_t, - size_t numElements) - { - return serializeArray(array_t->data(), numElements * array_t->size()); - } - - /*! - * @brief This function template detects the content type of the STD container array and serializes the array with a different endianness. - * @param array_t The array that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize a position that exceeds the internal memory size. - */ - template - Cdr& serializeArray( - const std::array<_T, _Size>* array_t, - size_t numElements, - Endianness endianness) - { - return serializeArray(array_t->data(), numElements * array_t->size(), endianness); - } - - /*! - * @brief This function template detects the content type of the STD container array and deserializes the array. - * @param array_t The variable that will store the array read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeArray( - std::array<_T, _Size>* array_t, - size_t numElements) - { - return deserializeArray(array_t->data(), numElements * array_t->size()); - } - - /*! - * @brief This function template detects the content type of STD container array and deserializes the array with a different endianness. - * @param array_t The variable that will store the array read from the buffer. - * @param numElements Number of the elements in the array. - * @param endianness Endianness that will be used in the serialization of this value. - * @return Reference to the eprosima::fastcdr::Cdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - */ - template - Cdr& deserializeArray( - std::array<_T, _Size>* array_t, - size_t numElements, - Endianness endianness) - { - return deserializeArray(array_t->data(), numElements * array_t->size(), endianness); - } - -#endif // if HAVE_CXX0X - - /*! - * @brief This function returns the extra bytes regarding the allignment. - * @param dataSize The size of the data that will be serialized. - * @return The size needed for the aligment. - */ - inline size_t alignment( - size_t dataSize) const - { - return dataSize > - m_lastDataSize ? (dataSize - ((m_currentPosition - m_alignPosition) % dataSize)) & - (dataSize - 1) : 0; - } - - /*! - * @brief This function jumps the number of bytes of the alignment. These bytes should be calculated with the function eprosima::fastcdr::Cdr::alignment. - * @param align The number of bytes to be skipped. - */ - inline void makeAlign( - size_t align) - { - m_currentPosition += align; - } - - /*! - * @brief This function resizes the internal buffer. It only applies if the FastBuffer object was created with the default constructor. - * @param minSizeInc Minimun size increase for the internal buffer - * @return True if the resize was succesful, false if it was not - */ - bool resize( - size_t minSizeInc); - - //TODO - const char* readString( - uint32_t& length); - const std::wstring readWString( - uint32_t& length); - - //! @brief Reference to the buffer that will be serialized/deserialized. - FastBuffer& m_cdrBuffer; - - //! @brief The type of CDR that will be use in serialization/deserialization. - CdrType m_cdrType; - - //! @brief Using DDS_CDR type, this attribute stores if the stream buffer contains a parameter list or not. - DDSCdrPlFlag m_plFlag; - - //! @brief This attribute stores the option flags when the CDR type is DDS_CDR; - uint16_t m_options; - - //! @brief The endianness that will be applied over the buffer. - uint8_t m_endianness; - - //! @brief This attribute specifies if it is needed to swap the bytes. - bool m_swapBytes; - - //! @brief Stores the last datasize serialized/deserialized. It's used to optimize. - size_t m_lastDataSize; - - //! @brief The current position in the serialization/deserialization process. - FastBuffer::iterator m_currentPosition; - - //! @brief The position from where the aligment is calculated. - FastBuffer::iterator m_alignPosition; - - //! @brief The last position in the buffer; - FastBuffer::iterator m_lastPosition; + /*! + * @brief This function template detects the content type of the STD container array and + * serializes the array. + * @param array_t The array that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeArray(const std::array<_T, _Size>* array_t, size_t numElements) + { + return serializeArray(array_t->data(), numElements * array_t->size()); + } + + /*! + * @brief This function template detects the content type of the STD container array and + * serializes the array with a different endianness. + * @param array_t The array that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize a position that exceeds the internal memory size. + */ + template + Cdr& serializeArray(const std::array<_T, _Size>* array_t, size_t numElements, + Endianness endianness) + { + return serializeArray(array_t->data(), numElements * array_t->size(), endianness); + } + + /*! + * @brief This function template detects the content type of the STD container array and + * deserializes the array. + * @param array_t The variable that will store the array read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeArray(std::array<_T, _Size>* array_t, size_t numElements) + { + return deserializeArray(array_t->data(), numElements * array_t->size()); + } + + /*! + * @brief This function template detects the content type of STD container array and + * deserializes the array with a different endianness. + * @param array_t The variable that will store the array read from the buffer. + * @param numElements Number of the elements in the array. + * @param endianness Endianness that will be used in the serialization of this value. + * @return Reference to the eprosima::fastcdr::Cdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + */ + template + Cdr& deserializeArray(std::array<_T, _Size>* array_t, size_t numElements, + Endianness endianness) + { + return deserializeArray(array_t->data(), numElements * array_t->size(), endianness); + } + +#endif // if HAVE_CXX0X + + /*! + * @brief This function returns the extra bytes regarding the allignment. + * @param dataSize The size of the data that will be serialized. + * @return The size needed for the aligment. + */ + inline size_t alignment(size_t dataSize) const + { + return dataSize > m_lastDataSize ? + (dataSize - ((m_currentPosition - m_alignPosition) % dataSize)) & + (dataSize - 1) : + 0; + } + + /*! + * @brief This function jumps the number of bytes of the alignment. These bytes should + * be calculated with the function eprosima::fastcdr::Cdr::alignment. + * @param align The number of bytes to be skipped. + */ + inline void makeAlign(size_t align) + { + m_currentPosition += align; + } + + /*! + * @brief This function resizes the internal buffer. It only applies if the FastBuffer + * object was created with the default constructor. + * @param minSizeInc Minimun size increase for the internal buffer + * @return True if the resize was succesful, false if it was not + */ + bool resize(size_t minSizeInc); + + // TODO + const char* readString(uint32_t& length); + const std::wstring readWString(uint32_t& length); + + //! @brief Reference to the buffer that will be serialized/deserialized. + FastBuffer& m_cdrBuffer; + + //! @brief The type of CDR that will be use in serialization/deserialization. + CdrType m_cdrType; + + //! @brief Using DDS_CDR type, this attribute stores if the stream buffer contains a + //! parameter list or not. + DDSCdrPlFlag m_plFlag; + + //! @brief This attribute stores the option flags when the CDR type is DDS_CDR; + uint16_t m_options; + + //! @brief The endianness that will be applied over the buffer. + uint8_t m_endianness; + + //! @brief This attribute specifies if it is needed to swap the bytes. + bool m_swapBytes; + + //! @brief Stores the last datasize serialized/deserialized. It's used to optimize. + size_t m_lastDataSize; + + //! @brief The current position in the serialization/deserialization process. + FastBuffer::iterator m_currentPosition; + + //! @brief The position from where the aligment is calculated. + FastBuffer::iterator m_alignPosition; + + //! @brief The last position in the buffer; + FastBuffer::iterator m_lastPosition; }; -} //namespace fastcdr -} //namespace eprosima +} // namespace fastcdr +} // namespace eprosima -#endif // _CDR_CDR_H_ +#endif // _CDR_CDR_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastBuffer.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastBuffer.h index ba5fe6d38..fe969dee5 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastBuffer.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastBuffer.h @@ -22,201 +22,180 @@ #include #include -inline uint32_t size_to_uint32( - size_t val) +inline uint32_t size_to_uint32(size_t val) { - #if defined(_WIN32) || !defined(FASTCDR_ARM32) - // On 64 bit platforms and all Windows architectures (because of C4267), explicitly cast. - return static_cast(val); - #else - // Skip useless cast on 32-bit builds. - return val; - #endif // if defined(_WIN32) || !defined(FASTCDR_ARM32) +#if defined(_WIN32) || !defined(FASTCDR_ARM32) + // On 64 bit platforms and all Windows architectures (because of C4267), explicitly + // cast. + return static_cast(val); +#else + // Skip useless cast on 32-bit builds. + return val; +#endif // if defined(_WIN32) || !defined(FASTCDR_ARM32) } -namespace eprosima { -namespace fastcdr { +namespace eprosima +{ +namespace fastcdr +{ /*! * @brief This class implements the iterator used to go through a FastBuffer. */ class Cdr_DllAPI _FastBuffer_iterator { public: - - /*! - * @brief Default constructor. - * The iterator points any position. - */ - _FastBuffer_iterator() - : m_buffer(NULL) - , m_currentPosition(NULL) - { - } - - /*! - * @brief Constructor. - * The iterator points to the indicated position. - * @param buffer Pointer to the raw buffer. - * @param index Position of the raw buffer where the iterator will point. - */ - explicit _FastBuffer_iterator( - char* buffer, - size_t index) - : m_buffer(buffer) - , m_currentPosition(&m_buffer[index]) - { - } - - /*! - * @brief This operator changes the iterator's raw buffer. - * This operator makes the iterator point to the same position but in another raw buffer. - * The new raw buffer is the same than the source iterator's. - * @param iterator The source iterator. The iterator will use the source iterator's raw buffer after this operation. - */ - inline - void operator <<( - const _FastBuffer_iterator& iterator) - { - ptrdiff_t diff = m_currentPosition - m_buffer; - m_buffer = iterator.m_buffer; - m_currentPosition = m_buffer + diff; - } - - /*! - * @brief This operator changes the position where the iterator points. - * This operator takes the index of the source iterator, but the iterator continues using its raw buffer. - * @param iterator The source iterator. The iterator will use the source's iterator index to point to its own raw buffer. - */ - inline - void operator >>( - const _FastBuffer_iterator& iterator) - { - ptrdiff_t diff = iterator.m_currentPosition - iterator.m_buffer; - m_currentPosition = m_buffer + diff; - } - - /*! - * @brief This operator copies a data in the raw buffer. - * The copy uses the size of the data type. - * @param data Data to be copied. Cannot be NULL. - */ - template - inline - void operator <<( - const _T& data) + /*! + * @brief Default constructor. + * The iterator points any position. + */ + _FastBuffer_iterator() : m_buffer(NULL), m_currentPosition(NULL) + { + } + + /*! + * @brief Constructor. + * The iterator points to the indicated position. + * @param buffer Pointer to the raw buffer. + * @param index Position of the raw buffer where the iterator will point. + */ + explicit _FastBuffer_iterator(char* buffer, size_t index) + : m_buffer(buffer), m_currentPosition(&m_buffer[index]) + { + } + + /*! + * @brief This operator changes the iterator's raw buffer. + * This operator makes the iterator point to the same position but in another raw + * buffer. The new raw buffer is the same than the source iterator's. + * @param iterator The source iterator. The iterator will use the source iterator's raw + * buffer after this operation. + */ + inline void operator<<(const _FastBuffer_iterator& iterator) + { + ptrdiff_t diff = m_currentPosition - m_buffer; + m_buffer = iterator.m_buffer; + m_currentPosition = m_buffer + diff; + } + + /*! + * @brief This operator changes the position where the iterator points. + * This operator takes the index of the source iterator, but the iterator continues + * using its raw buffer. + * @param iterator The source iterator. The iterator will use the source's iterator + * index to point to its own raw buffer. + */ + inline void operator>>(const _FastBuffer_iterator& iterator) + { + ptrdiff_t diff = iterator.m_currentPosition - iterator.m_buffer; + m_currentPosition = m_buffer + diff; + } + + /*! + * @brief This operator copies a data in the raw buffer. + * The copy uses the size of the data type. + * @param data Data to be copied. Cannot be NULL. + */ + template + inline void operator<<(const _T& data) + { + memcpy(m_currentPosition, &data, sizeof(_T)); + } + + /*! + * @brief This operator copies data from the raw buffer to a variable. + * The copy uses the size of the data type. + * @param data Data to be filled. + */ + template + inline void operator>>(_T& data) + { + memcpy(&data, m_currentPosition, sizeof(_T)); + } + + /*! + * @brief This function copies a buffer into the raw buffer. + * @param src The source buffer. + * @param size The number of bytes to be copied. + */ + inline void memcopy(const void* src, const size_t size) + { + if (size > 0) { - memcpy(m_currentPosition, &data, sizeof(_T)); + memcpy(m_currentPosition, src, size); } - - /*! - * @brief This operator copies data from the raw buffer to a variable. - * The copy uses the size of the data type. - * @param data Data to be filled. - */ - template - inline - void operator >>( - _T& data) - { - memcpy(&data, m_currentPosition, sizeof(_T)); - } - - /*! - * @brief This function copies a buffer into the raw buffer. - * @param src The source buffer. - * @param size The number of bytes to be copied. - */ - inline - void memcopy( - const void* src, - const size_t size) + } + + /*! + * @brief This function copies from the raw buffer to a external buffer. + * @param dst The destination buffer. + * @param size The size of bytes to be copied. + */ + inline void rmemcopy(void* dst, const size_t size) + { + if (size > 0) { - if (size > 0) - { - memcpy(m_currentPosition, src, size); - } - } - - /*! - * @brief This function copies from the raw buffer to a external buffer. - * @param dst The destination buffer. - * @param size The size of bytes to be copied. - */ - inline - void rmemcopy( - void* dst, - const size_t size) - { - if (size > 0) - { - memcpy(dst, m_currentPosition, size); - } - } - - /*! - * @brief This function increments the position where the iterator points. - * @param numBytes Number of bytes the iterator moves the position. - */ - inline - void operator +=( - size_t numBytes) - { - m_currentPosition += numBytes; - } - - /*! - * @brief This operator returns the subtraction of the current interator's position and the source iterator's position. - * @param it Source iterator whose position is subtracted to the current iterator's position. - * @return The result of subtract the current iterator's position and the source iterator's position. - */ - inline - size_t operator -( - const _FastBuffer_iterator& it) const - { - return static_cast(m_currentPosition - it.m_currentPosition); - } - - /*! - * @brief This function increments the iterator in one the position. - * @return The current iterator. - */ - inline - _FastBuffer_iterator operator ++() - { - ++m_currentPosition; - return *this; - } - - /*! - * @brief This function increments the iterator in one the position. - * @return The current iterator. - */ - inline - _FastBuffer_iterator operator ++( - int) - { - _FastBuffer_iterator tmp = *this; - ++*this; - return tmp; - } - - /*! - * @brief This function returns the current position in the raw buffer. - * @return The current position in the raw buffer. - */ - inline - char* operator &() - { - return m_currentPosition; + memcpy(dst, m_currentPosition, size); } + } + + /*! + * @brief This function increments the position where the iterator points. + * @param numBytes Number of bytes the iterator moves the position. + */ + inline void operator+=(size_t numBytes) + { + m_currentPosition += numBytes; + } + + /*! + * @brief This operator returns the subtraction of the current interator's position and + * the source iterator's position. + * @param it Source iterator whose position is subtracted to the current iterator's + * position. + * @return The result of subtract the current iterator's position and the source + * iterator's position. + */ + inline size_t operator-(const _FastBuffer_iterator& it) const + { + return static_cast(m_currentPosition - it.m_currentPosition); + } + + /*! + * @brief This function increments the iterator in one the position. + * @return The current iterator. + */ + inline _FastBuffer_iterator operator++() + { + ++m_currentPosition; + return *this; + } + + /*! + * @brief This function increments the iterator in one the position. + * @return The current iterator. + */ + inline _FastBuffer_iterator operator++(int) + { + _FastBuffer_iterator tmp = *this; + ++*this; + return tmp; + } + + /*! + * @brief This function returns the current position in the raw buffer. + * @return The current position in the raw buffer. + */ + inline char* operator&() + { + return m_currentPosition; + } private: + //! Pointer to the raw buffer. + char* m_buffer; - //! Pointer to the raw buffer. - char* m_buffer; - - //! Current position in the raw buffer. - char* m_currentPosition; + //! Current position in the raw buffer. + char* m_currentPosition; }; /*! @@ -228,126 +207,122 @@ class Cdr_DllAPI _FastBuffer_iterator class Cdr_DllAPI FastBuffer { public: - - typedef _FastBuffer_iterator iterator; - - /*! - * @brief This constructor creates an internal stream and assigns it to the eprosima::fastcdr::FastBuffers object. - * The user can obtain this internal stream using the function eprosima::fastcdr::FastBuffers::getBuffer(). Be careful because this internal stream - * is deleted in the destruction of the eprosima::fastcdr::FastBuffers object. - */ - FastBuffer(); - - /*! - * @brief This constructor assigns the user's stream of bytes to the eprosima::fastcdr::FastBuffers object. - * The user's stream will be used to serialize. - * - * @param buffer The user's buffer that will be used. This buffer is not deallocated in the object's destruction. Cannot be NULL. - * @param bufferSize The length of user's buffer. - */ - FastBuffer( - char* const buffer, - const size_t bufferSize); - - //! Move constructor - FastBuffer( - FastBuffer&& fbuffer) - : m_buffer(nullptr) - , m_bufferSize(0) - , m_internalBuffer(true) - { - std::swap(m_buffer, fbuffer.m_buffer); - std::swap(m_bufferSize, fbuffer.m_bufferSize); - std::swap(m_internalBuffer, fbuffer.m_internalBuffer); - } - - //! Move assignment - FastBuffer& operator =( - FastBuffer&& fbuffer) - { - std::swap(m_buffer, fbuffer.m_buffer); - std::swap(m_bufferSize, fbuffer.m_bufferSize); - std::swap(m_internalBuffer, fbuffer.m_internalBuffer); - return *this; - } - - /*! - * @brief Default destructor. - */ - virtual ~FastBuffer(); - - /*! - * @brief This function returns the stream that the eprosima::fastcdr::FastBuffers uses to serialize data. - * @return The stream used by eprosima::fastcdr::FastBuffers to serialize data. - */ - inline char* getBuffer() const - { - return m_buffer; - } - - /*! - * @brief This function returns the size of the allocated memory of the stream that the eprosima::fastcdr::FastBuffers uses to serialize data. - * @return The size of the allocated memory of the stream used by the eprosima::fastcdr::FastBuffers to serialize data. - */ - inline size_t getBufferSize() const - { - return m_bufferSize; - } - - /*! - * @brief This function returns a iterator that points to the begining of the stream. - * @return The new iterator. - */ - inline - iterator begin() - { - return (iterator(m_buffer, 0)); - } - - /*! - * @brief This function returns a iterator that points to the end of the stream. - * @return The new iterator. - */ - inline - iterator end() - { - return (iterator(m_buffer, m_bufferSize)); - } - - /*! - * @brief This function reserves memory for the internal raw buffer. It will only do so if the buffer is not yet allocated and is not externally set. - * @param size The size of the memory to be allocated. - * @return True if the allocation suceeded. False if the raw buffer was set externally or is already allocated. - */ - bool reserve( - size_t size); - - /*! - * @brief This function resizes the raw buffer. It will call the user's defined function for this purpose. - * @param minSizeInc The minimun growth expected of the current raw buffer. - * @return True if the operation works. False if it does not. - */ - bool resize( - size_t minSizeInc); + typedef _FastBuffer_iterator iterator; + + /*! + * @brief This constructor creates an internal stream and assigns it to the + * eprosima::fastcdr::FastBuffers object. The user can obtain this internal stream using + * the function eprosima::fastcdr::FastBuffers::getBuffer(). Be careful because this + * internal stream is deleted in the destruction of the eprosima::fastcdr::FastBuffers + * object. + */ + FastBuffer(); + + /*! + * @brief This constructor assigns the user's stream of bytes to the + * eprosima::fastcdr::FastBuffers object. The user's stream will be used to serialize. + * + * @param buffer The user's buffer that will be used. This buffer is not deallocated in + * the object's destruction. Cannot be NULL. + * @param bufferSize The length of user's buffer. + */ + FastBuffer(char* const buffer, const size_t bufferSize); + + //! Move constructor + FastBuffer(FastBuffer&& fbuffer) + : m_buffer(nullptr), m_bufferSize(0), m_internalBuffer(true) + { + std::swap(m_buffer, fbuffer.m_buffer); + std::swap(m_bufferSize, fbuffer.m_bufferSize); + std::swap(m_internalBuffer, fbuffer.m_internalBuffer); + } + + //! Move assignment + FastBuffer& operator=(FastBuffer&& fbuffer) + { + std::swap(m_buffer, fbuffer.m_buffer); + std::swap(m_bufferSize, fbuffer.m_bufferSize); + std::swap(m_internalBuffer, fbuffer.m_internalBuffer); + return *this; + } + + /*! + * @brief Default destructor. + */ + virtual ~FastBuffer(); + + /*! + * @brief This function returns the stream that the eprosima::fastcdr::FastBuffers uses + * to serialize data. + * @return The stream used by eprosima::fastcdr::FastBuffers to serialize data. + */ + inline char* getBuffer() const + { + return m_buffer; + } + + /*! + * @brief This function returns the size of the allocated memory of the stream that the + * eprosima::fastcdr::FastBuffers uses to serialize data. + * @return The size of the allocated memory of the stream used by the + * eprosima::fastcdr::FastBuffers to serialize data. + */ + inline size_t getBufferSize() const + { + return m_bufferSize; + } + + /*! + * @brief This function returns a iterator that points to the begining of the stream. + * @return The new iterator. + */ + inline iterator begin() + { + return (iterator(m_buffer, 0)); + } + + /*! + * @brief This function returns a iterator that points to the end of the stream. + * @return The new iterator. + */ + inline iterator end() + { + return (iterator(m_buffer, m_bufferSize)); + } + + /*! + * @brief This function reserves memory for the internal raw buffer. It will only do so + * if the buffer is not yet allocated and is not externally set. + * @param size The size of the memory to be allocated. + * @return True if the allocation suceeded. False if the raw buffer was set externally + * or is already allocated. + */ + bool reserve(size_t size); + + /*! + * @brief This function resizes the raw buffer. It will call the user's defined function + * for this purpose. + * @param minSizeInc The minimun growth expected of the current raw buffer. + * @return True if the operation works. False if it does not. + */ + bool resize(size_t minSizeInc); private: + FastBuffer(const FastBuffer&) = delete; - FastBuffer( - const FastBuffer&) = delete; - - FastBuffer& operator =( - const FastBuffer&) = delete; + FastBuffer& operator=(const FastBuffer&) = delete; - //! @brief Pointer to the stream of bytes that contains the serialized data. - char* m_buffer; + //! @brief Pointer to the stream of bytes that contains the serialized data. + char* m_buffer; - //! @brief The total size of the user's buffer. - size_t m_bufferSize; + //! @brief The total size of the user's buffer. + size_t m_bufferSize; - //! @brief This variable indicates if the managed buffer is internal or is from the user. - bool m_internalBuffer; + //! @brief This variable indicates if the managed buffer is internal or is from the + //! user. + bool m_internalBuffer; }; -} //namespace fastcdr -} //namespace eprosima +} // namespace fastcdr +} // namespace eprosima -#endif // _FASTCDR_FASTCDRBUFFER_H_ +#endif // _FASTCDR_FASTCDRBUFFER_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastCdr.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastCdr.h index 8f0973e56..6307f7f54 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastCdr.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/FastCdr.h @@ -26,2079 +26,2029 @@ #include #else #include -#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ +#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ #if HAVE_CXX0X #include -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X -namespace eprosima { -namespace fastcdr { -/*! - * @brief This class offers an interface to serialize/deserialize some basic types using a modified CDR protocol inside a eprosima::FastBuffer. - * This modified CDR protocol provides a serialization mechanism much faster than common CDR protocol, because it doesn't use alignment. - * @ingroup FASTCDRAPIREFERENCE - */ -class Cdr_DllAPI FastCdr -{ -public: - - /*! - * @brief This class stores the current state of a CDR serialization. - */ - class Cdr_DllAPI state - { - friend class FastCdr; - - public: - - /*! - * @brief Default constructor. - */ - state( - const FastCdr& fastcdr); - - /*! - * @brief Copy constructor. - */ - state( - const state&); - - private: - - state& operator =( - const state&) = delete; - - //! @brief The position in the buffer when the state was created. - const FastBuffer::iterator m_currentPosition; - }; - /*! - * @brief This constructor creates a eprosima::fastcdr::FastCdr object that can serialize/deserialize - * the assigned buffer. - * - * @param cdrBuffer A reference to the buffer that contains (or will contain) the CDR representation. - */ - FastCdr( - FastBuffer& cdrBuffer); - - /*! - * @brief This function skips a number of bytes in the CDR stream buffer. - * @param numBytes The number of bytes that will be jumped. - * @return True is returned when the jump operation works successfully. Otherwise, false is returned. - */ - bool jump( - size_t numBytes); - - /*! - * @brief This function resets the current position in the buffer to the begining. - */ - void reset(); - - /*! - * @brief This function returns the current position in the CDR stream. - * @return Pointer to the current position in the buffer. - */ - char* getCurrentPosition(); - - /*! - * @brief This function returns the length of the serialized data inside the stream. - * @return The length of the serialized data. - */ - inline size_t getSerializedDataLength() const - { - return m_currentPosition - m_cdrBuffer.begin(); - } - - /*! - * @brief This function returns the current state of the CDR stream. - * @return The current state of the buffer. - */ - FastCdr::state getState(); - - /*! - * @brief This function sets a previous state of the CDR stream; - * @param state Previous state that will be set again. - */ - void setState( - FastCdr::state& state); - - /*! - * @brief This operator serializes an octet. - * @param octet_t The value of the octet that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const uint8_t octet_t) - { - return serialize(octet_t); - } - - /*! - * @brief This operator serializes a character. - * @param char_t The value of the character that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const char char_t) - { - return serialize(char_t); - } - - /*! - * @brief This operator serializes a int8_t. - * @param int8 The value of the int8_t that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const int8_t int8) - { - return serialize(int8); - } - - /*! - * @brief This operator serializes an unsigned short. - * @param ushort_t The value of the unsigned short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const uint16_t ushort_t) - { - return serialize(ushort_t); - } - - /*! - * @brief This operator serializes a short. - * @param short_t The value of the short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const int16_t short_t) - { - return serialize(short_t); - } - - /*! - * @brief This operator serializes an unsigned long. - * @param ulong_t The value of the unsigned long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const uint32_t ulong_t) - { - return serialize(ulong_t); - } - - /*! - * @brief This operator serializes a long. - * @param long_t The value of the long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const int32_t long_t) - { - return serialize(long_t); - } - - /*! - * @brief This operator serializes a wide-char. - * @param wchar The value of the wide-char that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const wchar_t wchar) - { - return serialize(wchar); - } - - /*! - * @brief This operator serializes an unsigned long long. - * @param ulonglong_t The value of the unsigned long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const uint64_t ulonglong_t) - { - return serialize(ulonglong_t); - } - - /*! - * @brief This operator serializes a long long. - * @param longlong_t The value of the long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const int64_t longlong_t) - { - return serialize(longlong_t); - } - - /*! - * @brief This operator serializes a float. - * @param float_t The value of the float that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const float float_t) - { - return serialize(float_t); - } - - /*! - * @brief This operator serializes a ldouble. - * @param double_t The value of the double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const double double_t) - { - return serialize(double_t); - } - - /*! - * @brief This operator serializes a long double. - * @param ldouble_t The value of the long double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const long double ldouble_t) - { - return serialize(ldouble_t); - } - - /*! - * @brief This operator serializes a boolean. - * @param bool_t The value of the boolean that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const bool bool_t) - { - return serialize(bool_t); - } - - /*! - * @brief This operator serializes a null-terminated string. - * @param string_t The value of the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const char* string_t) - { - return serialize(string_t); - } - - /*! - * @brief This operator serializes a null-terminated wide-string. - * @param string_t The value of the wide-string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const wchar_t* string_t) - { - return serialize(string_t); - } - - /*! - * @brief This operator serializes a string. - * @param string_t The string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const std::string& string_t) - { - return serialize(string_t); - } - - /*! - * @brief This operator serializes a wstring. - * @param string_t The wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator <<( - const std::wstring& string_t) - { - return serialize(string_t); - } - -#if HAVE_CXX0X - /*! - * @brief This operator template is used to serialize arrays. - * @param array_t The array that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator <<( - const std::array<_T, _Size>& array_t) - { - return serialize<_T, _Size>(array_t); - } - -#endif // if HAVE_CXX0X - - /*! - * @brief This operator template is used to serialize sequences. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator <<( - const std::vector<_T>& vector_t) - { - return serialize<_T>(vector_t); - } - - /*! - * @brief This operator template is used to serialize non-basic types. - * @param type_t The object that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator <<( - const _T& type_t) - { - type_t.serialize(*this); - return *this; - } - - /*! - * @brief This operator deserializes an octet. - * @param octet_t The variable that will store the octet read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - uint8_t& octet_t) - { - return deserialize(octet_t); - } - - /*! - * @brief This operator deserializes a character. - * @param char_t The variable that will store the character read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - char& char_t) - { - return deserialize(char_t); - } - - /*! - * @brief This operator deserializes an int8_t. - * @param int8 The variable that will store the int8_t read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - int8_t& int8) - { - return deserialize(int8); - } - - /*! - * @brief This operator deserializes an unsigned short. - * @param ushort_t The variable that will store the unsigned short read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - uint16_t& ushort_t) - { - return deserialize(ushort_t); - } - - /*! - * @brief This operator deserializes a short. - * @param short_t The variable that will store the short read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - int16_t& short_t) - { - return deserialize(short_t); - } - - /*! - * @brief This operator deserializes an unsigned long. - * @param ulong_t The variable that will store the unsigned long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - uint32_t& ulong_t) - { - return deserialize(ulong_t); - } - - /*! - * @brief This operator deserializes a long. - * @param long_t The variable that will store the long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - int32_t& long_t) - { - return deserialize(long_t); - } - - /*! - * @brief This operator deserializes a wide-char. - * @param wchar The variable that will store the wide-char read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - wchar_t& wchar) - { - return deserialize(wchar); - } - - /*! - * @brief This operator deserializes an unsigned long long. - * @param ulonglong_t The variable that will store the unsigned long long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - uint64_t& ulonglong_t) - { - return deserialize(ulonglong_t); - } - - /*! - * @brief This operator deserializes a long long. - * @param longlong_t The variable that will store the long long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - int64_t& longlong_t) - { - return deserialize(longlong_t); - } - - /*! - * @brief This operator deserializes a float. - * @param float_t The variable that will store the float read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - float& float_t) - { - return deserialize(float_t); - } - - /*! - * @brief This operator deserializes a double. - * @param double_t The variable that will store the double read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - double& double_t) - { - return deserialize(double_t); - } - - /*! - * @brief This operator deserializes a long double. - * @param ldouble_t The variable that will store the long double read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - long double& ldouble_t) - { - return deserialize(ldouble_t); - } - - /*! - * @brief This operator deserializes a boolean. - * @param bool_t The variable that will store the boolean read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize in an invalid value. - */ - inline FastCdr& operator >>( - bool& bool_t) - { - return deserialize(bool_t); - } - - /*! - * @brief This operator deserializes a null-terminated c-string. - * @param string_t The variable that will store the c-string read from the buffer. - * Please note that a newly allocated string will be returned. - * The caller should free the returned pointer when appropiate. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize an invalid value. - */ - inline FastCdr& operator >>( - char*& string_t) - { - return deserialize(string_t); - } - - /*! - * @brief This operator deserializes a string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - std::string& string_t) - { - return deserialize(string_t); - } - - /*! - * @brief This operator deserializes a wstring. - * @param string_t The variable that will store the wstring read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline FastCdr& operator >>( - std::wstring& string_t) - { - return deserialize(string_t); - } - -#if HAVE_CXX0X - /*! - * @brief This operator template is used to deserialize arrays. - * @param array_t The variable that will store the array read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator >>( - std::array<_T, _Size>& array_t) - { - return deserialize<_T, _Size>(array_t); - } - -#endif // if HAVE_CXX0X - - /*! - * @brief This operator template is used to deserialize sequences. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator >>( - std::vector<_T>& vector_t) - { - return deserialize<_T>(vector_t); - } - - /*! - * @brief This operator template is used to deserialize non-basic types. - * @param type_t The variable that will store the object read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& operator >>( - _T& type_t) - { - type_t.deserialize(*this); - return *this; - } - - /*! - * @brief This function serializes an octet. - * @param octet_t The value of the octet that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const uint8_t octet_t) - { - return serialize(static_cast(octet_t)); - } - - /*! - * @brief This function serializes a character. - * @param char_t The value of the character that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const char char_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(char_t)) || resize(sizeof(char_t))) - { - m_currentPosition++ << char_t; - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes an int8_t. - * @param int8 The value of the int8_t that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const int8_t int8) - { - return serialize(static_cast(int8)); - } - - /*! - * @brief This function serializes an unsigned short. - * @param ushort_t The value of the unsigned short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const uint16_t ushort_t) - { - return serialize(static_cast(ushort_t)); - } - - /*! - * @brief This function serializes a short. - * @param short_t The value of the short that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const int16_t short_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(short_t)) || resize(sizeof(short_t))) - { - m_currentPosition << short_t; - m_currentPosition += sizeof(short_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes an unsigned long. - * @param ulong_t The value of the unsigned long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const uint32_t ulong_t) - { - return serialize(static_cast(ulong_t)); - } - - /*! - * @brief This function serializes a long. - * @param long_t The value of the long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const int32_t long_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(long_t)) || resize(sizeof(long_t))) - { - m_currentPosition << long_t; - m_currentPosition += sizeof(long_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes a wide-char. - * @param wchar The value of the wide-char that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const wchar_t wchar) - { - return serialize(static_cast(wchar)); - } - - /*! - * @brief This function serializes an unsigned long long. - * @param ulonglong_t The value of the unsigned long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const uint64_t ulonglong_t) - { - return serialize(static_cast(ulonglong_t)); - } - - /*! - * @brief This function serializes a long long. - * @param longlong_t The value of the long long that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const int64_t longlong_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(longlong_t)) || resize(sizeof(longlong_t))) - { - m_currentPosition << longlong_t; - m_currentPosition += sizeof(longlong_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes a float. - * @param float_t The value of the float that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const float float_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(float_t)) || resize(sizeof(float_t))) - { - m_currentPosition << float_t; - m_currentPosition += sizeof(float_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes a double. - * @param double_t The value of the double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const double double_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(double_t)) || resize(sizeof(double_t))) - { - m_currentPosition << double_t; - m_currentPosition += sizeof(double_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes a long double. - * @param ldouble_t The value of the long double that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const long double ldouble_t) - { - if (((m_lastPosition - m_currentPosition) >= sizeof(ldouble_t)) || resize(sizeof(ldouble_t))) - { - m_currentPosition << ldouble_t; -#if defined(_WIN32) - m_currentPosition += sizeof(ldouble_t); - m_currentPosition << static_cast(0); -#endif // if defined(_WIN32) - m_currentPosition += sizeof(ldouble_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function serializes a boolean. - * @param bool_t The value of the boolean that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serialize( - const bool bool_t); - - /*! - * @brief This function serializes a string. - * @param string_t The pointer to the string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serialize( - const char* string_t); - - /*! - * @brief This function serializes a wstring. - * @param string_t The pointer to the wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serialize( - const wchar_t* string_t); - - /*! - * @brief This function serializes a std::string. - * @param string_t The string that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const std::string& string_t) - { - return serialize(string_t.c_str()); - } - - /*! - * @brief This function serializes a std::wstring. - * @param string_t The wstring that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serialize( - const std::wstring& string_t) - { - return serialize(string_t.c_str()); - } - -#if HAVE_CXX0X - /*! - * @brief This function template serializes an array. - * @param array_t The array that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& serialize( - const std::array<_T, _Size>& array_t) - { - return serializeArray(array_t.data(), array_t.size()); - } - -#endif // if HAVE_CXX0X - -#if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template serializes a sequence of booleans. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serialize( - const std::vector& vector_t) - { - return serializeBoolSequence(vector_t); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template serializes a sequence. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serialize( - const std::vector<_T>& vector_t) - { - state state_before_error(*this); - - *this << static_cast(vector_t.size()); - - try - { - return serializeArray(vector_t.data(), vector_t.size()); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } - -#ifdef _MSC_VER - /*! - * @brief This function template serializes a sequence of booleans. - * @param vector_t The sequence that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template<> - FastCdr& serialize( - const std::vector& vector_t) - { - return serializeBoolSequence(vector_t); - } - -#endif // ifdef _MSC_VER - - /*! - * @brief This function template serializes a non-basic type. - * @param type_t The object that will be serialized in the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& serialize( - const _T& type_t) - { - type_t.serialize(*this); - return *this; - } - - /*! - * @brief This function serializes an array of octets. - * @param octet_t The sequence of octets that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const uint8_t* octet_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(octet_t), numElements); - } - - /*! - * @brief This function serializes an array of characters. - * @param char_t The array of characters that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const char* char_t, - size_t numElements); - - /*! - * @brief This function serializes an array of int8_t. - * @param int8 The sequence of int8_t that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const int8_t* int8, - size_t numElements) - { - return serializeArray(reinterpret_cast(int8), numElements); - } - - /*! - * @brief This function serializes an array of unsigned shorts. - * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const uint16_t* ushort_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ushort_t), numElements); - } - - /*! - * @brief This function serializes an array of shorts. - * @param short_t The array of shorts that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const int16_t* short_t, - size_t numElements); - - /*! - * @brief This function serializes an array of unsigned longs. - * @param ulong_t The array of unsigned longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const uint32_t* ulong_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ulong_t), numElements); - } - - /*! - * @brief This function serializes an array of longs. - * @param long_t The array of longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const int32_t* long_t, - size_t numElements); - - /*! - * @brief This function serializes an array of wide-chars. - * @param wchar The array of wide-chars that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const wchar_t* wchar, - size_t numElements); - - /*! - * @brief This function serializes an array of unsigned long longs. - * @param ulonglong_t The array of unsigned long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const uint64_t* ulonglong_t, - size_t numElements) - { - return serializeArray(reinterpret_cast(ulonglong_t), numElements); - } - - /*! - * @brief This function serializes an array of long longs. - * @param longlong_t The array of long longs that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const int64_t* longlong_t, - size_t numElements); - - /*! - * @brief This function serializes an array of floats. - * @param float_t The array of floats that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const float* float_t, - size_t numElements); - - /*! - * @brief This function serializes an array of doubles. - * @param double_t The array of doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const double* double_t, - size_t numElements); - - /*! - * @brief This function serializes an array of long doubles. - * @param ldouble_t The array of long doubles that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const long double* ldouble_t, - size_t numElements); - - /*! - * @brief This function serializes an array of booleans. - * @param bool_t The array of booleans that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - FastCdr& serializeArray( - const bool* bool_t, - size_t numElements); - - /*! - * @brief This function serializes an array of strings. - * @param string_t The array of strings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const std::string* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(string_t[count].c_str()); - } - return *this; - } - - /*! - * @brief This function serializes an array of wstrings. - * @param string_t The array of wstrings that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& serializeArray( - const std::wstring* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(string_t[count].c_str()); - } - return *this; - } - - /*! - * @brief This function template serializes an array of sequences. - * @param vector_t The array of sequences that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serializeArray( - const std::vector<_T>* vector_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - serialize(vector_t[count]); - } - return *this; - } - - /*! - * @brief This function template serializes an array of non-basic type objects. - * @param type_t The array of objects that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serializeArray( - const _T* type_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - type_t[count].serialize(*this); - } - return *this; - } - - /*! - * @brief This function template serializes a raw sequence. - * @param sequence_t Pointer to the sequence that will be serialized in the buffer. - * @param numElements The number of elements contained in the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serializeSequence( - const _T* sequence_t, - size_t numElements) - { - state state_before_error(*this); - - serialize(static_cast(numElements)); - - try - { - return serializeArray(sequence_t, numElements); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } - - /*! - * @brief This function deserializes an octet. - * @param octet_t The variable that will store the octet read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - uint8_t& octet_t) - { - return deserialize(reinterpret_cast(octet_t)); - } - - /*! - * @brief This function deserializes a character. - * @param char_t The variable that will store the character read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - char& char_t) - { - if ((m_lastPosition - m_currentPosition) >= sizeof(char_t)) - { - m_currentPosition++ >> char_t; - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function deserializes an int8_t. - * @param int8 The variable that will store the int8_t read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - int8_t& int8) - { - return deserialize(reinterpret_cast(int8)); - } - - /*! - * @brief This function deserializes an unsigned short. - * @param ushort_t The variable that will store the unsigned short read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - uint16_t& ushort_t) - { - return deserialize(reinterpret_cast(ushort_t)); - } - - /*! - * @brief This function deserializes a short. - * @param short_t The variable that will store the short read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - int16_t& short_t) - { - if ((m_lastPosition - m_currentPosition) >= sizeof(short_t)) - { - m_currentPosition >> short_t; - m_currentPosition += sizeof(short_t); - - return *this; - } +namespace eprosima +{ +namespace fastcdr +{ +/*! + * @brief This class offers an interface to serialize/deserialize some basic types using a + * modified CDR protocol inside a eprosima::FastBuffer. This modified CDR protocol + * provides a serialization mechanism much faster than common CDR protocol, because it + * doesn't use alignment. + * @ingroup FASTCDRAPIREFERENCE + */ +class Cdr_DllAPI FastCdr +{ +public: + /*! + * @brief This class stores the current state of a CDR serialization. + */ + class Cdr_DllAPI state + { + friend class FastCdr; + + public: + /*! + * @brief Default constructor. + */ + state(const FastCdr& fastcdr); + + /*! + * @brief Copy constructor. + */ + state(const state&); + + private: + state& operator=(const state&) = delete; + + //! @brief The position in the buffer when the state was created. + const FastBuffer::iterator m_currentPosition; + }; + /*! + * @brief This constructor creates a eprosima::fastcdr::FastCdr object that can + * serialize/deserialize the assigned buffer. + * + * @param cdrBuffer A reference to the buffer that contains (or will contain) the CDR + * representation. + */ + FastCdr(FastBuffer& cdrBuffer); + + /*! + * @brief This function skips a number of bytes in the CDR stream buffer. + * @param numBytes The number of bytes that will be jumped. + * @return True is returned when the jump operation works successfully. Otherwise, false + * is returned. + */ + bool jump(size_t numBytes); + + /*! + * @brief This function resets the current position in the buffer to the begining. + */ + void reset(); + + /*! + * @brief This function returns the current position in the CDR stream. + * @return Pointer to the current position in the buffer. + */ + char* getCurrentPosition(); + + /*! + * @brief This function returns the length of the serialized data inside the stream. + * @return The length of the serialized data. + */ + inline size_t getSerializedDataLength() const + { + return m_currentPosition - m_cdrBuffer.begin(); + } + + /*! + * @brief This function returns the current state of the CDR stream. + * @return The current state of the buffer. + */ + FastCdr::state getState(); + + /*! + * @brief This function sets a previous state of the CDR stream; + * @param state Previous state that will be set again. + */ + void setState(FastCdr::state& state); + + /*! + * @brief This operator serializes an octet. + * @param octet_t The value of the octet that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const uint8_t octet_t) + { + return serialize(octet_t); + } + + /*! + * @brief This operator serializes a character. + * @param char_t The value of the character that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const char char_t) + { + return serialize(char_t); + } + + /*! + * @brief This operator serializes a int8_t. + * @param int8 The value of the int8_t that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const int8_t int8) + { + return serialize(int8); + } + + /*! + * @brief This operator serializes an unsigned short. + * @param ushort_t The value of the unsigned short that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const uint16_t ushort_t) + { + return serialize(ushort_t); + } + + /*! + * @brief This operator serializes a short. + * @param short_t The value of the short that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const int16_t short_t) + { + return serialize(short_t); + } + + /*! + * @brief This operator serializes an unsigned long. + * @param ulong_t The value of the unsigned long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const uint32_t ulong_t) + { + return serialize(ulong_t); + } + + /*! + * @brief This operator serializes a long. + * @param long_t The value of the long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const int32_t long_t) + { + return serialize(long_t); + } + + /*! + * @brief This operator serializes a wide-char. + * @param wchar The value of the wide-char that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const wchar_t wchar) + { + return serialize(wchar); + } + + /*! + * @brief This operator serializes an unsigned long long. + * @param ulonglong_t The value of the unsigned long long that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const uint64_t ulonglong_t) + { + return serialize(ulonglong_t); + } + + /*! + * @brief This operator serializes a long long. + * @param longlong_t The value of the long long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const int64_t longlong_t) + { + return serialize(longlong_t); + } + + /*! + * @brief This operator serializes a float. + * @param float_t The value of the float that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const float float_t) + { + return serialize(float_t); + } + + /*! + * @brief This operator serializes a ldouble. + * @param double_t The value of the double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const double double_t) + { + return serialize(double_t); + } + + /*! + * @brief This operator serializes a long double. + * @param ldouble_t The value of the long double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const long double ldouble_t) + { + return serialize(ldouble_t); + } + + /*! + * @brief This operator serializes a boolean. + * @param bool_t The value of the boolean that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const bool bool_t) + { + return serialize(bool_t); + } + + /*! + * @brief This operator serializes a null-terminated string. + * @param string_t The value of the string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const char* string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a null-terminated wide-string. + * @param string_t The value of the wide-string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const wchar_t* string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a string. + * @param string_t The string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const std::string& string_t) + { + return serialize(string_t); + } + + /*! + * @brief This operator serializes a wstring. + * @param string_t The wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator<<(const std::wstring& string_t) + { + return serialize(string_t); + } - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } +#if HAVE_CXX0X + /*! + * @brief This operator template is used to serialize arrays. + * @param array_t The array that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator<<(const std::array<_T, _Size>& array_t) + { + return serialize<_T, _Size>(array_t); + } + +#endif // if HAVE_CXX0X + + /*! + * @brief This operator template is used to serialize sequences. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator<<(const std::vector<_T>& vector_t) + { + return serialize<_T>(vector_t); + } + + /*! + * @brief This operator template is used to serialize non-basic types. + * @param type_t The object that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator<<(const _T& type_t) + { + type_t.serialize(*this); + return *this; + } + + /*! + * @brief This operator deserializes an octet. + * @param octet_t The variable that will store the octet read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(uint8_t& octet_t) + { + return deserialize(octet_t); + } + + /*! + * @brief This operator deserializes a character. + * @param char_t The variable that will store the character read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(char& char_t) + { + return deserialize(char_t); + } + + /*! + * @brief This operator deserializes an int8_t. + * @param int8 The variable that will store the int8_t read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(int8_t& int8) + { + return deserialize(int8); + } + + /*! + * @brief This operator deserializes an unsigned short. + * @param ushort_t The variable that will store the unsigned short read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(uint16_t& ushort_t) + { + return deserialize(ushort_t); + } + + /*! + * @brief This operator deserializes a short. + * @param short_t The variable that will store the short read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(int16_t& short_t) + { + return deserialize(short_t); + } + + /*! + * @brief This operator deserializes an unsigned long. + * @param ulong_t The variable that will store the unsigned long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(uint32_t& ulong_t) + { + return deserialize(ulong_t); + } + + /*! + * @brief This operator deserializes a long. + * @param long_t The variable that will store the long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(int32_t& long_t) + { + return deserialize(long_t); + } + + /*! + * @brief This operator deserializes a wide-char. + * @param wchar The variable that will store the wide-char read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(wchar_t& wchar) + { + return deserialize(wchar); + } + + /*! + * @brief This operator deserializes an unsigned long long. + * @param ulonglong_t The variable that will store the unsigned long long read from the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(uint64_t& ulonglong_t) + { + return deserialize(ulonglong_t); + } + + /*! + * @brief This operator deserializes a long long. + * @param longlong_t The variable that will store the long long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(int64_t& longlong_t) + { + return deserialize(longlong_t); + } + + /*! + * @brief This operator deserializes a float. + * @param float_t The variable that will store the float read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(float& float_t) + { + return deserialize(float_t); + } + + /*! + * @brief This operator deserializes a double. + * @param double_t The variable that will store the double read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(double& double_t) + { + return deserialize(double_t); + } + + /*! + * @brief This operator deserializes a long double. + * @param ldouble_t The variable that will store the long double read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(long double& ldouble_t) + { + return deserialize(ldouble_t); + } + + /*! + * @brief This operator deserializes a boolean. + * @param bool_t The variable that will store the boolean read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize in an invalid value. + */ + inline FastCdr& operator>>(bool& bool_t) + { + return deserialize(bool_t); + } + + /*! + * @brief This operator deserializes a null-terminated c-string. + * @param string_t The variable that will store the c-string read from the buffer. + * Please note that a newly allocated string will be returned. + * The caller should free the returned pointer when appropiate. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize an invalid value. + */ + inline FastCdr& operator>>(char*& string_t) + { + return deserialize(string_t); + } + + /*! + * @brief This operator deserializes a string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(std::string& string_t) + { + return deserialize(string_t); + } + + /*! + * @brief This operator deserializes a wstring. + * @param string_t The variable that will store the wstring read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& operator>>(std::wstring& string_t) + { + return deserialize(string_t); + } - /*! - * @brief This function deserializes an unsigned long. - * @param ulong_t The variable that will store the unsigned long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - uint32_t& ulong_t) - { - return deserialize(reinterpret_cast(ulong_t)); - } +#if HAVE_CXX0X + /*! + * @brief This operator template is used to deserialize arrays. + * @param array_t The variable that will store the array read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator>>(std::array<_T, _Size>& array_t) + { + return deserialize<_T, _Size>(array_t); + } + +#endif // if HAVE_CXX0X + + /*! + * @brief This operator template is used to deserialize sequences. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator>>(std::vector<_T>& vector_t) + { + return deserialize<_T>(vector_t); + } + + /*! + * @brief This operator template is used to deserialize non-basic types. + * @param type_t The variable that will store the object read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& operator>>(_T& type_t) + { + type_t.deserialize(*this); + return *this; + } + + /*! + * @brief This function serializes an octet. + * @param octet_t The value of the octet that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const uint8_t octet_t) + { + return serialize(static_cast(octet_t)); + } + + /*! + * @brief This function serializes a character. + * @param char_t The value of the character that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const char char_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(char_t)) || + resize(sizeof(char_t))) + { + m_currentPosition++ << char_t; + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes an int8_t. + * @param int8 The value of the int8_t that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const int8_t int8) + { + return serialize(static_cast(int8)); + } + + /*! + * @brief This function serializes an unsigned short. + * @param ushort_t The value of the unsigned short that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const uint16_t ushort_t) + { + return serialize(static_cast(ushort_t)); + } + + /*! + * @brief This function serializes a short. + * @param short_t The value of the short that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const int16_t short_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(short_t)) || + resize(sizeof(short_t))) + { + m_currentPosition << short_t; + m_currentPosition += sizeof(short_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes an unsigned long. + * @param ulong_t The value of the unsigned long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const uint32_t ulong_t) + { + return serialize(static_cast(ulong_t)); + } + + /*! + * @brief This function serializes a long. + * @param long_t The value of the long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const int32_t long_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(long_t)) || + resize(sizeof(long_t))) + { + m_currentPosition << long_t; + m_currentPosition += sizeof(long_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes a wide-char. + * @param wchar The value of the wide-char that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const wchar_t wchar) + { + return serialize(static_cast(wchar)); + } + + /*! + * @brief This function serializes an unsigned long long. + * @param ulonglong_t The value of the unsigned long long that will be serialized in the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const uint64_t ulonglong_t) + { + return serialize(static_cast(ulonglong_t)); + } + + /*! + * @brief This function serializes a long long. + * @param longlong_t The value of the long long that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const int64_t longlong_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(longlong_t)) || + resize(sizeof(longlong_t))) + { + m_currentPosition << longlong_t; + m_currentPosition += sizeof(longlong_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes a float. + * @param float_t The value of the float that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const float float_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(float_t)) || + resize(sizeof(float_t))) + { + m_currentPosition << float_t; + m_currentPosition += sizeof(float_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes a double. + * @param double_t The value of the double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const double double_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(double_t)) || + resize(sizeof(double_t))) + { + m_currentPosition << double_t; + m_currentPosition += sizeof(double_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes a long double. + * @param ldouble_t The value of the long double that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const long double ldouble_t) + { + if (((m_lastPosition - m_currentPosition) >= sizeof(ldouble_t)) || + resize(sizeof(ldouble_t))) + { + m_currentPosition << ldouble_t; +#if defined(_WIN32) + m_currentPosition += sizeof(ldouble_t); + m_currentPosition << static_cast(0); +#endif // if defined(_WIN32) + m_currentPosition += sizeof(ldouble_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function serializes a boolean. + * @param bool_t The value of the boolean that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serialize(const bool bool_t); + + /*! + * @brief This function serializes a string. + * @param string_t The pointer to the string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serialize(const char* string_t); + + /*! + * @brief This function serializes a wstring. + * @param string_t The pointer to the wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serialize(const wchar_t* string_t); + + /*! + * @brief This function serializes a std::string. + * @param string_t The string that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const std::string& string_t) + { + return serialize(string_t.c_str()); + } + + /*! + * @brief This function serializes a std::wstring. + * @param string_t The wstring that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serialize(const std::wstring& string_t) + { + return serialize(string_t.c_str()); + } - /*! - * @brief This function deserializes a long. - * @param long_t The variable that will store the long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - int32_t& long_t) - { - if ((m_lastPosition - m_currentPosition) >= sizeof(long_t)) - { - m_currentPosition >> long_t; - m_currentPosition += sizeof(long_t); +#if HAVE_CXX0X + /*! + * @brief This function template serializes an array. + * @param array_t The array that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& serialize(const std::array<_T, _Size>& array_t) + { + return serializeArray(array_t.data(), array_t.size()); + } + +#endif // if HAVE_CXX0X - return *this; - } +#if !defined(_MSC_VER) && HAVE_CXX0X + /*! + * @brief This function template serializes a sequence of booleans. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serialize(const std::vector& vector_t) + { + return serializeBoolSequence(vector_t); + } - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } +#endif // if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function deserializes a wide-char. - * @param wchar The variable that will store the wide-char read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - wchar_t& wchar) - { - uint32_t ret; - deserialize(ret); - wchar = static_cast(ret); - return *this; - } + /*! + * @brief This function template serializes a sequence. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serialize(const std::vector<_T>& vector_t) + { + state state_before_error(*this); - /*! - * @brief This function deserializes an unsigned long long. - * @param ulonglong_t The variable that will store the unsigned long long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - uint64_t& ulonglong_t) - { - return deserialize(reinterpret_cast(ulonglong_t)); - } + *this << static_cast(vector_t.size()); - /*! - * @brief This function deserializes a long long. - * @param longlong_t The variable that will store the long long read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - int64_t& longlong_t) + try { - if ((m_lastPosition - m_currentPosition) >= sizeof(longlong_t)) - { - m_currentPosition >> longlong_t; - m_currentPosition += sizeof(longlong_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return serializeArray(vector_t.data(), vector_t.size()); } - - /*! - * @brief This function deserializes a float. - * @param float_t The variable that will store the float read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - float& float_t) + catch (eprosima::fastcdr::exception::Exception& ex) { - if ((m_lastPosition - m_currentPosition) >= sizeof(float_t)) - { - m_currentPosition >> float_t; - m_currentPosition += sizeof(float_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + ex.raise(); } - /*! - * @brief This function deserializes a double. - * @param double_t The variable that will store the double read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - double& double_t) - { - if ((m_lastPosition - m_currentPosition) >= sizeof(double_t)) - { - m_currentPosition >> double_t; - m_currentPosition += sizeof(double_t); - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } + return *this; + } - /*! - * @brief This function deserializes a long double. - * @param ldouble_t The variable that will store the long double read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - long double& ldouble_t) - { - if ((m_lastPosition - m_currentPosition) >= sizeof(ldouble_t)) - { - m_currentPosition >> ldouble_t; - m_currentPosition += sizeof(ldouble_t); +#ifdef _MSC_VER + /*! + * @brief This function template serializes a sequence of booleans. + * @param vector_t The sequence that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template <> + FastCdr& serialize(const std::vector& vector_t) + { + return serializeBoolSequence(vector_t); + } + +#endif // ifdef _MSC_VER + + /*! + * @brief This function template serializes a non-basic type. + * @param type_t The object that will be serialized in the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& serialize(const _T& type_t) + { + type_t.serialize(*this); + return *this; + } + + /*! + * @brief This function serializes an array of octets. + * @param octet_t The sequence of octets that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const uint8_t* octet_t, size_t numElements) + { + return serializeArray(reinterpret_cast(octet_t), numElements); + } + + /*! + * @brief This function serializes an array of characters. + * @param char_t The array of characters that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const char* char_t, size_t numElements); + + /*! + * @brief This function serializes an array of int8_t. + * @param int8 The sequence of int8_t that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const int8_t* int8, size_t numElements) + { + return serializeArray(reinterpret_cast(int8), numElements); + } + + /*! + * @brief This function serializes an array of unsigned shorts. + * @param ushort_t The array of unsigned shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const uint16_t* ushort_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ushort_t), numElements); + } + + /*! + * @brief This function serializes an array of shorts. + * @param short_t The array of shorts that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const int16_t* short_t, size_t numElements); + + /*! + * @brief This function serializes an array of unsigned longs. + * @param ulong_t The array of unsigned longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const uint32_t* ulong_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ulong_t), numElements); + } + + /*! + * @brief This function serializes an array of longs. + * @param long_t The array of longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const int32_t* long_t, size_t numElements); + + /*! + * @brief This function serializes an array of wide-chars. + * @param wchar The array of wide-chars that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const wchar_t* wchar, size_t numElements); + + /*! + * @brief This function serializes an array of unsigned long longs. + * @param ulonglong_t The array of unsigned long longs that will be serialized in the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const uint64_t* ulonglong_t, size_t numElements) + { + return serializeArray(reinterpret_cast(ulonglong_t), numElements); + } + + /*! + * @brief This function serializes an array of long longs. + * @param longlong_t The array of long longs that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const int64_t* longlong_t, size_t numElements); + + /*! + * @brief This function serializes an array of floats. + * @param float_t The array of floats that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const float* float_t, size_t numElements); + + /*! + * @brief This function serializes an array of doubles. + * @param double_t The array of doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const double* double_t, size_t numElements); + + /*! + * @brief This function serializes an array of long doubles. + * @param ldouble_t The array of long doubles that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const long double* ldouble_t, size_t numElements); + + /*! + * @brief This function serializes an array of booleans. + * @param bool_t The array of booleans that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + FastCdr& serializeArray(const bool* bool_t, size_t numElements); + + /*! + * @brief This function serializes an array of strings. + * @param string_t The array of strings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const std::string* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(string_t[count].c_str()); + } + return *this; + } + + /*! + * @brief This function serializes an array of wstrings. + * @param string_t The array of wstrings that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + inline FastCdr& serializeArray(const std::wstring* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(string_t[count].c_str()); + } + return *this; + } + + /*! + * @brief This function template serializes an array of sequences. + * @param vector_t The array of sequences that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serializeArray(const std::vector<_T>* vector_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + serialize(vector_t[count]); + } + return *this; + } + + /*! + * @brief This function template serializes an array of non-basic type objects. + * @param type_t The array of objects that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serializeArray(const _T* type_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + type_t[count].serialize(*this); + } + return *this; + } + + /*! + * @brief This function template serializes a raw sequence. + * @param sequence_t Pointer to the sequence that will be serialized in the buffer. + * @param numElements The number of elements contained in the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serializeSequence(const _T* sequence_t, size_t numElements) + { + state state_before_error(*this); + + serialize(static_cast(numElements)); + + try + { + return serializeArray(sequence_t, numElements); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + setState(state_before_error); + ex.raise(); + } + + return *this; + } + + /*! + * @brief This function deserializes an octet. + * @param octet_t The variable that will store the octet read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(uint8_t& octet_t) + { + return deserialize(reinterpret_cast(octet_t)); + } + + /*! + * @brief This function deserializes a character. + * @param char_t The variable that will store the character read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(char& char_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(char_t)) + { + m_currentPosition++ >> char_t; + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes an int8_t. + * @param int8 The variable that will store the int8_t read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(int8_t& int8) + { + return deserialize(reinterpret_cast(int8)); + } + + /*! + * @brief This function deserializes an unsigned short. + * @param ushort_t The variable that will store the unsigned short read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(uint16_t& ushort_t) + { + return deserialize(reinterpret_cast(ushort_t)); + } + + /*! + * @brief This function deserializes a short. + * @param short_t The variable that will store the short read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(int16_t& short_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(short_t)) + { + m_currentPosition >> short_t; + m_currentPosition += sizeof(short_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes an unsigned long. + * @param ulong_t The variable that will store the unsigned long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(uint32_t& ulong_t) + { + return deserialize(reinterpret_cast(ulong_t)); + } + + /*! + * @brief This function deserializes a long. + * @param long_t The variable that will store the long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(int32_t& long_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(long_t)) + { + m_currentPosition >> long_t; + m_currentPosition += sizeof(long_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes a wide-char. + * @param wchar The variable that will store the wide-char read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(wchar_t& wchar) + { + uint32_t ret; + deserialize(ret); + wchar = static_cast(ret); + return *this; + } + + /*! + * @brief This function deserializes an unsigned long long. + * @param ulonglong_t The variable that will store the unsigned long long read from the + * buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(uint64_t& ulonglong_t) + { + return deserialize(reinterpret_cast(ulonglong_t)); + } + + /*! + * @brief This function deserializes a long long. + * @param longlong_t The variable that will store the long long read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(int64_t& longlong_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(longlong_t)) + { + m_currentPosition >> longlong_t; + m_currentPosition += sizeof(longlong_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes a float. + * @param float_t The variable that will store the float read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(float& float_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(float_t)) + { + m_currentPosition >> float_t; + m_currentPosition += sizeof(float_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes a double. + * @param double_t The variable that will store the double read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(double& double_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(double_t)) + { + m_currentPosition >> double_t; + m_currentPosition += sizeof(double_t); + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes a long double. + * @param ldouble_t The variable that will store the long double read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(long double& ldouble_t) + { + if ((m_lastPosition - m_currentPosition) >= sizeof(ldouble_t)) + { + m_currentPosition >> ldouble_t; + m_currentPosition += sizeof(ldouble_t); #if defined(_WIN32) - m_currentPosition += sizeof(ldouble_t); -#endif // if defined(_WIN32) - - return *this; - } - - throw exception::NotEnoughMemoryException(exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } - - /*! - * @brief This function deserializes a boolean. - * @param bool_t The variable that will store the boolean read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - * @exception exception::BadParamException This exception is thrown when trying to deserialize in an invalid value. - */ - FastCdr& deserialize( - bool& bool_t); - - /*! - * @brief This function deserializes a string. - * This function allocates memory to store the string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the string read from the buffer. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserialize( - char*& string_t); - - /*! - * @brief This function deserializes a wide string. - * This function allocates memory to store the wide string. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param string_t The pointer that will point to the wide string read from the buffer. - * The user will have to free the allocated memory using free() - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserialize( - wchar_t*& string_t); - - /*! - * @brief This function deserializes a std::string. - * @param string_t The variable that will store the string read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - std::string& string_t) - { - uint32_t length = 0; - const char* str = readString(length); - string_t = std::string(str, length); - return *this; - } - - /*! - * @brief This function deserializes a std::wstring. - * @param string_t The variable that will store the wstring read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserialize( - std::wstring& string_t) - { - uint32_t length = 0; - string_t = readWString(length); - return *this; - } + m_currentPosition += sizeof(ldouble_t); +#endif // if defined(_WIN32) + + return *this; + } + + throw exception::NotEnoughMemoryException( + exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } + + /*! + * @brief This function deserializes a boolean. + * @param bool_t The variable that will store the boolean read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + * @exception exception::BadParamException This exception is thrown when trying to + * deserialize in an invalid value. + */ + FastCdr& deserialize(bool& bool_t); + + /*! + * @brief This function deserializes a string. + * This function allocates memory to store the string. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param string_t The pointer that will point to the string read from the buffer. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserialize(char*& string_t); + + /*! + * @brief This function deserializes a wide string. + * This function allocates memory to store the wide string. The user pointer will be set + * to point this allocated memory. The user will have to free this allocated memory + * using free() + * @param string_t The pointer that will point to the wide string read from the buffer. + * The user will have to free the allocated memory using free() + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserialize(wchar_t*& string_t); + + /*! + * @brief This function deserializes a std::string. + * @param string_t The variable that will store the string read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(std::string& string_t) + { + uint32_t length = 0; + const char* str = readString(length); + string_t = std::string(str, length); + return *this; + } + + /*! + * @brief This function deserializes a std::wstring. + * @param string_t The variable that will store the wstring read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserialize(std::wstring& string_t) + { + uint32_t length = 0; + string_t = readWString(length); + return *this; + } #if HAVE_CXX0X - /*! - * @brief This function template deserializes an array. - * @param array_t The variable that will store the array read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& deserialize( - std::array<_T, _Size>& array_t) - { - return deserializeArray(array_t.data(), array_t.size()); - } - -#endif // if HAVE_CXX0X + /*! + * @brief This function template deserializes an array. + * @param array_t The variable that will store the array read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& deserialize(std::array<_T, _Size>& array_t) + { + return deserializeArray(array_t.data(), array_t.size()); + } + +#endif // if HAVE_CXX0X #if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template deserializes a sequence of booleans. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserialize( - std::vector& vector_t) - { - return deserializeBoolSequence(vector_t); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template deserializes a sequence. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserialize( - std::vector<_T>& vector_t) - { - uint32_t seqLength = 0; - state state_before_error(*this); - - *this >> seqLength; - - try - { - vector_t.resize(seqLength); - return deserializeArray(vector_t.data(), vector_t.size()); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - setState(state_before_error); - ex.raise(); - } - - return *this; - } + /*! + * @brief This function template deserializes a sequence of booleans. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserialize(std::vector& vector_t) + { + return deserializeBoolSequence(vector_t); + } + +#endif // if !defined(_MSC_VER) && HAVE_CXX0X + + /*! + * @brief This function template deserializes a sequence. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserialize(std::vector<_T>& vector_t) + { + uint32_t seqLength = 0; + state state_before_error(*this); + + *this >> seqLength; + + try + { + vector_t.resize(seqLength); + return deserializeArray(vector_t.data(), vector_t.size()); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + setState(state_before_error); + ex.raise(); + } + + return *this; + } #ifdef _MSC_VER - /*! - * @brief This function template deserializes a sequence of booleans. - * @param vector_t The variable that will store the sequence read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template<> - FastCdr& deserialize( - std::vector& vector_t) - { - return deserializeBoolSequence(vector_t); - } - -#endif // ifdef _MSC_VER - - /*! - * @brief This function template deserializes a non-basic type object. - * @param type_t The variable that will store the object read from the buffer. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - inline FastCdr& deserialize( - _T& type_t) - { - type_t.deserialize(*this); - return *this; - } - - /*! - * @brief This function deserializes an array of octets. - * @param octet_t The variable that will store the array of octets read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - uint8_t* octet_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(octet_t), numElements); - } - - /*! - * @brief This function deserializes an array of characters. - * @param char_t The variable that will store the array of characters read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - char* char_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of int8_t. - * @param int8 The variable that will store the array of int8_t read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - int8_t* int8, - size_t numElements) - { - return deserializeArray(reinterpret_cast(int8), numElements); - } - - /*! - * @brief This function deserializes an array of unsigned shorts. - * @param ushort_t The variable that will store the array of unsigned shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - uint16_t* ushort_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ushort_t), numElements); - } - - /*! - * @brief This function deserializes an array of shorts. - * @param short_t The variable that will store the array of shorts read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - int16_t* short_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of unsigned longs. - * @param ulong_t The variable that will store the array of unsigned longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - uint32_t* ulong_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ulong_t), numElements); - } - - /*! - * @brief This function deserializes an array of longs. - * @param long_t The variable that will store the array of longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - int32_t* long_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of wide-chars. - * @param wchar The variable that will store the array of wide-chars read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - wchar_t* wchar, - size_t numElements); - - /*! - * @brief This function deserializes an array of unsigned long longs. - * @param ulonglong_t The variable that will store the array of unsigned long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - uint64_t* ulonglong_t, - size_t numElements) - { - return deserializeArray(reinterpret_cast(ulonglong_t), numElements); - } - - /*! - * @brief This function deserializes an array of long longs. - * @param longlong_t The variable that will store the array of long longs read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - int64_t* longlong_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of floats. - * @param float_t The variable that will store the array of floats read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - float* float_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of doubles. - * @param double_t The variable that will store the array of doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - double* double_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of long doubles. - * @param ldouble_t The variable that will store the array of long doubles read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - long double* ldouble_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of booleans. - * @param bool_t The variable that will store the array of booleans read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - FastCdr& deserializeArray( - bool* bool_t, - size_t numElements); - - /*! - * @brief This function deserializes an array of strings. - * @param string_t The variable that will store the array of strings read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - std::string* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(string_t[count]); - } - return *this; - } - - /*! - * @brief This function deserializes an array of wide-strings. - * @param string_t The variable that will store the array of strings read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - inline - FastCdr& deserializeArray( - std::wstring* string_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(string_t[count]); - } - return *this; - } - - /*! - * @brief This function template deserializes an array of sequences. - * @param vector_t The variable that will store the array of sequences read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeArray( - std::vector<_T>* vector_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - deserialize(vector_t[count]); - } - return *this; - } - - /*! - * @brief This function template deserializes an array of non-basic type objects. - * @param type_t The variable that will store the array of objects read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeArray( - _T* type_t, - size_t numElements) - { - for (size_t count = 0; count < numElements; ++count) - { - type_t[count].deserialize(*this); - } - return *this; - } + /*! + * @brief This function template deserializes a sequence of booleans. + * @param vector_t The variable that will store the sequence read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template <> + FastCdr& deserialize(std::vector& vector_t) + { + return deserializeBoolSequence(vector_t); + } + +#endif // ifdef _MSC_VER + + /*! + * @brief This function template deserializes a non-basic type object. + * @param type_t The variable that will store the object read from the buffer. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + inline FastCdr& deserialize(_T& type_t) + { + type_t.deserialize(*this); + return *this; + } + + /*! + * @brief This function deserializes an array of octets. + * @param octet_t The variable that will store the array of octets read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(uint8_t* octet_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(octet_t), numElements); + } + + /*! + * @brief This function deserializes an array of characters. + * @param char_t The variable that will store the array of characters read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(char* char_t, size_t numElements); + + /*! + * @brief This function deserializes an array of int8_t. + * @param int8 The variable that will store the array of int8_t read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(int8_t* int8, size_t numElements) + { + return deserializeArray(reinterpret_cast(int8), numElements); + } + + /*! + * @brief This function deserializes an array of unsigned shorts. + * @param ushort_t The variable that will store the array of unsigned shorts read from + * the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(uint16_t* ushort_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ushort_t), numElements); + } + + /*! + * @brief This function deserializes an array of shorts. + * @param short_t The variable that will store the array of shorts read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(int16_t* short_t, size_t numElements); + + /*! + * @brief This function deserializes an array of unsigned longs. + * @param ulong_t The variable that will store the array of unsigned longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(uint32_t* ulong_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ulong_t), numElements); + } + + /*! + * @brief This function deserializes an array of longs. + * @param long_t The variable that will store the array of longs read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(int32_t* long_t, size_t numElements); + + /*! + * @brief This function deserializes an array of wide-chars. + * @param wchar The variable that will store the array of wide-chars read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(wchar_t* wchar, size_t numElements); + + /*! + * @brief This function deserializes an array of unsigned long longs. + * @param ulonglong_t The variable that will store the array of unsigned long longs read + * from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(uint64_t* ulonglong_t, size_t numElements) + { + return deserializeArray(reinterpret_cast(ulonglong_t), numElements); + } + + /*! + * @brief This function deserializes an array of long longs. + * @param longlong_t The variable that will store the array of long longs read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(int64_t* longlong_t, size_t numElements); + + /*! + * @brief This function deserializes an array of floats. + * @param float_t The variable that will store the array of floats read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(float* float_t, size_t numElements); + + /*! + * @brief This function deserializes an array of doubles. + * @param double_t The variable that will store the array of doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(double* double_t, size_t numElements); + + /*! + * @brief This function deserializes an array of long doubles. + * @param ldouble_t The variable that will store the array of long doubles read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(long double* ldouble_t, size_t numElements); + + /*! + * @brief This function deserializes an array of booleans. + * @param bool_t The variable that will store the array of booleans read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + FastCdr& deserializeArray(bool* bool_t, size_t numElements); + + /*! + * @brief This function deserializes an array of strings. + * @param string_t The variable that will store the array of strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(std::string* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(string_t[count]); + } + return *this; + } + + /*! + * @brief This function deserializes an array of wide-strings. + * @param string_t The variable that will store the array of strings read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + inline FastCdr& deserializeArray(std::wstring* string_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(string_t[count]); + } + return *this; + } + + /*! + * @brief This function template deserializes an array of sequences. + * @param vector_t The variable that will store the array of sequences read from the + * buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeArray(std::vector<_T>* vector_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + deserialize(vector_t[count]); + } + return *this; + } + + /*! + * @brief This function template deserializes an array of non-basic type objects. + * @param type_t The variable that will store the array of objects read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeArray(_T* type_t, size_t numElements) + { + for (size_t count = 0; count < numElements; ++count) + { + type_t[count].deserialize(*this); + } + return *this; + } #if !defined(_MSC_VER) && HAVE_CXX0X - /*! - * @brief This function template deserializes a string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeSequence( - std::string*& sequence_t, - size_t& numElements) - { - return deserializeStringSequence(sequence_t, numElements); - } - - /*! - * @brief This function template deserializes a wide-string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeSequence( - std::wstring*& sequence_t, - size_t& numElements) - { - return deserializeWStringSequence(sequence_t, numElements); - } - -#endif // if !defined(_MSC_VER) && HAVE_CXX0X - - /*! - * @brief This function template deserializes a raw sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeSequence( - _T*& sequence_t, - size_t& numElements) - { - uint32_t seqLength = 0; - state state_before_error(*this); - - deserialize(seqLength); - - try - { - sequence_t = reinterpret_cast<_T*>(calloc(seqLength, sizeof(_T))); - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - free(sequence_t); - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } - - numElements = seqLength; - return *this; - } + /*! + * @brief This function template deserializes a string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeSequence(std::string*& sequence_t, size_t& numElements) + { + return deserializeStringSequence(sequence_t, numElements); + } + + /*! + * @brief This function template deserializes a wide-string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeSequence(std::wstring*& sequence_t, size_t& numElements) + { + return deserializeWStringSequence(sequence_t, numElements); + } + +#endif // if !defined(_MSC_VER) && HAVE_CXX0X + + /*! + * @brief This function template deserializes a raw sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeSequence(_T*& sequence_t, size_t& numElements) + { + uint32_t seqLength = 0; + state state_before_error(*this); + + deserialize(seqLength); + + try + { + sequence_t = reinterpret_cast<_T*>(calloc(seqLength, sizeof(_T))); + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + free(sequence_t); + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } + + numElements = seqLength; + return *this; + } #ifdef _MSC_VER - /*! - * @brief This function template deserializes a string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template<> - FastCdr& deserializeSequence( - std::string*& sequence_t, - size_t& numElements) - { - return deserializeStringSequence(sequence_t, numElements); - } - - /*! - * @brief This function template deserializes a wide-string sequence. - * This function allocates memory to store the sequence. The user pointer will be set to point this allocated memory. - * The user will have to free this allocated memory using free() - * @param sequence_t The pointer that will store the sequence read from the buffer. - * @param numElements This variable return the number of elements of the sequence. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template<> - FastCdr& deserializeSequence( - std::wstring*& sequence_t, - size_t& numElements) - { - return deserializeWStringSequence(sequence_t, numElements); - } - -#endif // ifdef _MSC_VER + /*! + * @brief This function template deserializes a string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template <> + FastCdr& deserializeSequence(std::string*& sequence_t, size_t& numElements) + { + return deserializeStringSequence(sequence_t, numElements); + } + + /*! + * @brief This function template deserializes a wide-string sequence. + * This function allocates memory to store the sequence. The user pointer will be set to + * point this allocated memory. The user will have to free this allocated memory using + * free() + * @param sequence_t The pointer that will store the sequence read from the buffer. + * @param numElements This variable return the number of elements of the sequence. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template <> + FastCdr& deserializeSequence(std::wstring*& sequence_t, + size_t& numElements) + { + return deserializeWStringSequence(sequence_t, numElements); + } + +#endif // ifdef _MSC_VER private: + FastCdr(const FastCdr&) = delete; - FastCdr( - const FastCdr&) = delete; - - FastCdr& operator =( - const FastCdr&) = delete; + FastCdr& operator=(const FastCdr&) = delete; - FastCdr& serializeBoolSequence( - const std::vector& vector_t); + FastCdr& serializeBoolSequence(const std::vector& vector_t); - FastCdr& deserializeBoolSequence( - std::vector& vector_t); + FastCdr& deserializeBoolSequence(std::vector& vector_t); - FastCdr& deserializeStringSequence( - std::string*& sequence_t, - size_t& numElements); + FastCdr& deserializeStringSequence(std::string*& sequence_t, size_t& numElements); - FastCdr& deserializeWStringSequence( - std::wstring*& sequence_t, - size_t& numElements); + FastCdr& deserializeWStringSequence(std::wstring*& sequence_t, size_t& numElements); #if HAVE_CXX0X - /*! - * @brief This function template detects the content type of the STD container array and serializes the array. - * @param array_t The array that will be serialized in the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to serialize in a position that exceeds the internal memory size. - */ - template - FastCdr& serializeArray( - const std::array<_T, _Size>* array_t, - size_t numElements) - { - return serializeArray(array_t->data(), numElements * array_t->size()); - } - - /*! - * @brief This function template detects the content type of the STD container array and deserializes the array. - * @param array_t The variable that will store the array read from the buffer. - * @param numElements Number of the elements in the array. - * @return Reference to the eprosima::fastcdr::FastCdr object. - * @exception exception::NotEnoughMemoryException This exception is thrown when trying to deserialize in a position that exceeds the internal memory size. - */ - template - FastCdr& deserializeArray( - std::array<_T, _Size>* array_t, - size_t numElements) - { - return deserializeArray(array_t->data(), numElements * array_t->size()); - } - -#endif // if HAVE_CXX0X - - bool resize( - size_t minSizeInc); - - const char* readString( - uint32_t& length); - - std::wstring readWString( - uint32_t& length); - - //! @brief Reference to the buffer that will be serialized/deserialized. - FastBuffer& m_cdrBuffer; - - //! @brief The current position in the serialization/deserialization process. - FastBuffer::iterator m_currentPosition; - - //! @brief The last position in the buffer; - FastBuffer::iterator m_lastPosition; + /*! + * @brief This function template detects the content type of the STD container array and + * serializes the array. + * @param array_t The array that will be serialized in the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to serialize in a position that exceeds the internal memory size. + */ + template + FastCdr& serializeArray(const std::array<_T, _Size>* array_t, size_t numElements) + { + return serializeArray(array_t->data(), numElements * array_t->size()); + } + + /*! + * @brief This function template detects the content type of the STD container array and + * deserializes the array. + * @param array_t The variable that will store the array read from the buffer. + * @param numElements Number of the elements in the array. + * @return Reference to the eprosima::fastcdr::FastCdr object. + * @exception exception::NotEnoughMemoryException This exception is thrown when trying + * to deserialize in a position that exceeds the internal memory size. + */ + template + FastCdr& deserializeArray(std::array<_T, _Size>* array_t, size_t numElements) + { + return deserializeArray(array_t->data(), numElements * array_t->size()); + } + +#endif // if HAVE_CXX0X + + bool resize(size_t minSizeInc); + + const char* readString(uint32_t& length); + + std::wstring readWString(uint32_t& length); + + //! @brief Reference to the buffer that will be serialized/deserialized. + FastBuffer& m_cdrBuffer; + + //! @brief The current position in the serialization/deserialization process. + FastBuffer::iterator m_currentPosition; + + //! @brief The last position in the buffer; + FastBuffer::iterator m_lastPosition; }; -} //namespace fastcdr -} //namespace eprosima +} // namespace fastcdr +} // namespace eprosima -#endif //_FASTCDR_FASTCDR_H_ +#endif //_FASTCDR_FASTCDR_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/eProsima_auto_link.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/eProsima_auto_link.h index 3e821d8cf..418e3f477 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/eProsima_auto_link.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/eProsima_auto_link.h @@ -21,47 +21,49 @@ */ #if defined(_MSC_VER) - #define EPROSIMA_STRINGIZE(X) EPROSIMA_DO_STRINGIZE(X) - #define EPROSIMA_DO_STRINGIZE(X) #X +#define EPROSIMA_STRINGIZE(X) EPROSIMA_DO_STRINGIZE(X) +#define EPROSIMA_DO_STRINGIZE(X) #X - #if defined(_DEBUG) - #define EPROSIMA_LIB_DEBUG_TAG "d" - #else - #define EPROSIMA_LIB_DEBUG_TAG - #endif // _DEBUG +#if defined(_DEBUG) +#define EPROSIMA_LIB_DEBUG_TAG "d" +#else +#define EPROSIMA_LIB_DEBUG_TAG +#endif // _DEBUG // Select linkage option. - #if (defined(_DLL) || defined(_RTLDLL)) && defined(EPROSIMA_DYN_LINK) - #define EPROSIMA_LIB_PREFIX - #elif defined(EPROSIMA_DYN_LINK) - #error "Mixing a dll eprosima library with a static runtime is a bad idea" - #else - #define EPROSIMA_LIB_PREFIX "lib" - #endif // if (defined(_DLL) || defined(_RTLDLL)) && defined(EPROSIMA_DYN_LINK) +#if (defined(_DLL) || defined(_RTLDLL)) && defined(EPROSIMA_DYN_LINK) +#define EPROSIMA_LIB_PREFIX +#elif defined(EPROSIMA_DYN_LINK) +#error "Mixing a dll eprosima library with a static runtime is a bad idea" +#else +#define EPROSIMA_LIB_PREFIX "lib" +#endif // if (defined(_DLL) || defined(_RTLDLL)) && defined(EPROSIMA_DYN_LINK) // Include library - #if defined(EPROSIMA_LIB_NAME) \ - && defined(EPROSIMA_LIB_PREFIX) \ - && defined(EPROSIMA_LIB_DEBUG_TAG) \ - && defined(FASTCDR_VERSION_MAJOR) \ - && defined(FASTCDR_VERSION_MINOR) - #pragma \ - comment(lib, EPROSIMA_LIB_PREFIX EPROSIMA_STRINGIZE(EPROSIMA_LIB_NAME) EPROSIMA_LIB_DEBUG_TAG "-" EPROSIMA_STRINGIZE(FASTCDR_VERSION_MAJOR) "." EPROSIMA_STRINGIZE(FASTCDR_VERSION_MINOR) ".lib") - #else - #error "Some required macros where not defined" - #endif // if defined(EPROSIMA_LIB_NAME) && defined(EPROSIMA_LIB_PREFIX) && defined(EPROSIMA_LIB_DEBUG_TAG) && defined(FASTCDR_VERSION_MAJOR) && defined(FASTCDR_VERSION_MINOR) +#if defined(EPROSIMA_LIB_NAME) && defined(EPROSIMA_LIB_PREFIX) && \ + defined(EPROSIMA_LIB_DEBUG_TAG) && defined(FASTCDR_VERSION_MAJOR) && \ + defined(FASTCDR_VERSION_MINOR) +#pragma comment(lib, EPROSIMA_LIB_PREFIX EPROSIMA_STRINGIZE(EPROSIMA_LIB_NAME) \ + EPROSIMA_LIB_DEBUG_TAG \ + "-" EPROSIMA_STRINGIZE(FASTCDR_VERSION_MAJOR) "." EPROSIMA_STRINGIZE( \ + FASTCDR_VERSION_MINOR) ".lib") +#else +#error "Some required macros where not defined" +#endif // if defined(EPROSIMA_LIB_NAME) && defined(EPROSIMA_LIB_PREFIX) && + // defined(EPROSIMA_LIB_DEBUG_TAG) && defined(FASTCDR_VERSION_MAJOR) && + // defined(FASTCDR_VERSION_MINOR) -#endif // _MSC_VER +#endif // _MSC_VER // Undef macros #ifdef EPROSIMA_LIB_PREFIX #undef EPROSIMA_LIB_PREFIX -#endif // ifdef EPROSIMA_LIB_PREFIX +#endif // ifdef EPROSIMA_LIB_PREFIX #ifdef EPROSIMA_LIB_NAME #undef EPROSIMA_LIB_NAME -#endif // ifdef EPROSIMA_LIB_NAME +#endif // ifdef EPROSIMA_LIB_NAME #ifdef EPROSIMA_LIB_DEBUG_TAG #undef EPROSIMA_LIB_DEBUG_TAG -#endif // ifdef EPROSIMA_LIB_DEBUG_TAG +#endif // ifdef EPROSIMA_LIB_DEBUG_TAG diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/BadParamException.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/BadParamException.h index 95838ed84..1abba7d77 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/BadParamException.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/BadParamException.h @@ -17,71 +17,69 @@ #include "Exception.h" -namespace eprosima { -namespace fastcdr { -namespace exception { +namespace eprosima +{ +namespace fastcdr +{ +namespace exception +{ /*! - * @brief This class is thrown as an exception when a invalid parameter was being serialized. + * @brief This class is thrown as an exception when a invalid parameter was being + * serialized. * @ingroup EXCEPTIONMODULE */ class BadParamException : public Exception { public: + /*! + * @brief Default constructor. + * + * @param message A error message. This message pointer is copied. + */ + Cdr_DllAPI BadParamException(const char* const& message) noexcept; - /*! - * @brief Default constructor. - * - * @param message A error message. This message pointer is copied. - */ - Cdr_DllAPI BadParamException( - const char* const& message) noexcept; - - /*! - * @brief Default copy constructor. - * - * @param ex BadParamException that will be copied. - */ - Cdr_DllAPI BadParamException( - const BadParamException& ex) noexcept; + /*! + * @brief Default copy constructor. + * + * @param ex BadParamException that will be copied. + */ + Cdr_DllAPI BadParamException(const BadParamException& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Default move constructor. - * - * @param ex BadParamException that will be moved. - */ - Cdr_DllAPI BadParamException( - BadParamException&& ex) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Default move constructor. + * + * @param ex BadParamException that will be moved. + */ + Cdr_DllAPI BadParamException(BadParamException&& ex) noexcept; +#endif // if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex BadParamException that will be copied. - */ - Cdr_DllAPI BadParamException& operator =( - const BadParamException& ex) noexcept; + /*! + * @brief Assigment operation. + * + * @param ex BadParamException that will be copied. + */ + Cdr_DllAPI BadParamException& operator=(const BadParamException& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex BadParamException that will be moved. - */ - BadParamException& operator =( - BadParamException&& ex) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Assigment operation. + * + * @param ex BadParamException that will be moved. + */ + BadParamException& operator=(BadParamException&& ex) noexcept; +#endif // if HAVE_CXX0X - //! @brief Default constructor - virtual Cdr_DllAPI ~BadParamException() noexcept; + //! @brief Default constructor + virtual Cdr_DllAPI ~BadParamException() noexcept; - //! @brief This function throws the object as exception. - virtual Cdr_DllAPI void raise() const; + //! @brief This function throws the object as exception. + virtual Cdr_DllAPI void raise() const; - //! @brief Default message used in the library. - static Cdr_DllAPI const char* const BAD_PARAM_MESSAGE_DEFAULT; + //! @brief Default message used in the library. + static Cdr_DllAPI const char* const BAD_PARAM_MESSAGE_DEFAULT; }; -} //namespace exception -} //namespace fastcdr -} //namespace eprosima -#endif // _FASTCDR_EXCEPTIONS_BADPARAMEXCEPTION_H_ +} // namespace exception +} // namespace fastcdr +} // namespace eprosima +#endif // _FASTCDR_EXCEPTIONS_BADPARAMEXCEPTION_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/Exception.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/Exception.h index b37133267..4752a08c5 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/Exception.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/Exception.h @@ -19,9 +19,12 @@ #include #include -namespace eprosima { -namespace fastcdr { -namespace exception { +namespace eprosima +{ +namespace fastcdr +{ +namespace exception +{ /*! * @brief This abstract class is used to create exceptions. * @ingroup EXCEPTIONMODULE @@ -29,72 +32,64 @@ namespace exception { class Exception : public std::exception { public: + //! \brief Default destructor. + virtual Cdr_DllAPI ~Exception() noexcept; - //! \brief Default destructor. - virtual Cdr_DllAPI ~Exception() noexcept; + //! \brief This function throws the object as exception. + virtual Cdr_DllAPI void raise() const = 0; - //! \brief This function throws the object as exception. - virtual Cdr_DllAPI void raise() const = 0; - - /*! - * @brief This function returns the error message. - * - * @return The error message. - */ - virtual Cdr_DllAPI const char* what() const noexcept override; + /*! + * @brief This function returns the error message. + * + * @return The error message. + */ + virtual Cdr_DllAPI const char* what() const noexcept override; protected: + /*! + * @brief Default constructor. + * + * @param message A error message. This message pointer is copied. + */ + Cdr_DllAPI Exception(const char* const& message) noexcept; - /*! - * @brief Default constructor. - * - * @param message A error message. This message pointer is copied. - */ - Cdr_DllAPI Exception( - const char* const& message) noexcept; - - /*! - * @brief Default copy constructor. - * - * @param ex Exception that will be copied. - */ - Cdr_DllAPI Exception( - const Exception& ex) noexcept; + /*! + * @brief Default copy constructor. + * + * @param ex Exception that will be copied. + */ + Cdr_DllAPI Exception(const Exception& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Default move constructor. - * - * @param ex Exception that will be moved. - */ - Cdr_DllAPI Exception( - Exception&& ex) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Default move constructor. + * + * @param ex Exception that will be moved. + */ + Cdr_DllAPI Exception(Exception&& ex) noexcept; +#endif // if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex Exception that will be copied. - */ - Cdr_DllAPI Exception& operator =( - const Exception& ex) noexcept; + /*! + * @brief Assigment operation. + * + * @param ex Exception that will be copied. + */ + Cdr_DllAPI Exception& operator=(const Exception& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex Exception that will be moved. - */ - Cdr_DllAPI Exception& operator =( - Exception&&) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Assigment operation. + * + * @param ex Exception that will be moved. + */ + Cdr_DllAPI Exception& operator=(Exception&&) noexcept; +#endif // if HAVE_CXX0X private: - - const char* m_message; + const char* m_message; }; -} //namespace exception -} //namespace fastcdr -} //namespace eprosima +} // namespace exception +} // namespace fastcdr +} // namespace eprosima -#endif // _FASTCDR_EXCEPTIONS_EXCEPTION_H_ +#endif // _FASTCDR_EXCEPTIONS_EXCEPTION_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/NotEnoughMemoryException.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/NotEnoughMemoryException.h index 3a190c525..808d719e6 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/NotEnoughMemoryException.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/exceptions/NotEnoughMemoryException.h @@ -17,71 +17,70 @@ #include "Exception.h" -namespace eprosima { -namespace fastcdr { -namespace exception { +namespace eprosima +{ +namespace fastcdr +{ +namespace exception +{ /*! - * @brief This class is thrown as an exception when the buffer's internal memory reachs its size limit. + * @brief This class is thrown as an exception when the buffer's internal memory reachs + * its size limit. * @ingroup EXCEPTIONMODULE */ class NotEnoughMemoryException : public Exception { public: + /*! + * @brief Default constructor. + * + * @param message A error message. This message pointer is copied. + */ + Cdr_DllAPI NotEnoughMemoryException(const char* const& message) noexcept; - /*! - * @brief Default constructor. - * - * @param message A error message. This message pointer is copied. - */ - Cdr_DllAPI NotEnoughMemoryException( - const char* const& message) noexcept; - - /*! - * @brief Default copy constructor. - * - * @param ex NotEnoughMemoryException that will be copied. - */ - Cdr_DllAPI NotEnoughMemoryException( - const NotEnoughMemoryException& ex) noexcept; + /*! + * @brief Default copy constructor. + * + * @param ex NotEnoughMemoryException that will be copied. + */ + Cdr_DllAPI NotEnoughMemoryException(const NotEnoughMemoryException& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Default move constructor. - * - * @param ex NotEnoughMemoryException that will be moved. - */ - Cdr_DllAPI NotEnoughMemoryException( - NotEnoughMemoryException&& ex) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Default move constructor. + * + * @param ex NotEnoughMemoryException that will be moved. + */ + Cdr_DllAPI NotEnoughMemoryException(NotEnoughMemoryException&& ex) noexcept; +#endif // if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex NotEnoughMemoryException that will be copied. - */ - Cdr_DllAPI NotEnoughMemoryException& operator =( - const NotEnoughMemoryException& ex) noexcept; + /*! + * @brief Assigment operation. + * + * @param ex NotEnoughMemoryException that will be copied. + */ + Cdr_DllAPI NotEnoughMemoryException& + operator=(const NotEnoughMemoryException& ex) noexcept; #if HAVE_CXX0X - /*! - * @brief Assigment operation. - * - * @param ex NotEnoughMemoryException that will be moved. - */ - Cdr_DllAPI NotEnoughMemoryException& operator =( - NotEnoughMemoryException&& ex) noexcept; -#endif // if HAVE_CXX0X + /*! + * @brief Assigment operation. + * + * @param ex NotEnoughMemoryException that will be moved. + */ + Cdr_DllAPI NotEnoughMemoryException& operator=(NotEnoughMemoryException&& ex) noexcept; +#endif // if HAVE_CXX0X - //! @brief Default constructor - virtual Cdr_DllAPI ~NotEnoughMemoryException() noexcept; + //! @brief Default constructor + virtual Cdr_DllAPI ~NotEnoughMemoryException() noexcept; - //! @brief This function throws the object as exception. - virtual Cdr_DllAPI void raise() const override; + //! @brief This function throws the object as exception. + virtual Cdr_DllAPI void raise() const override; - //! @brief Default message used in the library. - static Cdr_DllAPI const char* const NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT; + //! @brief Default message used in the library. + static Cdr_DllAPI const char* const NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT; }; -} //namespace exception -} //namespace fastcdr -} //namespace eprosima -#endif // _FASTCDR_EXCEPTIONS_NOTENOUGHMEMORYEXCEPTION_H_ +} // namespace exception +} // namespace fastcdr +} // namespace eprosima +#endif // _FASTCDR_EXCEPTIONS_NOTENOUGHMEMORYEXCEPTION_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/fastcdr_dll.h b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/fastcdr_dll.h index c355f2f40..ebc51b572 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/fastcdr_dll.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/include/fastcdr/fastcdr_dll.h @@ -18,52 +18,52 @@ #include // normalize macros -#if !defined(FASTCDR_DYN_LINK) && !defined(FASTCDR_STATIC_LINK) \ - && !defined(EPROSIMA_ALL_DYN_LINK) && !defined(EPROSIMA_ALL_STATIC_LINK) +#if !defined(FASTCDR_DYN_LINK) && !defined(FASTCDR_STATIC_LINK) && \ + !defined(EPROSIMA_ALL_DYN_LINK) && !defined(EPROSIMA_ALL_STATIC_LINK) #define FASTCDR_STATIC_LINK -#endif // if !defined(FASTCDR_DYN_LINK) && !defined(FASTCDR_STATIC_LINK) && !defined(EPROSIMA_ALL_DYN_LINK) && !defined(EPROSIMA_ALL_STATIC_LINK) +#endif // if !defined(FASTCDR_DYN_LINK) && !defined(FASTCDR_STATIC_LINK) && + // !defined(EPROSIMA_ALL_DYN_LINK) && !defined(EPROSIMA_ALL_STATIC_LINK) #if defined(EPROSIMA_ALL_DYN_LINK) && !defined(FASTCDR_DYN_LINK) #define FASTCDR_DYN_LINK -#endif // if defined(EPROSIMA_ALL_DYN_LINK) && !defined(FASTCDR_DYN_LINK) +#endif // if defined(EPROSIMA_ALL_DYN_LINK) && !defined(FASTCDR_DYN_LINK) #if defined(FASTCDR_DYN_LINK) && defined(FASTCDR_STATIC_LINK) #error Must not define both FASTCDR_DYN_LINK and FASTCDR_STATIC_LINK -#endif // if defined(FASTCDR_DYN_LINK) && defined(FASTCDR_STATIC_LINK) +#endif // if defined(FASTCDR_DYN_LINK) && defined(FASTCDR_STATIC_LINK) #if defined(EPROSIMA_ALL_NO_LIB) && !defined(FASTCDR_NO_LIB) #define FASTCDR_NO_LIB -#endif // if defined(EPROSIMA_ALL_NO_LIB) && !defined(FASTCDR_NO_LIB) +#endif // if defined(EPROSIMA_ALL_NO_LIB) && !defined(FASTCDR_NO_LIB) // enable dynamic linking #if defined(_WIN32) #if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) #if defined(fastcdr_EXPORTS) -#define Cdr_DllAPI __declspec( dllexport ) +#define Cdr_DllAPI __declspec(dllexport) #else -#define Cdr_DllAPI __declspec( dllimport ) -#endif // FASTCDR_SOURCE +#define Cdr_DllAPI __declspec(dllimport) +#endif // FASTCDR_SOURCE #else #define Cdr_DllAPI -#endif // if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) +#endif // if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) #else #define Cdr_DllAPI -#endif // _WIN32 +#endif // _WIN32 // Auto linking. -#if !defined(FASTCDR_SOURCE) && !defined(EPROSIMA_ALL_NO_LIB) \ - && !defined(FASTCDR_NO_LIB) +#if !defined(FASTCDR_SOURCE) && !defined(EPROSIMA_ALL_NO_LIB) && !defined(FASTCDR_NO_LIB) // Set properties. #define EPROSIMA_LIB_NAME fastcdr #if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) #define EPROSIMA_DYN_LINK -#endif // if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) +#endif // if defined(EPROSIMA_ALL_DYN_LINK) || defined(FASTCDR_DYN_LINK) #include "eProsima_auto_link.h" -#endif // auto-linking disabled +#endif // auto-linking disabled -#endif // _FASTCDR_FASTCDR_DLL_H_ +#endif // _FASTCDR_FASTCDR_DLL_H_ diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/Cdr.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/Cdr.cpp index 4a8bb25a7..b232a23e5 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/Cdr.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/Cdr.cpp @@ -22,2725 +22,2653 @@ using namespace ::exception; const Cdr::Endianness Cdr::DEFAULT_ENDIAN = BIG_ENDIANNESS; #else const Cdr::Endianness Cdr::DEFAULT_ENDIAN = LITTLE_ENDIANNESS; -#endif // if FASTCDR_IS_BIG_ENDIAN_TARGET +#endif // if FASTCDR_IS_BIG_ENDIAN_TARGET CONSTEXPR size_t ALIGNMENT_LONG_DOUBLE = 8; -Cdr::state::state( - const Cdr& cdr) - : m_currentPosition(cdr.m_currentPosition) - , m_alignPosition(cdr.m_alignPosition) - , m_swapBytes(cdr.m_swapBytes) - , m_lastDataSize(cdr.m_lastDataSize) +Cdr::state::state(const Cdr& cdr) + : m_currentPosition(cdr.m_currentPosition) + , m_alignPosition(cdr.m_alignPosition) + , m_swapBytes(cdr.m_swapBytes) + , m_lastDataSize(cdr.m_lastDataSize) { } -Cdr::state::state( - const state& current_state) - : m_currentPosition(current_state.m_currentPosition) - , m_alignPosition(current_state.m_alignPosition) - , m_swapBytes(current_state.m_swapBytes) - , m_lastDataSize(current_state.m_lastDataSize) +Cdr::state::state(const state& current_state) + : m_currentPosition(current_state.m_currentPosition) + , m_alignPosition(current_state.m_alignPosition) + , m_swapBytes(current_state.m_swapBytes) + , m_lastDataSize(current_state.m_lastDataSize) { } -Cdr::Cdr( - FastBuffer& cdrBuffer, - const Endianness endianness, - const CdrType cdrType) - : m_cdrBuffer(cdrBuffer) - , m_cdrType(cdrType) - , m_plFlag(DDS_CDR_WITHOUT_PL) - , m_options(0) - , m_endianness(static_cast(endianness)) - , m_swapBytes(endianness == DEFAULT_ENDIAN ? false : true) - , m_lastDataSize(0) - , m_currentPosition(cdrBuffer.begin()) - , m_alignPosition(cdrBuffer.begin()) - , m_lastPosition(cdrBuffer.end()) +Cdr::Cdr(FastBuffer& cdrBuffer, const Endianness endianness, const CdrType cdrType) + : m_cdrBuffer(cdrBuffer) + , m_cdrType(cdrType) + , m_plFlag(DDS_CDR_WITHOUT_PL) + , m_options(0) + , m_endianness(static_cast(endianness)) + , m_swapBytes(endianness == DEFAULT_ENDIAN ? false : true) + , m_lastDataSize(0) + , m_currentPosition(cdrBuffer.begin()) + , m_alignPosition(cdrBuffer.begin()) + , m_lastPosition(cdrBuffer.end()) { } Cdr& Cdr::read_encapsulation() { - uint8_t dummy = 0, encapsulationKind = 0; - state state_before_error(*this); + uint8_t dummy = 0, encapsulationKind = 0; + state state_before_error(*this); - try + try + { + // If it is DDS_CDR, the first step is to get the dummy byte. + if (m_cdrType == DDS_CDR) { - // If it is DDS_CDR, the first step is to get the dummy byte. - if (m_cdrType == DDS_CDR) - { - (*this) >> dummy; - if (0 != dummy) - { - throw BadParamException("Unexpected non-zero initial byte received in Cdr::read_encapsulation"); - } - } - - // Get the ecampsulation byte. - (*this) >> encapsulationKind; - + (*this) >> dummy; + if (0 != dummy) + { + throw BadParamException("Unexpected non-zero initial byte received in " + "Cdr::read_encapsulation"); + } + } - // If it is a different endianness, make changes. - if (m_endianness != (encapsulationKind & 0x1)) - { - m_swapBytes = !m_swapBytes; - m_endianness = (encapsulationKind & 0x1); - } + // Get the ecampsulation byte. + (*this) >> encapsulationKind; - // Check encapsulationKind correctness - uint8_t allowed_kind_mask = LITTLE_ENDIANNESS; - if (m_cdrType == DDS_CDR) - { - allowed_kind_mask |= DDS_CDR_WITH_PL; - } + // If it is a different endianness, make changes. + if (m_endianness != (encapsulationKind & 0x1)) + { + m_swapBytes = !m_swapBytes; + m_endianness = (encapsulationKind & 0x1); + } - if (0 != (encapsulationKind & ~allowed_kind_mask)) - { - throw BadParamException("Unexpected CDR type received in Cdr::read_encapsulation"); - } + // Check encapsulationKind correctness + uint8_t allowed_kind_mask = LITTLE_ENDIANNESS; + if (m_cdrType == DDS_CDR) + { + allowed_kind_mask |= DDS_CDR_WITH_PL; + } - // If it is DDS_CDR type, view if contains a parameter list. - if ((encapsulationKind & DDS_CDR_WITH_PL) && ((m_cdrType == DDS_CDR))) - { - m_plFlag = DDS_CDR_WITH_PL; - } + if (0 != (encapsulationKind & ~allowed_kind_mask)) + { + throw BadParamException("Unexpected CDR type received in Cdr::read_encapsulation"); + } - if (m_cdrType == DDS_CDR) - { - (*this) >> m_options; - } + // If it is DDS_CDR type, view if contains a parameter list. + if ((encapsulationKind & DDS_CDR_WITH_PL) && ((m_cdrType == DDS_CDR))) + { + m_plFlag = DDS_CDR_WITH_PL; } - catch (Exception& ex) + + if (m_cdrType == DDS_CDR) { - setState(state_before_error); - ex.raise(); + (*this) >> m_options; } + } + catch (Exception& ex) + { + setState(state_before_error); + ex.raise(); + } - resetAlignment(); - return *this; + resetAlignment(); + return *this; } Cdr& Cdr::serialize_encapsulation() { - uint8_t dummy = 0, encapsulationKind = 0; - state state_before_error(*this); + uint8_t dummy = 0, encapsulationKind = 0; + state state_before_error(*this); - try + try + { + // If it is DDS_CDR, the first step is to serialize the dummy byte. + if (m_cdrType == DDS_CDR) { - // If it is DDS_CDR, the first step is to serialize the dummy byte. - if (m_cdrType == DDS_CDR) - { - (*this) << dummy; - } + (*this) << dummy; + } - // Construct encapsulation byte. - encapsulationKind = (static_cast(m_plFlag) | m_endianness); + // Construct encapsulation byte. + encapsulationKind = (static_cast(m_plFlag) | m_endianness); - // Serialize the encapsulation byte. - (*this) << encapsulationKind; - } - catch (Exception& ex) - { - setState(state_before_error); - ex.raise(); - } + // Serialize the encapsulation byte. + (*this) << encapsulationKind; + } + catch (Exception& ex) + { + setState(state_before_error); + ex.raise(); + } - try - { - if (m_cdrType == DDS_CDR) - { - (*this) << m_options; - } - } - catch (Exception& ex) + try + { + if (m_cdrType == DDS_CDR) { - setState(state_before_error); - ex.raise(); + (*this) << m_options; } + } + catch (Exception& ex) + { + setState(state_before_error); + ex.raise(); + } - resetAlignment(); - return *this; + resetAlignment(); + return *this; } Cdr::DDSCdrPlFlag Cdr::getDDSCdrPlFlag() const { - return m_plFlag; + return m_plFlag; } -void Cdr::setDDSCdrPlFlag( - DDSCdrPlFlag plFlag) +void Cdr::setDDSCdrPlFlag(DDSCdrPlFlag plFlag) { - m_plFlag = plFlag; + m_plFlag = plFlag; } uint16_t Cdr::getDDSCdrOptions() const { - return m_options; + return m_options; } -void Cdr::setDDSCdrOptions( - uint16_t options) +void Cdr::setDDSCdrOptions(uint16_t options) { - m_options = options; + m_options = options; } -void Cdr::changeEndianness( - Endianness endianness) +void Cdr::changeEndianness(Endianness endianness) { - if (m_endianness != endianness) - { - m_swapBytes = !m_swapBytes; - m_endianness = endianness; - } + if (m_endianness != endianness) + { + m_swapBytes = !m_swapBytes; + m_endianness = endianness; + } } -bool Cdr::jump( - size_t numBytes) +bool Cdr::jump(size_t numBytes) { - bool returnedValue = false; + bool returnedValue = false; - if (((m_lastPosition - m_currentPosition) >= numBytes) || resize(numBytes)) - { - m_currentPosition += numBytes; - returnedValue = true; - } + if (((m_lastPosition - m_currentPosition) >= numBytes) || resize(numBytes)) + { + m_currentPosition += numBytes; + returnedValue = true; + } - return returnedValue; + return returnedValue; } char* Cdr::getBufferPointer() { - return m_cdrBuffer.getBuffer(); + return m_cdrBuffer.getBuffer(); } char* Cdr::getCurrentPosition() { - return &m_currentPosition; + return &m_currentPosition; } Cdr::state Cdr::getState() { - return Cdr::state(*this); + return Cdr::state(*this); } -void Cdr::setState( - state& current_state) +void Cdr::setState(state& current_state) { - m_currentPosition >> current_state.m_currentPosition; - m_alignPosition >> current_state.m_alignPosition; - m_swapBytes = current_state.m_swapBytes; - m_lastDataSize = current_state.m_lastDataSize; + m_currentPosition >> current_state.m_currentPosition; + m_alignPosition >> current_state.m_alignPosition; + m_swapBytes = current_state.m_swapBytes; + m_lastDataSize = current_state.m_lastDataSize; } void Cdr::reset() { - m_currentPosition = m_cdrBuffer.begin(); - m_alignPosition = m_cdrBuffer.begin(); - m_swapBytes = m_endianness == DEFAULT_ENDIAN ? false : true; - m_lastDataSize = 0; + m_currentPosition = m_cdrBuffer.begin(); + m_alignPosition = m_cdrBuffer.begin(); + m_swapBytes = m_endianness == DEFAULT_ENDIAN ? false : true; + m_lastDataSize = 0; } -bool Cdr::moveAlignmentForward( - size_t numBytes) +bool Cdr::moveAlignmentForward(size_t numBytes) { - bool returnedValue = false; + bool returnedValue = false; - if (((m_lastPosition - m_alignPosition) >= numBytes) || resize(numBytes)) - { - m_alignPosition += numBytes; - returnedValue = true; - } + if (((m_lastPosition - m_alignPosition) >= numBytes) || resize(numBytes)) + { + m_alignPosition += numBytes; + returnedValue = true; + } - return returnedValue; + return returnedValue; } -bool Cdr::resize( - size_t minSizeInc) +bool Cdr::resize(size_t minSizeInc) { - if (m_cdrBuffer.resize(minSizeInc)) - { - m_currentPosition << m_cdrBuffer.begin(); - m_alignPosition << m_cdrBuffer.begin(); - m_lastPosition = m_cdrBuffer.end(); - return true; - } + if (m_cdrBuffer.resize(minSizeInc)) + { + m_currentPosition << m_cdrBuffer.begin(); + m_alignPosition << m_cdrBuffer.begin(); + m_lastPosition = m_cdrBuffer.end(); + return true; + } - return false; + return false; } -Cdr& Cdr::serialize( - const char char_t) +Cdr& Cdr::serialize(const char char_t) { - if (((m_lastPosition - m_currentPosition) >= sizeof(char_t)) || resize(sizeof(char_t))) - { - // Save last datasize. - m_lastDataSize = sizeof(char_t); + if (((m_lastPosition - m_currentPosition) >= sizeof(char_t)) || resize(sizeof(char_t))) + { + // Save last datasize. + m_lastDataSize = sizeof(char_t); - m_currentPosition++ << char_t; - return *this; - } + m_currentPosition++ << char_t; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const int16_t short_t) +Cdr& Cdr::serialize(const int16_t short_t) { - size_t align = alignment(sizeof(short_t)); - size_t sizeAligned = sizeof(short_t) + align; - - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(short_t); - - // Align. - makeAlign(align); - - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&short_t); - - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - else - { - m_currentPosition << short_t; - m_currentPosition += sizeof(short_t); - } + size_t align = alignment(sizeof(short_t)); + size_t sizeAligned = sizeof(short_t) + align; - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(short_t); -Cdr& Cdr::serialize( - const int16_t short_t, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + // Align. + makeAlign(align); - try + if (m_swapBytes) { - serialize(short_t); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&short_t); + + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition << short_t; + m_currentPosition += sizeof(short_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const int32_t long_t) +Cdr& Cdr::serialize(const int16_t short_t, Endianness endianness) { - size_t align = alignment(sizeof(long_t)); - size_t sizeAligned = sizeof(long_t) + align; - - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(long_t); - - // Align. - makeAlign(align); - - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&long_t); - - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - else - { - m_currentPosition << long_t; - m_currentPosition += sizeof(long_t); - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - return *this; - } + try + { + serialize(short_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::serialize( - const int32_t long_t, - Endianness endianness) +Cdr& Cdr::serialize(const int32_t long_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(long_t)); + size_t sizeAligned = sizeof(long_t) + align; + + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(long_t); - try + // Align. + makeAlign(align); + + if (m_swapBytes) { - serialize(long_t); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&long_t); + + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition << long_t; + m_currentPosition += sizeof(long_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const int64_t longlong_t) +Cdr& Cdr::serialize(const int32_t long_t, Endianness endianness) { - size_t align = alignment(sizeof(longlong_t)); - size_t sizeAligned = sizeof(longlong_t) + align; - - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(longlong_t); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - // Align. - makeAlign(align); - - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&longlong_t); - - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - else - { - m_currentPosition << longlong_t; - m_currentPosition += sizeof(longlong_t); - } - - return *this; - } + try + { + serialize(long_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::serialize( - const int64_t longlong_t, - Endianness endianness) +Cdr& Cdr::serialize(const int64_t longlong_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(longlong_t)); + size_t sizeAligned = sizeof(longlong_t) + align; - try + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(longlong_t); + + // Align. + makeAlign(align); + + if (m_swapBytes) { - serialize(longlong_t); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&longlong_t); + + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition << longlong_t; + m_currentPosition += sizeof(longlong_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const float float_t) +Cdr& Cdr::serialize(const int64_t longlong_t, Endianness endianness) { - size_t align = alignment(sizeof(float_t)); - size_t sizeAligned = sizeof(float_t) + align; - - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(float_t); - - // Align. - makeAlign(align); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&float_t); + try + { + serialize(longlong_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - else - { - m_currentPosition << float_t; - m_currentPosition += sizeof(float_t); - } - - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::serialize( - const float float_t, - Endianness endianness) +Cdr& Cdr::serialize(const float float_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(float_t)); + size_t sizeAligned = sizeof(float_t) + align; + + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(float_t); - try + // Align. + makeAlign(align); + + if (m_swapBytes) { - serialize(float_t); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&float_t); + + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition << float_t; + m_currentPosition += sizeof(float_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const double double_t) +Cdr& Cdr::serialize(const float float_t, Endianness endianness) { - size_t align = alignment(sizeof(double_t)); - size_t sizeAligned = sizeof(double_t) + align; + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(double_t); - - // Align. - makeAlign(align); - - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&double_t); - - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - else - { - m_currentPosition << double_t; - m_currentPosition += sizeof(double_t); - } + try + { + serialize(float_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::serialize( - const double double_t, - Endianness endianness) +Cdr& Cdr::serialize(const double double_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(double_t)); + size_t sizeAligned = sizeof(double_t) + align; + + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(double_t); + + // Align. + makeAlign(align); - try + if (m_swapBytes) { - serialize(double_t); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&double_t); + + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition << double_t; + m_currentPosition += sizeof(double_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const long double ldouble_t) +Cdr& Cdr::serialize(const double double_t, Endianness endianness) { - size_t align = alignment(ALIGNMENT_LONG_DOUBLE); - size_t sizeAligned = sizeof(ldouble_t) + align; + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = 16; // sizeof(ldouble_t); + try + { + serialize(double_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; +} + +Cdr& Cdr::serialize(const long double ldouble_t) +{ + size_t align = alignment(ALIGNMENT_LONG_DOUBLE); + size_t sizeAligned = sizeof(ldouble_t) + align; - // Align. - makeAlign(align); + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = 16; // sizeof(ldouble_t); - if (m_swapBytes) - { + // Align. + makeAlign(align); + + if (m_swapBytes) + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp = ldouble_t; - const char* dst = reinterpret_cast(&tmp); + __float128 tmp = ldouble_t; + const char* dst = reinterpret_cast(&tmp); #else - const char* dst = reinterpret_cast(&ldouble_t); -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + const char* dst = reinterpret_cast(&ldouble_t); +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 #if FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ << dst[15]; - m_currentPosition++ << dst[14]; - m_currentPosition++ << dst[13]; - m_currentPosition++ << dst[12]; - m_currentPosition++ << dst[11]; - m_currentPosition++ << dst[10]; - m_currentPosition++ << dst[9]; - m_currentPosition++ << dst[8]; - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; + m_currentPosition++ << dst[15]; + m_currentPosition++ << dst[14]; + m_currentPosition++ << dst[13]; + m_currentPosition++ << dst[12]; + m_currentPosition++ << dst[11]; + m_currentPosition++ << dst[10]; + m_currentPosition++ << dst[9]; + m_currentPosition++ << dst[8]; + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - // Filled with 0's. - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; + // Filled with 0's. + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 -#endif // FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - } - else - { +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 +#endif // FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 + } + else + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp = ldouble_t; - m_currentPosition << tmp; - m_currentPosition += 16; + __float128 tmp = ldouble_t; + m_currentPosition << tmp; + m_currentPosition += 16; #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - m_currentPosition << static_cast(0); - m_currentPosition += sizeof(ldouble_t); -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 + m_currentPosition << static_cast(0); + m_currentPosition += sizeof(ldouble_t); +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition << ldouble_t; - m_currentPosition += sizeof(ldouble_t); + m_currentPosition << ldouble_t; + m_currentPosition += sizeof(ldouble_t); #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - } - - return *this; +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const long double ldouble_t, - Endianness endianness) +Cdr& Cdr::serialize(const long double ldouble_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - serialize(ldouble_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + serialize(ldouble_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::serialize( - const bool bool_t) +Cdr& Cdr::serialize(const bool bool_t) { - uint8_t value = 0; - - if (((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) || resize(sizeof(uint8_t))) - { - // Save last datasize. - m_lastDataSize = sizeof(uint8_t); + uint8_t value = 0; - if (bool_t) - { - value = 1; - } - m_currentPosition++ << value; + if (((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) || + resize(sizeof(uint8_t))) + { + // Save last datasize. + m_lastDataSize = sizeof(uint8_t); - return *this; + if (bool_t) + { + value = 1; } + m_currentPosition++ << value; - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serialize( - const char* string_t) +Cdr& Cdr::serialize(const char* string_t) { - uint32_t length = 0; + uint32_t length = 0; - if (string_t != nullptr) - { - length = size_to_uint32(strlen(string_t)) + 1; - } + if (string_t != nullptr) + { + length = size_to_uint32(strlen(string_t)) + 1; + } - if (length > 0) - { - Cdr::state state_before_error(*this); - serialize(length); + if (length > 0) + { + Cdr::state state_before_error(*this); + serialize(length); - if (((m_lastPosition - m_currentPosition) >= length) || resize(length)) - { - // Save last datasize. - m_lastDataSize = sizeof(uint8_t); + if (((m_lastPosition - m_currentPosition) >= length) || resize(length)) + { + // Save last datasize. + m_lastDataSize = sizeof(uint8_t); - m_currentPosition.memcopy(string_t, length); - m_currentPosition += length; - } - else - { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } + m_currentPosition.memcopy(string_t, length); + m_currentPosition += length; } else { - serialize(length); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } + } + else + { + serialize(length); + } - return *this; + return *this; } -Cdr& Cdr::serialize( - const wchar_t* string_t) +Cdr& Cdr::serialize(const wchar_t* string_t) { - uint32_t bytesLength = 0; - size_t wstrlen = 0; + uint32_t bytesLength = 0; + size_t wstrlen = 0; - if (string_t != nullptr) - { - wstrlen = wcslen(string_t); - bytesLength = size_to_uint32(wstrlen * 4); - } + if (string_t != nullptr) + { + wstrlen = wcslen(string_t); + bytesLength = size_to_uint32(wstrlen * 4); + } - if (bytesLength > 0) - { - Cdr::state state_(*this); - serialize(size_to_uint32(wstrlen)); + if (bytesLength > 0) + { + Cdr::state state_(*this); + serialize(size_to_uint32(wstrlen)); - if (((m_lastPosition - m_currentPosition) >= bytesLength) || resize(bytesLength)) - { - // Save last datasize. - m_lastDataSize = sizeof(uint32_t); + if (((m_lastPosition - m_currentPosition) >= bytesLength) || resize(bytesLength)) + { + // Save last datasize. + m_lastDataSize = sizeof(uint32_t); #if defined(_WIN32) - serializeArray(string_t, wstrlen); + serializeArray(string_t, wstrlen); #else - m_currentPosition.memcopy(string_t, bytesLength); - m_currentPosition += bytesLength; // size on bytes -#endif // if defined(_WIN32) - } - else - { - setState(state_); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } + m_currentPosition.memcopy(string_t, bytesLength); + m_currentPosition += bytesLength; // size on bytes +#endif // if defined(_WIN32) } else { - serialize(bytesLength); + setState(state_); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } + } + else + { + serialize(bytesLength); + } - return *this; + return *this; } -Cdr& Cdr::serialize( - const char* string_t, - Endianness endianness) +Cdr& Cdr::serialize(const char* string_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - serialize(string_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + serialize(string_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::serialize( - const wchar_t* string_t, - Endianness endianness) +Cdr& Cdr::serialize(const wchar_t* string_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - serialize(string_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + serialize(string_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::serializeArray( - const bool* bool_t, - size_t numElements) +Cdr& Cdr::serializeArray(const bool* bool_t, size_t numElements) { - size_t totalSize = sizeof(*bool_t) * numElements; - - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - // Save last datasize. - m_lastDataSize = sizeof(*bool_t); + size_t totalSize = sizeof(*bool_t) * numElements; - for (size_t count = 0; count < numElements; ++count) - { - uint8_t value = 0; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + // Save last datasize. + m_lastDataSize = sizeof(*bool_t); - if (bool_t[count]) - { - value = 1; - } - m_currentPosition++ << value; - } + for (size_t count = 0; count < numElements; ++count) + { + uint8_t value = 0; - return *this; + if (bool_t[count]) + { + value = 1; + } + m_currentPosition++ << value; } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const char* char_t, - size_t numElements) +Cdr& Cdr::serializeArray(const char* char_t, size_t numElements) { - size_t totalSize = sizeof(*char_t) * numElements; + size_t totalSize = sizeof(*char_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - // Save last datasize. - m_lastDataSize = sizeof(*char_t); + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + // Save last datasize. + m_lastDataSize = sizeof(*char_t); - m_currentPosition.memcopy(char_t, totalSize); - m_currentPosition += totalSize; - return *this; - } + m_currentPosition.memcopy(char_t, totalSize); + m_currentPosition += totalSize; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const int16_t* short_t, - size_t numElements) +Cdr& Cdr::serializeArray(const int16_t* short_t, size_t numElements) { - if (numElements == 0) - { - return *this; - } - - size_t align = alignment(sizeof(*short_t)); - size_t totalSize = sizeof(*short_t) * numElements; - size_t sizeAligned = totalSize + align; - - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(*short_t); - - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&short_t); - const char* end = dst + totalSize; + size_t align = alignment(sizeof(*short_t)); + size_t totalSize = sizeof(*short_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*short_t)) - { - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - m_currentPosition.memcopy(short_t, totalSize); - m_currentPosition += totalSize; - } + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(*short_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::serializeArray( - const int16_t* short_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - serializeArray(short_t, numElements); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&short_t); + const char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*short_t)) + { + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.memcopy(short_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const int32_t* long_t, - size_t numElements) +Cdr& Cdr::serializeArray(const int16_t* short_t, size_t numElements, + Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*long_t)); - size_t totalSize = sizeof(*long_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + serializeArray(short_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(*long_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::serializeArray(const int32_t* long_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&long_t); - const char* end = dst + totalSize; + size_t align = alignment(sizeof(*long_t)); + size_t totalSize = sizeof(*long_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*long_t)) - { - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - m_currentPosition.memcopy(long_t, totalSize); - m_currentPosition += totalSize; - } + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(*long_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::serializeArray( - const int32_t* long_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - serializeArray(long_t, numElements); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&long_t); + const char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*long_t)) + { + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.memcopy(long_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const wchar_t* wchar, - size_t numElements) +Cdr& Cdr::serializeArray(const int32_t* long_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - for (size_t count = 0; count < numElements; ++count) - { - serialize(wchar[count]); - } - return *this; + try + { + serializeArray(long_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; } -Cdr& Cdr::serializeArray( - const wchar_t* wchar, - size_t numElements, - Endianness endianness) +Cdr& Cdr::serializeArray(const wchar_t* wchar, size_t numElements) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - serializeArray(wchar, numElements); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - + if (numElements == 0) + { return *this; + } + + for (size_t count = 0; count < numElements; ++count) + { + serialize(wchar[count]); + } + return *this; } -Cdr& Cdr::serializeArray( - const int64_t* longlong_t, - size_t numElements) +Cdr& Cdr::serializeArray(const wchar_t* wchar, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*longlong_t)); - size_t totalSize = sizeof(*longlong_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + serializeArray(wchar, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(*longlong_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::serializeArray(const int64_t* longlong_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&longlong_t); - const char* end = dst + totalSize; + size_t align = alignment(sizeof(*longlong_t)); + size_t totalSize = sizeof(*longlong_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*longlong_t)) - { - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - m_currentPosition.memcopy(longlong_t, totalSize); - m_currentPosition += totalSize; - } + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(*longlong_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::serializeArray( - const int64_t* longlong_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - serializeArray(longlong_t, numElements); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&longlong_t); + const char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*longlong_t)) + { + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.memcopy(longlong_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const float* float_t, - size_t numElements) +Cdr& Cdr::serializeArray(const int64_t* longlong_t, size_t numElements, + Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*float_t)); - size_t totalSize = sizeof(*float_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + serializeArray(longlong_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(*float_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::serializeArray(const float* float_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&float_t); - const char* end = dst + totalSize; + size_t align = alignment(sizeof(*float_t)); + size_t totalSize = sizeof(*float_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*float_t)) - { - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - m_currentPosition.memcopy(float_t, totalSize); - m_currentPosition += totalSize; - } + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(*float_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::serializeArray( - const float* float_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - serializeArray(float_t, numElements); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&float_t); + const char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*float_t)) + { + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.memcopy(float_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const double* double_t, - size_t numElements) +Cdr& Cdr::serializeArray(const float* float_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*double_t)); - size_t totalSize = sizeof(*double_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + serializeArray(float_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = sizeof(*double_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::serializeArray(const double* double_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&double_t); - const char* end = dst + totalSize; + size_t align = alignment(sizeof(*double_t)); + size_t totalSize = sizeof(*double_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*double_t)) - { - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - m_currentPosition.memcopy(double_t, totalSize); - m_currentPosition += totalSize; - } + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = sizeof(*double_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::serializeArray( - const double* double_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - serializeArray(double_t, numElements); - m_swapBytes = auxSwap; + const char* dst = reinterpret_cast(&double_t); + const char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*double_t)) + { + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.memcopy(double_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const long double* ldouble_t, - size_t numElements) +Cdr& Cdr::serializeArray(const double* double_t, size_t numElements, + Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(ALIGNMENT_LONG_DOUBLE); - // Fix for Windows ( long doubles only store 8 bytes ) - size_t totalSize = 16 * numElements; // sizeof(*ldouble_t) - size_t sizeAligned = totalSize + align; + try + { + serializeArray(double_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) - { - // Save last datasize. - m_lastDataSize = 16; + return *this; +} + +Cdr& Cdr::serializeArray(const long double* ldouble_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } + size_t align = alignment(ALIGNMENT_LONG_DOUBLE); + // Fix for Windows ( long doubles only store 8 bytes ) + size_t totalSize = 16 * numElements; // sizeof(*ldouble_t) + size_t sizeAligned = totalSize + align; + + if (((m_lastPosition - m_currentPosition) >= sizeAligned) || resize(sizeAligned)) + { + // Save last datasize. + m_lastDataSize = 16; + + // Align if there are any elements + if (numElements) + { + makeAlign(align); + } #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - if (m_swapBytes) - { - for (size_t i = 0; i < numElements; ++i, ++ldouble_t) - { - __float128 tmp = *ldouble_t; - const char* dst = reinterpret_cast(&tmp); - m_currentPosition++ << dst[15]; - m_currentPosition++ << dst[14]; - m_currentPosition++ << dst[13]; - m_currentPosition++ << dst[12]; - m_currentPosition++ << dst[11]; - m_currentPosition++ << dst[10]; - m_currentPosition++ << dst[9]; - m_currentPosition++ << dst[8]; - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { - for (size_t i = 0; i < numElements; ++i, ++ldouble_t) - { - __float128 tmp = *ldouble_t; - m_currentPosition << tmp; - m_currentPosition += 16; - } - } + if (m_swapBytes) + { + for (size_t i = 0; i < numElements; ++i, ++ldouble_t) + { + __float128 tmp = *ldouble_t; + const char* dst = reinterpret_cast(&tmp); + m_currentPosition++ << dst[15]; + m_currentPosition++ << dst[14]; + m_currentPosition++ << dst[13]; + m_currentPosition++ << dst[12]; + m_currentPosition++ << dst[11]; + m_currentPosition++ << dst[10]; + m_currentPosition++ << dst[9]; + m_currentPosition++ << dst[8]; + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } + } + else + { + for (size_t i = 0; i < numElements; ++i, ++ldouble_t) + { + __float128 tmp = *ldouble_t; + m_currentPosition << tmp; + m_currentPosition += 16; + } + } #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - if (m_swapBytes) - { - const char* dst = reinterpret_cast(&ldouble_t); - const char* end = dst + totalSize; + if (m_swapBytes) + { + const char* dst = reinterpret_cast(&ldouble_t); + const char* end = dst + totalSize; - for (; dst < end; dst += sizeof(*ldouble_t)) - { + for (; dst < end; dst += sizeof(*ldouble_t)) + { #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ << dst[15]; - m_currentPosition++ << dst[14]; - m_currentPosition++ << dst[13]; - m_currentPosition++ << dst[12]; - m_currentPosition++ << dst[11]; - m_currentPosition++ << dst[10]; - m_currentPosition++ << dst[9]; - m_currentPosition++ << dst[8]; + m_currentPosition++ << dst[15]; + m_currentPosition++ << dst[14]; + m_currentPosition++ << dst[13]; + m_currentPosition++ << dst[12]; + m_currentPosition++ << dst[11]; + m_currentPosition++ << dst[10]; + m_currentPosition++ << dst[9]; + m_currentPosition++ << dst[8]; #else - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); - m_currentPosition++ << static_cast(0); -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ << dst[7]; - m_currentPosition++ << dst[6]; - m_currentPosition++ << dst[5]; - m_currentPosition++ << dst[4]; - m_currentPosition++ << dst[3]; - m_currentPosition++ << dst[2]; - m_currentPosition++ << dst[1]; - m_currentPosition++ << dst[0]; - } - } - else - { + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); + m_currentPosition++ << static_cast(0); +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 + m_currentPosition++ << dst[7]; + m_currentPosition++ << dst[6]; + m_currentPosition++ << dst[5]; + m_currentPosition++ << dst[4]; + m_currentPosition++ << dst[3]; + m_currentPosition++ << dst[2]; + m_currentPosition++ << dst[1]; + m_currentPosition++ << dst[0]; + } + } + else + { #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition.memcopy(ldouble_t, totalSize); - m_currentPosition += totalSize; + m_currentPosition.memcopy(ldouble_t, totalSize); + m_currentPosition += totalSize; #else - for (size_t i = 0; i < numElements; ++i) - { - m_currentPosition << static_cast(0); - m_currentPosition += 8; - m_currentPosition << ldouble_t[i]; - m_currentPosition += 8; - } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 - } + for (size_t i = 0; i < numElements; ++i) + { + m_currentPosition << static_cast(0); + m_currentPosition += 8; + m_currentPosition << ldouble_t[i]; + m_currentPosition += 8; + } +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 + } #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::serializeArray( - const long double* ldouble_t, - size_t numElements, - Endianness endianness) +Cdr& Cdr::serializeArray(const long double* ldouble_t, size_t numElements, + Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - serializeArray(ldouble_t, numElements); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + serializeArray(ldouble_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::deserialize( - char& char_t) +Cdr& Cdr::deserialize(char& char_t) { - if ((m_lastPosition - m_currentPosition) >= sizeof(char_t)) - { - // Save last datasize. - m_lastDataSize = sizeof(char_t); + if ((m_lastPosition - m_currentPosition) >= sizeof(char_t)) + { + // Save last datasize. + m_lastDataSize = sizeof(char_t); - m_currentPosition++ >> char_t; - return *this; - } + m_currentPosition++ >> char_t; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - int16_t& short_t) +Cdr& Cdr::deserialize(int16_t& short_t) { - size_t align = alignment(sizeof(short_t)); - size_t sizeAligned = sizeof(short_t) + align; - - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(short_t); + size_t align = alignment(sizeof(short_t)); + size_t sizeAligned = sizeof(short_t) + align; - // Align - makeAlign(align); + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(short_t); - if (m_swapBytes) - { - char* dst = reinterpret_cast(&short_t); + // Align + makeAlign(align); - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - else - { - m_currentPosition >> short_t; - m_currentPosition += sizeof(short_t); - } - - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserialize( - int16_t& short_t, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserialize(short_t); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(&short_t); + + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition >> short_t; + m_currentPosition += sizeof(short_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - int32_t& long_t) +Cdr& Cdr::deserialize(int16_t& short_t, Endianness endianness) { - size_t align = alignment(sizeof(long_t)); - size_t sizeAligned = sizeof(long_t) + align; - - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(long_t); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - // Align - makeAlign(align); + try + { + deserialize(short_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(&long_t); - - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - else - { - m_currentPosition >> long_t; - m_currentPosition += sizeof(long_t); - } - - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::deserialize( - int32_t& long_t, - Endianness endianness) +Cdr& Cdr::deserialize(int32_t& long_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(long_t)); + size_t sizeAligned = sizeof(long_t) + align; + + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(long_t); - try + // Align + makeAlign(align); + + if (m_swapBytes) { - deserialize(long_t); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(&long_t); + + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition >> long_t; + m_currentPosition += sizeof(long_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - int64_t& longlong_t) +Cdr& Cdr::deserialize(int32_t& long_t, Endianness endianness) { - size_t align = alignment(sizeof(longlong_t)); - size_t sizeAligned = sizeof(longlong_t) + align; + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(longlong_t); - - // Align. - makeAlign(align); - - if (m_swapBytes) - { - char* dst = reinterpret_cast(&longlong_t); - - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - else - { - m_currentPosition >> longlong_t; - m_currentPosition += sizeof(longlong_t); - } + try + { + deserialize(long_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::deserialize( - int64_t& longlong_t, - Endianness endianness) +Cdr& Cdr::deserialize(int64_t& longlong_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(longlong_t)); + size_t sizeAligned = sizeof(longlong_t) + align; + + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(longlong_t); + + // Align. + makeAlign(align); - try + if (m_swapBytes) { - deserialize(longlong_t); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(&longlong_t); + + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition >> longlong_t; + m_currentPosition += sizeof(longlong_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - float& float_t) +Cdr& Cdr::deserialize(int64_t& longlong_t, Endianness endianness) { - size_t align = alignment(sizeof(float_t)); - size_t sizeAligned = sizeof(float_t) + align; - - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(float_t); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - // Align. - makeAlign(align); - - if (m_swapBytes) - { - char* dst = reinterpret_cast(&float_t); - - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - else - { - m_currentPosition >> float_t; - m_currentPosition += sizeof(float_t); - } - - return *this; - } + try + { + deserialize(longlong_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::deserialize( - float& float_t, - Endianness endianness) +Cdr& Cdr::deserialize(float& float_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(float_t)); + size_t sizeAligned = sizeof(float_t) + align; - try + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(float_t); + + // Align. + makeAlign(align); + + if (m_swapBytes) { - deserialize(float_t); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(&float_t); + + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition >> float_t; + m_currentPosition += sizeof(float_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - double& double_t) +Cdr& Cdr::deserialize(float& float_t, Endianness endianness) { - size_t align = alignment(sizeof(double_t)); - size_t sizeAligned = sizeof(double_t) + align; - - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(double_t); - - // Align. - makeAlign(align); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if (m_swapBytes) - { - char* dst = reinterpret_cast(&double_t); + try + { + deserialize(float_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - else - { - m_currentPosition >> double_t; - m_currentPosition += sizeof(double_t); - } - - return *this; - } - - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; } -Cdr& Cdr::deserialize( - double& double_t, - Endianness endianness) +Cdr& Cdr::deserialize(double& double_t) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + size_t align = alignment(sizeof(double_t)); + size_t sizeAligned = sizeof(double_t) + align; + + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(double_t); + + // Align. + makeAlign(align); - try + if (m_swapBytes) { - deserialize(double_t); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(&double_t); + + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition >> double_t; + m_currentPosition += sizeof(double_t); } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - long double& ldouble_t) +Cdr& Cdr::deserialize(double& double_t, Endianness endianness) { - size_t align = alignment(ALIGNMENT_LONG_DOUBLE); - size_t sizeAligned = sizeof(ldouble_t) + align; + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = 16; // sizeof(ldouble_t); + try + { + deserialize(double_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - // Align. - makeAlign(align); + return *this; +} + +Cdr& Cdr::deserialize(long double& ldouble_t) +{ + size_t align = alignment(ALIGNMENT_LONG_DOUBLE); + size_t sizeAligned = sizeof(ldouble_t) + align; + + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = 16; // sizeof(ldouble_t); - if (m_swapBytes) - { + // Align. + makeAlign(align); + + if (m_swapBytes) + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp = ldouble_t; - char* dst = reinterpret_cast(&tmp); + __float128 tmp = ldouble_t; + char* dst = reinterpret_cast(&tmp); #else - char* dst = reinterpret_cast(&ldouble_t); -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + char* dst = reinterpret_cast(&ldouble_t); +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 #if FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ >> dst[15]; - m_currentPosition++ >> dst[14]; - m_currentPosition++ >> dst[13]; - m_currentPosition++ >> dst[12]; - m_currentPosition++ >> dst[11]; - m_currentPosition++ >> dst[10]; - m_currentPosition++ >> dst[9]; - m_currentPosition++ >> dst[8]; - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; + m_currentPosition++ >> dst[15]; + m_currentPosition++ >> dst[14]; + m_currentPosition++ >> dst[13]; + m_currentPosition++ >> dst[12]; + m_currentPosition++ >> dst[11]; + m_currentPosition++ >> dst[10]; + m_currentPosition++ >> dst[9]; + m_currentPosition++ >> dst[8]; + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - ldouble_t = static_cast(tmp); -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + ldouble_t = static_cast(tmp); +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - m_currentPosition += 8; - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; + m_currentPosition += 8; + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 -#endif // FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - } - else - { +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 +#endif // FASTCDR_HAVE_FLOAT128 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 + } + else + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - __float128 tmp; - m_currentPosition >> tmp; - m_currentPosition += 16; - ldouble_t = static_cast(tmp); + __float128 tmp; + m_currentPosition >> tmp; + m_currentPosition += 16; + ldouble_t = static_cast(tmp); #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - m_currentPosition += 8; -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 - m_currentPosition >> ldouble_t; - m_currentPosition += sizeof(ldouble_t); -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - } - - return *this; + m_currentPosition += 8; +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 + m_currentPosition >> ldouble_t; + m_currentPosition += sizeof(ldouble_t); +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - long double& ldouble_t, - Endianness endianness) +Cdr& Cdr::deserialize(long double& ldouble_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - deserialize(ldouble_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + deserialize(ldouble_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::deserialize( - bool& bool_t) +Cdr& Cdr::deserialize(bool& bool_t) { - uint8_t value = 0; + uint8_t value = 0; - if ((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) - { - // Save last datasize. - m_lastDataSize = sizeof(uint8_t); - - m_currentPosition++ >> value; + if ((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) + { + // Save last datasize. + m_lastDataSize = sizeof(uint8_t); - if (value == 1) - { - bool_t = true; - return *this; - } - else if (value == 0) - { - bool_t = false; - return *this; - } + m_currentPosition++ >> value; - throw BadParamException("Unexpected byte value in Cdr::deserialize(bool), expected 0 or 1"); + if (value == 1) + { + bool_t = true; + return *this; + } + else if (value == 0) + { + bool_t = false; + return *this; } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw BadParamException("Unexpected byte value in Cdr::deserialize(bool), expected 0 " + "or 1"); + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - char*& string_t) +Cdr& Cdr::deserialize(char*& string_t) { - uint32_t length = 0; - Cdr::state state_before_error(*this); - - deserialize(length); + uint32_t length = 0; + Cdr::state state_before_error(*this); - if (length == 0) - { - string_t = NULL; - return *this; - } - else if ((m_lastPosition - m_currentPosition) >= length) - { - // Save last datasize. - m_lastDataSize = sizeof(uint8_t); + deserialize(length); - // Allocate memory. - string_t = - reinterpret_cast(calloc(length + ((&m_currentPosition)[length - 1] == '\0' ? 0 : 1), - sizeof(char))); - memcpy(string_t, &m_currentPosition, length); - m_currentPosition += length; - return *this; - } + if (length == 0) + { + string_t = NULL; + return *this; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + // Save last datasize. + m_lastDataSize = sizeof(uint8_t); + + // Allocate memory. + string_t = reinterpret_cast(calloc( + length + ((&m_currentPosition)[length - 1] == '\0' ? 0 : 1), sizeof(char))); + memcpy(string_t, &m_currentPosition, length); + m_currentPosition += length; + return *this; + } - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - wchar_t*& string_t) +Cdr& Cdr::deserialize(wchar_t*& string_t) { - uint32_t length = 0; - Cdr::state state_before_error(*this); + uint32_t length = 0; + Cdr::state state_before_error(*this); - deserialize(length); + deserialize(length); - if (length == 0) - { - string_t = NULL; - return *this; - } - else if ((m_lastPosition - m_currentPosition) >= length) - { - // Save last datasize. - m_lastDataSize = 4; - // Allocate memory. - string_t = reinterpret_cast(calloc(length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero + if (length == 0) + { + string_t = NULL; + return *this; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + // Save last datasize. + m_lastDataSize = 4; + // Allocate memory. + string_t = reinterpret_cast(calloc( + length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero #if defined(_WIN32) - for (size_t idx = 0; idx < length; ++idx) - { - uint32_t temp; - m_currentPosition >> temp; - string_t[idx] = static_cast(temp); - m_currentPosition += 4; - } -#else - memcpy(string_t, &m_currentPosition, length * sizeof(wchar_t)); - m_currentPosition += length * sizeof(wchar_t); -#endif // if defined(_WIN32) - return *this; + for (size_t idx = 0; idx < length; ++idx) + { + uint32_t temp; + m_currentPosition >> temp; + string_t[idx] = static_cast(temp); + m_currentPosition += 4; } +#else + memcpy(string_t, &m_currentPosition, length * sizeof(wchar_t)); + m_currentPosition += length * sizeof(wchar_t); +#endif // if defined(_WIN32) + return *this; + } - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserialize( - char*& string_t, - Endianness endianness) +Cdr& Cdr::deserialize(char*& string_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - deserialize(string_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + deserialize(string_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::deserialize( - wchar_t*& string_t, - Endianness endianness) +Cdr& Cdr::deserialize(wchar_t*& string_t, Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - deserialize(string_t); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + deserialize(string_t); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -const char* Cdr::readString( - uint32_t& length) +const char* Cdr::readString(uint32_t& length) { - const char* returnedValue = ""; - state state_before_error(*this); + const char* returnedValue = ""; + state state_before_error(*this); - *this >> length; + *this >> length; - if (length == 0) - { - return returnedValue; - } - else if ((m_lastPosition - m_currentPosition) >= length) - { - // Save last datasize. - m_lastDataSize = sizeof(uint8_t); + if (length == 0) + { + return returnedValue; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + // Save last datasize. + m_lastDataSize = sizeof(uint8_t); - returnedValue = &m_currentPosition; - m_currentPosition += length; - if (returnedValue[length - 1] == '\0') - { - --length; - } - return returnedValue; + returnedValue = &m_currentPosition; + m_currentPosition += length; + if (returnedValue[length - 1] == '\0') + { + --length; } + return returnedValue; + } - setState(state_before_error); - throw eprosima::fastcdr::exception::NotEnoughMemoryException( - eprosima::fastcdr::exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw eprosima::fastcdr::exception::NotEnoughMemoryException( + eprosima::fastcdr::exception::NotEnoughMemoryException:: + NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -const std::wstring Cdr::readWString( - uint32_t& length) +const std::wstring Cdr::readWString(uint32_t& length) { - std::wstring returnedValue = L""; - state state_(*this); + std::wstring returnedValue = L""; + state state_(*this); - *this >> length; - uint32_t bytesLength = length * 4; + *this >> length; + uint32_t bytesLength = length * 4; - if (bytesLength == 0) - { - return returnedValue; - } - else if ((m_lastPosition - m_currentPosition) >= bytesLength) - { - // Save last datasize. - m_lastDataSize = sizeof(uint32_t); + if (bytesLength == 0) + { + return returnedValue; + } + else if ((m_lastPosition - m_currentPosition) >= bytesLength) + { + // Save last datasize. + m_lastDataSize = sizeof(uint32_t); - returnedValue.resize(length); - deserializeArray(const_cast(returnedValue.c_str()), length); - if (returnedValue[length - 1] == L'\0') - { - --length; - returnedValue.erase(length); - } - return returnedValue; + returnedValue.resize(length); + deserializeArray(const_cast(returnedValue.c_str()), length); + if (returnedValue[length - 1] == L'\0') + { + --length; + returnedValue.erase(length); } + return returnedValue; + } - setState(state_); - throw eprosima::fastcdr::exception::NotEnoughMemoryException( - eprosima::fastcdr::exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_); + throw eprosima::fastcdr::exception::NotEnoughMemoryException( + eprosima::fastcdr::exception::NotEnoughMemoryException:: + NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - bool* bool_t, - size_t numElements) +Cdr& Cdr::deserializeArray(bool* bool_t, size_t numElements) { - size_t totalSize = sizeof(*bool_t) * numElements; - - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - // Save last datasize. - m_lastDataSize = sizeof(*bool_t); + size_t totalSize = sizeof(*bool_t) * numElements; - for (size_t count = 0; count < numElements; ++count) - { - uint8_t value = 0; - m_currentPosition++ >> value; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + // Save last datasize. + m_lastDataSize = sizeof(*bool_t); - if (value == 1) - { - bool_t[count] = true; - } - else if (value == 0) - { - bool_t[count] = false; - } - } + for (size_t count = 0; count < numElements; ++count) + { + uint8_t value = 0; + m_currentPosition++ >> value; - return *this; + if (value == 1) + { + bool_t[count] = true; + } + else if (value == 0) + { + bool_t[count] = false; + } } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - char* char_t, - size_t numElements) +Cdr& Cdr::deserializeArray(char* char_t, size_t numElements) { - size_t totalSize = sizeof(*char_t) * numElements; + size_t totalSize = sizeof(*char_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - // Save last datasize. - m_lastDataSize = sizeof(*char_t); + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + // Save last datasize. + m_lastDataSize = sizeof(*char_t); - m_currentPosition.rmemcopy(char_t, totalSize); - m_currentPosition += totalSize; - return *this; - } + m_currentPosition.rmemcopy(char_t, totalSize); + m_currentPosition += totalSize; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - int16_t* short_t, - size_t numElements) +Cdr& Cdr::deserializeArray(int16_t* short_t, size_t numElements) { - if (numElements == 0) - { - return *this; - } - - size_t align = alignment(sizeof(*short_t)); - size_t totalSize = sizeof(*short_t) * numElements; - size_t sizeAligned = totalSize + align; - - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(*short_t); - - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(short_t); - char* end = dst + totalSize; + size_t align = alignment(sizeof(*short_t)); + size_t totalSize = sizeof(*short_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*short_t)) - { - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { - m_currentPosition.rmemcopy(short_t, totalSize); - m_currentPosition += totalSize; - } + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(*short_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserializeArray( - int16_t* short_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserializeArray(short_t, numElements); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(short_t); + char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*short_t)) + { + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.rmemcopy(short_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - int32_t* long_t, - size_t numElements) +Cdr& Cdr::deserializeArray(int16_t* short_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*long_t)); - size_t totalSize = sizeof(*long_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + deserializeArray(short_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(*long_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::deserializeArray(int32_t* long_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(long_t); - char* end = dst + totalSize; + size_t align = alignment(sizeof(*long_t)); + size_t totalSize = sizeof(*long_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*long_t)) - { - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { - m_currentPosition.rmemcopy(long_t, totalSize); - m_currentPosition += totalSize; - } + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(*long_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserializeArray( - int32_t* long_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserializeArray(long_t, numElements); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(long_t); + char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*long_t)) + { + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.rmemcopy(long_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - wchar_t* wchar, - size_t numElements) +Cdr& Cdr::deserializeArray(int32_t* long_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - uint32_t value; - for (size_t count = 0; count < numElements; ++count) - { - deserialize(value); - wchar[count] = static_cast(value); - } - return *this; + try + { + deserializeArray(long_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } + + return *this; } -Cdr& Cdr::deserializeArray( - wchar_t* wchar, - size_t numElements, - Endianness endianness) +Cdr& Cdr::deserializeArray(wchar_t* wchar, size_t numElements) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try - { - deserializeArray(wchar, numElements); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } - + if (numElements == 0) + { return *this; + } + + uint32_t value; + for (size_t count = 0; count < numElements; ++count) + { + deserialize(value); + wchar[count] = static_cast(value); + } + return *this; } -Cdr& Cdr::deserializeArray( - int64_t* longlong_t, - size_t numElements) +Cdr& Cdr::deserializeArray(wchar_t* wchar, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*longlong_t)); - size_t totalSize = sizeof(*longlong_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + deserializeArray(wchar, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(*longlong_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::deserializeArray(int64_t* longlong_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(longlong_t); - char* end = dst + totalSize; + size_t align = alignment(sizeof(*longlong_t)); + size_t totalSize = sizeof(*longlong_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*longlong_t)) - { - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { - m_currentPosition.rmemcopy(longlong_t, totalSize); - m_currentPosition += totalSize; - } + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(*longlong_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserializeArray( - int64_t* longlong_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserializeArray(longlong_t, numElements); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(longlong_t); + char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*longlong_t)) + { + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.rmemcopy(longlong_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - float* float_t, - size_t numElements) +Cdr& Cdr::deserializeArray(int64_t* longlong_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*float_t)); - size_t totalSize = sizeof(*float_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + deserializeArray(longlong_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(*float_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::deserializeArray(float* float_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(float_t); - char* end = dst + totalSize; + size_t align = alignment(sizeof(*float_t)); + size_t totalSize = sizeof(*float_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*float_t)) - { - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { - m_currentPosition.rmemcopy(float_t, totalSize); - m_currentPosition += totalSize; - } + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(*float_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserializeArray( - float* float_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserializeArray(float_t, numElements); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(float_t); + char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*float_t)) + { + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.rmemcopy(float_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - double* double_t, - size_t numElements) +Cdr& Cdr::deserializeArray(float* float_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(sizeof(*double_t)); - size_t totalSize = sizeof(*double_t) * numElements; - size_t sizeAligned = totalSize + align; + try + { + deserializeArray(float_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = sizeof(*double_t); + return *this; +} - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } +Cdr& Cdr::deserializeArray(double* double_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - if (m_swapBytes) - { - char* dst = reinterpret_cast(double_t); - char* end = dst + totalSize; + size_t align = alignment(sizeof(*double_t)); + size_t totalSize = sizeof(*double_t) * numElements; + size_t sizeAligned = totalSize + align; - for (; dst < end; dst += sizeof(*double_t)) - { - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { - m_currentPosition.rmemcopy(double_t, totalSize); - m_currentPosition += totalSize; - } + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = sizeof(*double_t); - return *this; + // Align if there are any elements + if (numElements) + { + makeAlign(align); } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); -} - -Cdr& Cdr::deserializeArray( - double* double_t, - size_t numElements, - Endianness endianness) -{ - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); - - try + if (m_swapBytes) { - deserializeArray(double_t, numElements); - m_swapBytes = auxSwap; + char* dst = reinterpret_cast(double_t); + char* end = dst + totalSize; + + for (; dst < end; dst += sizeof(*double_t)) + { + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } } - catch (Exception& ex) + else { - m_swapBytes = auxSwap; - ex.raise(); + m_currentPosition.rmemcopy(double_t, totalSize); + m_currentPosition += totalSize; } return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - long double* ldouble_t, - size_t numElements) +Cdr& Cdr::deserializeArray(double* double_t, size_t numElements, Endianness endianness) { - if (numElements == 0) - { - return *this; - } + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - size_t align = alignment(ALIGNMENT_LONG_DOUBLE); - // Fix for Windows ( long doubles only store 8 bytes ) - size_t totalSize = 16 * numElements; - size_t sizeAligned = totalSize + align; + try + { + deserializeArray(double_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - if ((m_lastPosition - m_currentPosition) >= sizeAligned) - { - // Save last datasize. - m_lastDataSize = 16; + return *this; +} + +Cdr& Cdr::deserializeArray(long double* ldouble_t, size_t numElements) +{ + if (numElements == 0) + { + return *this; + } - // Align if there are any elements - if (numElements) - { - makeAlign(align); - } + size_t align = alignment(ALIGNMENT_LONG_DOUBLE); + // Fix for Windows ( long doubles only store 8 bytes ) + size_t totalSize = 16 * numElements; + size_t sizeAligned = totalSize + align; + + if ((m_lastPosition - m_currentPosition) >= sizeAligned) + { + // Save last datasize. + m_lastDataSize = 16; + + // Align if there are any elements + if (numElements) + { + makeAlign(align); + } #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - if (m_swapBytes) - { - for (size_t i = 0; i < numElements; ++i) - { - __float128 tmp; - char* dst = reinterpret_cast(&tmp); - m_currentPosition++ >> dst[15]; - m_currentPosition++ >> dst[14]; - m_currentPosition++ >> dst[13]; - m_currentPosition++ >> dst[12]; - m_currentPosition++ >> dst[11]; - m_currentPosition++ >> dst[10]; - m_currentPosition++ >> dst[9]; - m_currentPosition++ >> dst[8]; - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - ldouble_t[i] = static_cast(tmp); - } - } - else - { - for (size_t i = 0; i < numElements; ++i) - { - __float128 tmp; - m_currentPosition >> tmp; - m_currentPosition += 16; - ldouble_t[i] = static_cast(tmp); - } - } + if (m_swapBytes) + { + for (size_t i = 0; i < numElements; ++i) + { + __float128 tmp; + char* dst = reinterpret_cast(&tmp); + m_currentPosition++ >> dst[15]; + m_currentPosition++ >> dst[14]; + m_currentPosition++ >> dst[13]; + m_currentPosition++ >> dst[12]; + m_currentPosition++ >> dst[11]; + m_currentPosition++ >> dst[10]; + m_currentPosition++ >> dst[9]; + m_currentPosition++ >> dst[8]; + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + ldouble_t[i] = static_cast(tmp); + } + } + else + { + for (size_t i = 0; i < numElements; ++i) + { + __float128 tmp; + m_currentPosition >> tmp; + m_currentPosition += 16; + ldouble_t[i] = static_cast(tmp); + } + } #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 - if (m_swapBytes) - { - char* dst = reinterpret_cast(ldouble_t); - char* end = dst + numElements * sizeof(*ldouble_t); + if (m_swapBytes) + { + char* dst = reinterpret_cast(ldouble_t); + char* end = dst + numElements * sizeof(*ldouble_t); - for (; dst < end; dst += sizeof(*ldouble_t)) - { + for (; dst < end; dst += sizeof(*ldouble_t)) + { #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ >> dst[15]; - m_currentPosition++ >> dst[14]; - m_currentPosition++ >> dst[13]; - m_currentPosition++ >> dst[12]; - m_currentPosition++ >> dst[11]; - m_currentPosition++ >> dst[10]; - m_currentPosition++ >> dst[9]; - m_currentPosition++ >> dst[8]; + m_currentPosition++ >> dst[15]; + m_currentPosition++ >> dst[14]; + m_currentPosition++ >> dst[13]; + m_currentPosition++ >> dst[12]; + m_currentPosition++ >> dst[11]; + m_currentPosition++ >> dst[10]; + m_currentPosition++ >> dst[9]; + m_currentPosition++ >> dst[8]; #else - m_currentPosition += 8; -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition++ >> dst[7]; - m_currentPosition++ >> dst[6]; - m_currentPosition++ >> dst[5]; - m_currentPosition++ >> dst[4]; - m_currentPosition++ >> dst[3]; - m_currentPosition++ >> dst[2]; - m_currentPosition++ >> dst[1]; - m_currentPosition++ >> dst[0]; - } - } - else - { + m_currentPosition += 8; +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 + m_currentPosition++ >> dst[7]; + m_currentPosition++ >> dst[6]; + m_currentPosition++ >> dst[5]; + m_currentPosition++ >> dst[4]; + m_currentPosition++ >> dst[3]; + m_currentPosition++ >> dst[2]; + m_currentPosition++ >> dst[1]; + m_currentPosition++ >> dst[0]; + } + } + else + { #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition.rmemcopy(ldouble_t, totalSize); - m_currentPosition += totalSize; + m_currentPosition.rmemcopy(ldouble_t, totalSize); + m_currentPosition += totalSize; #else - for (size_t i = 0; i < numElements; ++i) - { - m_currentPosition += 8; // ignore first 8 bytes - m_currentPosition >> ldouble_t[i]; - m_currentPosition += 8; - } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 - } -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - - return *this; + for (size_t i = 0; i < numElements; ++i) + { + m_currentPosition += 8; // ignore first 8 bytes + m_currentPosition >> ldouble_t[i]; + m_currentPosition += 8; + } +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 } +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 || FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 + + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -Cdr& Cdr::deserializeArray( - long double* ldouble_t, - size_t numElements, - Endianness endianness) +Cdr& Cdr::deserializeArray(long double* ldouble_t, size_t numElements, + Endianness endianness) { - bool auxSwap = m_swapBytes; - m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || (!m_swapBytes && (m_endianness != endianness)); + bool auxSwap = m_swapBytes; + m_swapBytes = (m_swapBytes && (m_endianness == endianness)) || + (!m_swapBytes && (m_endianness != endianness)); - try - { - deserializeArray(ldouble_t, numElements); - m_swapBytes = auxSwap; - } - catch (Exception& ex) - { - m_swapBytes = auxSwap; - ex.raise(); - } + try + { + deserializeArray(ldouble_t, numElements); + m_swapBytes = auxSwap; + } + catch (Exception& ex) + { + m_swapBytes = auxSwap; + ex.raise(); + } - return *this; + return *this; } -Cdr& Cdr::serializeBoolSequence( - const std::vector& vector_t) +Cdr& Cdr::serializeBoolSequence(const std::vector& vector_t) { - state state_before_error(*this); + state state_before_error(*this); - *this << static_cast(vector_t.size()); + *this << static_cast(vector_t.size()); - size_t totalSize = vector_t.size() * sizeof(bool); + size_t totalSize = vector_t.size() * sizeof(bool); - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - // Save last datasize. - m_lastDataSize = sizeof(bool); + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + // Save last datasize. + m_lastDataSize = sizeof(bool); - for (size_t count = 0; count < vector_t.size(); ++count) - { - uint8_t value = 0; - std::vector::const_reference ref = vector_t[count]; - - if (ref) - { - value = 1; - } - m_currentPosition++ << value; - } - } - else + for (size_t count = 0; count < vector_t.size(); ++count) { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + uint8_t value = 0; + std::vector::const_reference ref = vector_t[count]; + + if (ref) + { + value = 1; + } + m_currentPosition++ << value; } + } + else + { + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } - return *this; + return *this; } -Cdr& Cdr::deserializeBoolSequence( - std::vector& vector_t) +Cdr& Cdr::deserializeBoolSequence(std::vector& vector_t) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - *this >> seqLength; + *this >> seqLength; - size_t totalSize = seqLength * sizeof(bool); - - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - vector_t.resize(seqLength); - // Save last datasize. - m_lastDataSize = sizeof(bool); + size_t totalSize = seqLength * sizeof(bool); - for (uint32_t count = 0; count < seqLength; ++count) - { - uint8_t value = 0; - m_currentPosition++ >> value; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + vector_t.resize(seqLength); + // Save last datasize. + m_lastDataSize = sizeof(bool); - if (value == 1) - { - vector_t[count] = true; - } - else if (value == 0) - { - vector_t[count] = false; - } - else - { - throw BadParamException("Unexpected byte value in Cdr::deserializeBoolSequence, expected 0 or 1"); - } - } - } - else + for (uint32_t count = 0; count < seqLength; ++count) { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + uint8_t value = 0; + m_currentPosition++ >> value; + + if (value == 1) + { + vector_t[count] = true; + } + else if (value == 0) + { + vector_t[count] = false; + } + else + { + throw BadParamException("Unexpected byte value in Cdr::deserializeBoolSequence, " + "expected 0 or 1"); + } } + } + else + { + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } - return *this; + return *this; } -Cdr& Cdr::deserializeStringSequence( - std::string*& sequence_t, - size_t& numElements) +Cdr& Cdr::deserializeStringSequence(std::string*& sequence_t, size_t& numElements) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - deserialize(seqLength); + deserialize(seqLength); - try - { - sequence_t = new std::string[seqLength]; - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - delete [] sequence_t; - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } + try + { + sequence_t = new std::string[seqLength]; + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + delete[] sequence_t; + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } - numElements = seqLength; - return *this; + numElements = seqLength; + return *this; } -Cdr& Cdr::deserializeWStringSequence( - std::wstring*& sequence_t, - size_t& numElements) +Cdr& Cdr::deserializeWStringSequence(std::wstring*& sequence_t, size_t& numElements) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - deserialize(seqLength); + deserialize(seqLength); - try - { - sequence_t = new std::wstring[seqLength]; - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - delete [] sequence_t; - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } + try + { + sequence_t = new std::wstring[seqLength]; + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + delete[] sequence_t; + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } - numElements = seqLength; - return *this; + numElements = seqLength; + return *this; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastBuffer.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastBuffer.cpp index d1301fb88..8a158d786 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastBuffer.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastBuffer.cpp @@ -18,86 +18,77 @@ #include #else #include -#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ +#endif // if !__APPLE__ && !__FreeBSD__ && !__VXWORKS__ #define BUFFER_START_LENGTH 200 using namespace eprosima::fastcdr; -FastBuffer::FastBuffer() - : m_buffer(nullptr) - , m_bufferSize(0) - , m_internalBuffer(true) +FastBuffer::FastBuffer() : m_buffer(nullptr), m_bufferSize(0), m_internalBuffer(true) { } -FastBuffer::FastBuffer( - char* const buffer, - const size_t bufferSize) - : m_buffer(buffer) - , m_bufferSize(bufferSize) - , m_internalBuffer(false) +FastBuffer::FastBuffer(char* const buffer, const size_t bufferSize) + : m_buffer(buffer), m_bufferSize(bufferSize), m_internalBuffer(false) { } FastBuffer::~FastBuffer() { - if (m_internalBuffer && m_buffer != nullptr) - { - free(m_buffer); - } + if (m_internalBuffer && m_buffer != nullptr) + { + free(m_buffer); + } } -bool FastBuffer::reserve( - size_t size) +bool FastBuffer::reserve(size_t size) { - if (m_internalBuffer && m_buffer == NULL) + if (m_internalBuffer && m_buffer == NULL) + { + m_buffer = reinterpret_cast(malloc(size)); + if (m_buffer) { - m_buffer = reinterpret_cast(malloc(size)); - if (m_buffer) - { - m_bufferSize = size; - return true; - } + m_bufferSize = size; + return true; } - return false; + } + return false; } -bool FastBuffer::resize( - size_t minSizeInc) +bool FastBuffer::resize(size_t minSizeInc) { - size_t incBufferSize = BUFFER_START_LENGTH; + size_t incBufferSize = BUFFER_START_LENGTH; + + if (m_internalBuffer) + { + if (minSizeInc > BUFFER_START_LENGTH) + { + incBufferSize = minSizeInc; + } - if (m_internalBuffer) + if (m_buffer == NULL) { - if (minSizeInc > BUFFER_START_LENGTH) - { - incBufferSize = minSizeInc; - } - - if (m_buffer == NULL) - { - m_bufferSize = incBufferSize; - - m_buffer = reinterpret_cast(malloc(m_bufferSize)); - - if (m_buffer != NULL) - { - return true; - } - } - else - { - m_bufferSize += incBufferSize; - - m_buffer = reinterpret_cast(realloc(m_buffer, m_bufferSize)); - - if (m_buffer != NULL) - { - return true; - } - } + m_bufferSize = incBufferSize; + + m_buffer = reinterpret_cast(malloc(m_bufferSize)); + + if (m_buffer != NULL) + { + return true; + } + } + else + { + m_bufferSize += incBufferSize; + + m_buffer = reinterpret_cast(realloc(m_buffer, m_bufferSize)); + + if (m_buffer != NULL) + { + return true; + } } + } - return false; + return false; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastCdr.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastCdr.cpp index 458c8b3ba..f62e4bf54 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastCdr.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/FastCdr.cpp @@ -19,795 +19,767 @@ using namespace eprosima::fastcdr; using namespace ::exception; -FastCdr::state::state( - const FastCdr& fastcdr) - : m_currentPosition(fastcdr.m_currentPosition) +FastCdr::state::state(const FastCdr& fastcdr) + : m_currentPosition(fastcdr.m_currentPosition) { } -FastCdr::state::state( - const state& current_state) - : m_currentPosition(current_state.m_currentPosition) +FastCdr::state::state(const state& current_state) + : m_currentPosition(current_state.m_currentPosition) { } -FastCdr::FastCdr( - FastBuffer& cdrBuffer) - : m_cdrBuffer(cdrBuffer) - , m_currentPosition(cdrBuffer.begin()) - , m_lastPosition(cdrBuffer.end()) +FastCdr::FastCdr(FastBuffer& cdrBuffer) + : m_cdrBuffer(cdrBuffer) + , m_currentPosition(cdrBuffer.begin()) + , m_lastPosition(cdrBuffer.end()) { } -bool FastCdr::jump( - size_t numBytes) +bool FastCdr::jump(size_t numBytes) { - bool returnedValue = false; + bool returnedValue = false; - if (((m_lastPosition - m_currentPosition) >= numBytes) || resize(numBytes)) - { - m_currentPosition += numBytes; - returnedValue = true; - } + if (((m_lastPosition - m_currentPosition) >= numBytes) || resize(numBytes)) + { + m_currentPosition += numBytes; + returnedValue = true; + } - return returnedValue; + return returnedValue; } char* FastCdr::getCurrentPosition() { - return &m_currentPosition; + return &m_currentPosition; } FastCdr::state FastCdr::getState() { - return FastCdr::state(*this); + return FastCdr::state(*this); } -void FastCdr::setState( - FastCdr::state& current_state) +void FastCdr::setState(FastCdr::state& current_state) { - m_currentPosition >> current_state.m_currentPosition; + m_currentPosition >> current_state.m_currentPosition; } void FastCdr::reset() { - m_currentPosition = m_cdrBuffer.begin(); + m_currentPosition = m_cdrBuffer.begin(); } -bool FastCdr::resize( - size_t minSizeInc) +bool FastCdr::resize(size_t minSizeInc) { - if (m_cdrBuffer.resize(minSizeInc)) - { - m_currentPosition << m_cdrBuffer.begin(); - m_lastPosition = m_cdrBuffer.end(); - return true; - } + if (m_cdrBuffer.resize(minSizeInc)) + { + m_currentPosition << m_cdrBuffer.begin(); + m_lastPosition = m_cdrBuffer.end(); + return true; + } - return false; + return false; } -FastCdr& FastCdr::serialize( - const bool bool_t) +FastCdr& FastCdr::serialize(const bool bool_t) { - uint8_t value = 0; + uint8_t value = 0; - if (((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) || resize(sizeof(uint8_t))) + if (((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) || + resize(sizeof(uint8_t))) + { + if (bool_t) { - if (bool_t) - { - value = 1; - } - m_currentPosition++ << value; - - return *this; + value = 1; } + m_currentPosition++ << value; + + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serialize( - const char* string_t) +FastCdr& FastCdr::serialize(const char* string_t) { - uint32_t length = 0; + uint32_t length = 0; - if (string_t != nullptr) - { - length = size_to_uint32(strlen(string_t)) + 1; - } + if (string_t != nullptr) + { + length = size_to_uint32(strlen(string_t)) + 1; + } + + if (length > 0) + { + FastCdr::state state_before_error(*this); + serialize(length); - if (length > 0) + if (((m_lastPosition - m_currentPosition) >= length) || resize(length)) { - FastCdr::state state_before_error(*this); - serialize(length); - - if (((m_lastPosition - m_currentPosition) >= length) || resize(length)) - { - m_currentPosition.memcopy(string_t, length); - m_currentPosition += length; - } - else - { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } + m_currentPosition.memcopy(string_t, length); + m_currentPosition += length; } else { - serialize(length); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } + } + else + { + serialize(length); + } - return *this; + return *this; } -FastCdr& FastCdr::serialize( - const wchar_t* string_t) +FastCdr& FastCdr::serialize(const wchar_t* string_t) { - uint32_t bytesLength = 0; - size_t wstrlen = 0; + uint32_t bytesLength = 0; + size_t wstrlen = 0; - if (string_t != nullptr) - { - wstrlen = wcslen(string_t); - bytesLength = size_to_uint32(wstrlen * 4); - } + if (string_t != nullptr) + { + wstrlen = wcslen(string_t); + bytesLength = size_to_uint32(wstrlen * 4); + } - if (bytesLength > 0) - { - FastCdr::state state_(*this); - serialize(size_to_uint32(wstrlen)); + if (bytesLength > 0) + { + FastCdr::state state_(*this); + serialize(size_to_uint32(wstrlen)); - if (((m_lastPosition - m_currentPosition) >= bytesLength) || resize(bytesLength)) - { + if (((m_lastPosition - m_currentPosition) >= bytesLength) || resize(bytesLength)) + { #if defined(_WIN32) - serializeArray(string_t, wstrlen); + serializeArray(string_t, wstrlen); #else - m_currentPosition.memcopy(string_t, bytesLength); - m_currentPosition += bytesLength; // size on bytes -#endif // if defined(_WIN32) - } - else - { - setState(state_); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); - } + m_currentPosition.memcopy(string_t, bytesLength); + m_currentPosition += bytesLength; // size on bytes +#endif // if defined(_WIN32) } else { - serialize(bytesLength); + setState(state_); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } + } + else + { + serialize(bytesLength); + } - return *this; + return *this; } -FastCdr& FastCdr::serializeArray( - const bool* bool_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const bool* bool_t, size_t numElements) { - size_t totalSize = sizeof(*bool_t) * numElements; + size_t totalSize = sizeof(*bool_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + for (size_t count = 0; count < numElements; ++count) { - for (size_t count = 0; count < numElements; ++count) - { - uint8_t value = 0; - - if (bool_t[count]) - { - value = 1; - } - m_currentPosition++ << value; - } - - return *this; + uint8_t value = 0; + + if (bool_t[count]) + { + value = 1; + } + m_currentPosition++ << value; } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const char* char_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const char* char_t, size_t numElements) { - size_t totalSize = sizeof(*char_t) * numElements; + size_t totalSize = sizeof(*char_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(char_t, totalSize); - m_currentPosition += totalSize; - return *this; - } + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(char_t, totalSize); + m_currentPosition += totalSize; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const int16_t* short_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const int16_t* short_t, size_t numElements) { - size_t totalSize = sizeof(*short_t) * numElements; + size_t totalSize = sizeof(*short_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(short_t, totalSize); - m_currentPosition += totalSize; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(short_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const int32_t* long_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const int32_t* long_t, size_t numElements) { - size_t totalSize = sizeof(*long_t) * numElements; + size_t totalSize = sizeof(*long_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(long_t, totalSize); - m_currentPosition += totalSize; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(long_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const wchar_t* wchar, - size_t numElements) +FastCdr& FastCdr::serializeArray(const wchar_t* wchar, size_t numElements) { - for (size_t count = 0; count < numElements; ++count) - { - serialize(wchar[count]); - } - return *this; + for (size_t count = 0; count < numElements; ++count) + { + serialize(wchar[count]); + } + return *this; } -FastCdr& FastCdr::serializeArray( - const int64_t* longlong_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const int64_t* longlong_t, size_t numElements) { - size_t totalSize = sizeof(*longlong_t) * numElements; + size_t totalSize = sizeof(*longlong_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(longlong_t, totalSize); - m_currentPosition += totalSize; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(longlong_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const float* float_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const float* float_t, size_t numElements) { - size_t totalSize = sizeof(*float_t) * numElements; + size_t totalSize = sizeof(*float_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(float_t, totalSize); - m_currentPosition += totalSize; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(float_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const double* double_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const double* double_t, size_t numElements) { - size_t totalSize = sizeof(*double_t) * numElements; + size_t totalSize = sizeof(*double_t) * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - m_currentPosition.memcopy(double_t, totalSize); - m_currentPosition += totalSize; + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + m_currentPosition.memcopy(double_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeArray( - const long double* ldouble_t, - size_t numElements) +FastCdr& FastCdr::serializeArray(const long double* ldouble_t, size_t numElements) { - size_t totalSize = 16 * numElements; + size_t totalSize = 16 * numElements; - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - for (size_t idx = 0; idx < numElements; ++idx) - { - __float128 tmp = ldouble_t[idx]; - m_currentPosition << tmp; - m_currentPosition += 16; - } + for (size_t idx = 0; idx < numElements; ++idx) + { + __float128 tmp = ldouble_t[idx]; + m_currentPosition << tmp; + m_currentPosition += 16; + } #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition.memcopy(ldouble_t, totalSize); - m_currentPosition += totalSize; + m_currentPosition.memcopy(ldouble_t, totalSize); + m_currentPosition += totalSize; #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - for (size_t idx = 0; idx < numElements; ++idx) - { - m_currentPosition << static_cast(0); - m_currentPosition += 8; - m_currentPosition << ldouble_t[idx]; - m_currentPosition += 8; - } + for (size_t idx = 0; idx < numElements; ++idx) + { + m_currentPosition << static_cast(0); + m_currentPosition += 8; + m_currentPosition << ldouble_t[idx]; + m_currentPosition += 8; + } #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserialize( - bool& bool_t) +FastCdr& FastCdr::deserialize(bool& bool_t) { - uint8_t value = 0; + uint8_t value = 0; - if ((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) + if ((m_lastPosition - m_currentPosition) >= sizeof(uint8_t)) + { + m_currentPosition++ >> value; + + if (value == 1) { - m_currentPosition++ >> value; - - if (value == 1) - { - bool_t = true; - return *this; - } - else if (value == 0) - { - bool_t = false; - return *this; - } - - throw BadParamException("Got unexpected byte value in deserialize for bool (expected 0 or 1)"); + bool_t = true; + return *this; } + else if (value == 0) + { + bool_t = false; + return *this; + } + + throw BadParamException("Got unexpected byte value in deserialize for bool (expected " + "0 or 1)"); + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserialize( - char*& string_t) +FastCdr& FastCdr::deserialize(char*& string_t) { - uint32_t length = 0; - FastCdr::state state_before_error(*this); + uint32_t length = 0; + FastCdr::state state_before_error(*this); - deserialize(length); + deserialize(length); - if (length == 0) - { - string_t = NULL; - return *this; - } - else if ((m_lastPosition - m_currentPosition) >= length) - { - // Allocate memory. - string_t = - reinterpret_cast(calloc(length + ((&m_currentPosition)[length - 1] == '\0' ? 0 : 1), - sizeof(char))); - memcpy(string_t, &m_currentPosition, length); - m_currentPosition += length; - return *this; - } + if (length == 0) + { + string_t = NULL; + return *this; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + // Allocate memory. + string_t = reinterpret_cast(calloc( + length + ((&m_currentPosition)[length - 1] == '\0' ? 0 : 1), sizeof(char))); + memcpy(string_t, &m_currentPosition, length); + m_currentPosition += length; + return *this; + } - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserialize( - wchar_t*& string_t) +FastCdr& FastCdr::deserialize(wchar_t*& string_t) { - uint32_t length = 0; - FastCdr::state state_before_error(*this); + uint32_t length = 0; + FastCdr::state state_before_error(*this); - deserialize(length); + deserialize(length); - if (length == 0) - { - string_t = NULL; - return *this; - } - else if ((m_lastPosition - m_currentPosition) >= length) - { - // Allocate memory. - string_t = reinterpret_cast(calloc(length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero + if (length == 0) + { + string_t = NULL; + return *this; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + // Allocate memory. + string_t = reinterpret_cast(calloc( + length + 1, sizeof(wchar_t))); // WStrings never serialize terminating zero #if defined(_WIN32) - for (size_t idx = 0; idx < length; ++idx) - { - uint32_t temp; - m_currentPosition >> temp; - string_t[idx] = static_cast(temp); - m_currentPosition += 4; - } + for (size_t idx = 0; idx < length; ++idx) + { + uint32_t temp; + m_currentPosition >> temp; + string_t[idx] = static_cast(temp); + m_currentPosition += 4; + } #else - memcpy(string_t, &m_currentPosition, length * sizeof(wchar_t)); - m_currentPosition += length * sizeof(wchar_t); -#endif // if defined(_WIN32) + memcpy(string_t, &m_currentPosition, length * sizeof(wchar_t)); + m_currentPosition += length * sizeof(wchar_t); +#endif // if defined(_WIN32) - return *this; - } + return *this; + } - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -const char* FastCdr::readString( - uint32_t& length) +const char* FastCdr::readString(uint32_t& length) { - const char* returnedValue = ""; - state state_before_error(*this); + const char* returnedValue = ""; + state state_before_error(*this); - *this >> length; + *this >> length; - if (length == 0) - { - return returnedValue; - } - else if ((m_lastPosition - m_currentPosition) >= length) + if (length == 0) + { + return returnedValue; + } + else if ((m_lastPosition - m_currentPosition) >= length) + { + returnedValue = &m_currentPosition; + m_currentPosition += length; + if (returnedValue[length - 1] == '\0') { - returnedValue = &m_currentPosition; - m_currentPosition += length; - if (returnedValue[length - 1] == '\0') - { - --length; - } - return returnedValue; + --length; } + return returnedValue; + } - setState(state_before_error); - throw eprosima::fastcdr::exception::NotEnoughMemoryException( - eprosima::fastcdr::exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_before_error); + throw eprosima::fastcdr::exception::NotEnoughMemoryException( + eprosima::fastcdr::exception::NotEnoughMemoryException:: + NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -std::wstring FastCdr::readWString( - uint32_t& length) +std::wstring FastCdr::readWString(uint32_t& length) { - std::wstring returnedValue = L""; - state state_(*this); + std::wstring returnedValue = L""; + state state_(*this); - *this >> length; - uint32_t bytesLength = length * 4; + *this >> length; + uint32_t bytesLength = length * 4; - if (bytesLength == 0) - { - return returnedValue; - } - else if ((m_lastPosition - m_currentPosition) >= bytesLength) + if (bytesLength == 0) + { + return returnedValue; + } + else if ((m_lastPosition - m_currentPosition) >= bytesLength) + { + returnedValue.resize(length); + deserializeArray(const_cast(returnedValue.c_str()), length); + if (returnedValue[length - 1] == L'\0') { - - returnedValue.resize(length); - deserializeArray(const_cast(returnedValue.c_str()), length); - if (returnedValue[length - 1] == L'\0') - { - --length; - returnedValue.erase(length); - } - return returnedValue; + --length; + returnedValue.erase(length); } + return returnedValue; + } - setState(state_); - throw eprosima::fastcdr::exception::NotEnoughMemoryException( - eprosima::fastcdr::exception::NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + setState(state_); + throw eprosima::fastcdr::exception::NotEnoughMemoryException( + eprosima::fastcdr::exception::NotEnoughMemoryException:: + NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - bool* bool_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(bool* bool_t, size_t numElements) { - size_t totalSize = sizeof(*bool_t) * numElements; + size_t totalSize = sizeof(*bool_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + for (size_t count = 0; count < numElements; ++count) { - for (size_t count = 0; count < numElements; ++count) - { - uint8_t value = 0; - m_currentPosition++ >> value; - - if (value == 1) - { - bool_t[count] = true; - } - else if (value == 0) - { - bool_t[count] = false; - } - } - - return *this; + uint8_t value = 0; + m_currentPosition++ >> value; + + if (value == 1) + { + bool_t[count] = true; + } + else if (value == 0) + { + bool_t[count] = false; + } } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + return *this; + } + + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - char* char_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(char* char_t, size_t numElements) { - size_t totalSize = sizeof(*char_t) * numElements; + size_t totalSize = sizeof(*char_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(char_t, totalSize); - m_currentPosition += totalSize; - return *this; - } + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(char_t, totalSize); + m_currentPosition += totalSize; + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - int16_t* short_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(int16_t* short_t, size_t numElements) { - size_t totalSize = sizeof(*short_t) * numElements; + size_t totalSize = sizeof(*short_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(short_t, totalSize); - m_currentPosition += totalSize; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(short_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - int32_t* long_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(int32_t* long_t, size_t numElements) { - size_t totalSize = sizeof(*long_t) * numElements; + size_t totalSize = sizeof(*long_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(long_t, totalSize); - m_currentPosition += totalSize; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(long_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - wchar_t* wchar, - size_t numElements) +FastCdr& FastCdr::deserializeArray(wchar_t* wchar, size_t numElements) { - uint32_t value = 0; - for (size_t count = 0; count < numElements; ++count) - { - deserialize(value); - wchar[count] = static_cast(value); - } - return *this; + uint32_t value = 0; + for (size_t count = 0; count < numElements; ++count) + { + deserialize(value); + wchar[count] = static_cast(value); + } + return *this; } -FastCdr& FastCdr::deserializeArray( - int64_t* longlong_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(int64_t* longlong_t, size_t numElements) { - size_t totalSize = sizeof(*longlong_t) * numElements; + size_t totalSize = sizeof(*longlong_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(longlong_t, totalSize); - m_currentPosition += totalSize; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(longlong_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - float* float_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(float* float_t, size_t numElements) { - size_t totalSize = sizeof(*float_t) * numElements; + size_t totalSize = sizeof(*float_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(float_t, totalSize); - m_currentPosition += totalSize; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(float_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - double* double_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(double* double_t, size_t numElements) { - size_t totalSize = sizeof(*double_t) * numElements; + size_t totalSize = sizeof(*double_t) * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { - m_currentPosition.rmemcopy(double_t, totalSize); - m_currentPosition += totalSize; + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + m_currentPosition.rmemcopy(double_t, totalSize); + m_currentPosition += totalSize; - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::deserializeArray( - long double* ldouble_t, - size_t numElements) +FastCdr& FastCdr::deserializeArray(long double* ldouble_t, size_t numElements) { - size_t totalSize = 16 * numElements; + size_t totalSize = 16 * numElements; - if ((m_lastPosition - m_currentPosition) >= totalSize) - { + if ((m_lastPosition - m_currentPosition) >= totalSize) + { #if FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - for (size_t idx = 0; idx < numElements; ++idx) - { - __float128 tmp; - m_currentPosition >> tmp; - m_currentPosition += 16; - ldouble_t[idx] = static_cast(tmp); - } + for (size_t idx = 0; idx < numElements; ++idx) + { + __float128 tmp; + m_currentPosition >> tmp; + m_currentPosition += 16; + ldouble_t[idx] = static_cast(tmp); + } #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 16 - m_currentPosition.rmemcopy(ldouble_t, totalSize); - m_currentPosition += totalSize; + m_currentPosition.rmemcopy(ldouble_t, totalSize); + m_currentPosition += totalSize; #else #if FASTCDR_SIZEOF_LONG_DOUBLE == 8 - for (size_t idx = 0; idx < numElements; ++idx) - { - m_currentPosition += 8; - m_currentPosition >> ldouble_t[idx]; - m_currentPosition += 8; - } + for (size_t idx = 0; idx < numElements; ++idx) + { + m_currentPosition += 8; + m_currentPosition >> ldouble_t[idx]; + m_currentPosition += 8; + } #else #error unsupported long double type and no __float128 available -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 -#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 -#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 8 +#endif // FASTCDR_SIZEOF_LONG_DOUBLE == 16 +#endif // FASTCDR_HAVE_FLOAT128 && FASTCDR_SIZEOF_LONG_DOUBLE < 16 - return *this; - } + return *this; + } - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); } -FastCdr& FastCdr::serializeBoolSequence( - const std::vector& vector_t) +FastCdr& FastCdr::serializeBoolSequence(const std::vector& vector_t) { - state state_before_error(*this); + state state_before_error(*this); - *this << static_cast(vector_t.size()); + *this << static_cast(vector_t.size()); - size_t totalSize = vector_t.size() * sizeof(bool); + size_t totalSize = vector_t.size() * sizeof(bool); - if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) - { - for (size_t count = 0; count < vector_t.size(); ++count) - { - uint8_t value = 0; - std::vector::const_reference ref = vector_t[count]; - - if (ref) - { - value = 1; - } - m_currentPosition++ << value; - } - } - else + if (((m_lastPosition - m_currentPosition) >= totalSize) || resize(totalSize)) + { + for (size_t count = 0; count < vector_t.size(); ++count) { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + uint8_t value = 0; + std::vector::const_reference ref = vector_t[count]; + + if (ref) + { + value = 1; + } + m_currentPosition++ << value; } + } + else + { + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } - return *this; + return *this; } -FastCdr& FastCdr::deserializeBoolSequence( - std::vector& vector_t) +FastCdr& FastCdr::deserializeBoolSequence(std::vector& vector_t) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - *this >> seqLength; + *this >> seqLength; - size_t totalSize = seqLength * sizeof(bool); + size_t totalSize = seqLength * sizeof(bool); - if ((m_lastPosition - m_currentPosition) >= totalSize) + if ((m_lastPosition - m_currentPosition) >= totalSize) + { + vector_t.resize(seqLength); + for (uint32_t count = 0; count < seqLength; ++count) { - vector_t.resize(seqLength); - for (uint32_t count = 0; count < seqLength; ++count) - { - uint8_t value = 0; - m_currentPosition++ >> value; - - if (value == 1) - { - vector_t[count] = true; - } - else if (value == 0) - { - vector_t[count] = false; - } - } - } - else - { - setState(state_before_error); - throw NotEnoughMemoryException(NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + uint8_t value = 0; + m_currentPosition++ >> value; + + if (value == 1) + { + vector_t[count] = true; + } + else if (value == 0) + { + vector_t[count] = false; + } } + } + else + { + setState(state_before_error); + throw NotEnoughMemoryException( + NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT); + } - return *this; + return *this; } -FastCdr& FastCdr::deserializeStringSequence( - std::string*& sequence_t, - size_t& numElements) +FastCdr& FastCdr::deserializeStringSequence(std::string*& sequence_t, size_t& numElements) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - deserialize(seqLength); + deserialize(seqLength); - try - { - sequence_t = new std::string[seqLength]; - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - delete [] sequence_t; - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } + try + { + sequence_t = new std::string[seqLength]; + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + delete[] sequence_t; + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } - numElements = seqLength; - return *this; + numElements = seqLength; + return *this; } -FastCdr& FastCdr::deserializeWStringSequence( - std::wstring*& sequence_t, - size_t& numElements) +FastCdr& FastCdr::deserializeWStringSequence(std::wstring*& sequence_t, + size_t& numElements) { - uint32_t seqLength = 0; - state state_before_error(*this); + uint32_t seqLength = 0; + state state_before_error(*this); - deserialize(seqLength); + deserialize(seqLength); - try - { - sequence_t = new std::wstring[seqLength]; - deserializeArray(sequence_t, seqLength); - } - catch (eprosima::fastcdr::exception::Exception& ex) - { - delete [] sequence_t; - sequence_t = NULL; - setState(state_before_error); - ex.raise(); - } + try + { + sequence_t = new std::wstring[seqLength]; + deserializeArray(sequence_t, seqLength); + } + catch (eprosima::fastcdr::exception::Exception& ex) + { + delete[] sequence_t; + sequence_t = NULL; + setState(state_before_error); + ex.raise(); + } - numElements = seqLength; - return *this; + numElements = seqLength; + return *this; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/BadParamException.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/BadParamException.cpp index e111144cd..bb7cd35cf 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/BadParamException.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/BadParamException.cpp @@ -18,53 +18,45 @@ using namespace eprosima::fastcdr::exception; const char* const BadParamException::BAD_PARAM_MESSAGE_DEFAULT = "Bad parameter"; -BadParamException::BadParamException( - const char* const& message) noexcept - : Exception(message) +BadParamException::BadParamException(const char* const& message) noexcept + : Exception(message) { } -BadParamException::BadParamException( - const BadParamException& ex) noexcept - : Exception(ex) +BadParamException::BadParamException(const BadParamException& ex) noexcept : Exception(ex) { } #if HAVE_CXX0X -BadParamException::BadParamException( - BadParamException&& ex) noexcept - : Exception(std::move(ex)) +BadParamException::BadParamException(BadParamException&& ex) noexcept + : Exception(std::move(ex)) { } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X -BadParamException& BadParamException::operator =( - const BadParamException& ex) noexcept +BadParamException& BadParamException::operator=(const BadParamException& ex) noexcept { - if (this != &ex) - { - Exception::operator =( - ex); - } + if (this != &ex) + { + Exception::operator=(ex); + } - return *this; + return *this; } #if HAVE_CXX0X -BadParamException& BadParamException::operator =( - BadParamException&& ex) noexcept +BadParamException& BadParamException::operator=(BadParamException&& ex) noexcept { - if (this != &ex) - { - Exception::operator =( - std::move(ex)); - } + if (this != &ex) + { + Exception::operator=(std::move(ex)); + } - return *this; + return *this; } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X BadParamException::~BadParamException() noexcept { @@ -72,5 +64,5 @@ BadParamException::~BadParamException() noexcept void BadParamException::raise() const { - throw *this; + throw *this; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/Exception.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/Exception.cpp index 8459b23b4..304fe49f9 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/Exception.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/Exception.cpp @@ -16,43 +16,35 @@ using namespace eprosima::fastcdr::exception; -Exception::Exception( - const char* const& message) noexcept - : m_message(message) +Exception::Exception(const char* const& message) noexcept : m_message(message) { } -Exception::Exception( - const Exception& ex) noexcept - : m_message(ex.m_message) +Exception::Exception(const Exception& ex) noexcept : m_message(ex.m_message) { } #if HAVE_CXX0X -Exception::Exception( - Exception&& ex) noexcept - : m_message(std::move(ex.m_message)) +Exception::Exception(Exception&& ex) noexcept : m_message(std::move(ex.m_message)) { } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X -Exception& Exception::operator =( - const Exception& ex) noexcept +Exception& Exception::operator=(const Exception& ex) noexcept { - m_message = ex.m_message; - return *this; + m_message = ex.m_message; + return *this; } #if HAVE_CXX0X -Exception& Exception::operator =( - Exception&& ex) noexcept +Exception& Exception::operator=(Exception&& ex) noexcept { - m_message = std::move(ex.m_message); - return *this; + m_message = std::move(ex.m_message); + return *this; } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X Exception::~Exception() noexcept { @@ -60,5 +52,5 @@ Exception::~Exception() noexcept const char* Exception::what() const noexcept { - return m_message; + return m_message; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/NotEnoughMemoryException.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/NotEnoughMemoryException.cpp index 67e5c4513..1cc285fd4 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/NotEnoughMemoryException.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/3rdparty/Fast-CDR/src/cpp/exceptions/NotEnoughMemoryException.cpp @@ -16,56 +16,56 @@ using namespace eprosima::fastcdr::exception; -const char* const NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT = - "Not enough memory in the buffer stream"; +const char* const NotEnoughMemoryException::NOT_ENOUGH_MEMORY_MESSAGE_DEFAULT = "Not " + "enough " + "memory " + "in the " + "buffer " + "stream"; -NotEnoughMemoryException::NotEnoughMemoryException( - const char* const& message) noexcept - : Exception(message) +NotEnoughMemoryException::NotEnoughMemoryException(const char* const& message) noexcept + : Exception(message) { } NotEnoughMemoryException::NotEnoughMemoryException( - const NotEnoughMemoryException& ex) noexcept - : Exception(ex) + const NotEnoughMemoryException& ex) noexcept + : Exception(ex) { } #if HAVE_CXX0X -NotEnoughMemoryException::NotEnoughMemoryException( - NotEnoughMemoryException&& ex) noexcept - : Exception(std::move(ex)) +NotEnoughMemoryException::NotEnoughMemoryException(NotEnoughMemoryException&& ex) noexcept + : Exception(std::move(ex)) { } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X -NotEnoughMemoryException& NotEnoughMemoryException::operator =( - const NotEnoughMemoryException& ex) noexcept +NotEnoughMemoryException& +NotEnoughMemoryException::operator=(const NotEnoughMemoryException& ex) noexcept { - if (this != &ex) - { - Exception::operator =( - ex); - } + if (this != &ex) + { + Exception::operator=(ex); + } - return *this; + return *this; } #if HAVE_CXX0X -NotEnoughMemoryException& NotEnoughMemoryException::operator =( - NotEnoughMemoryException&& ex) noexcept +NotEnoughMemoryException& +NotEnoughMemoryException::operator=(NotEnoughMemoryException&& ex) noexcept { - if (this != &ex) - { - Exception::operator =( - std::move(ex)); - } + if (this != &ex) + { + Exception::operator=(std::move(ex)); + } - return *this; + return *this; } -#endif // if HAVE_CXX0X +#endif // if HAVE_CXX0X NotEnoughMemoryException::~NotEnoughMemoryException() noexcept { @@ -73,5 +73,5 @@ NotEnoughMemoryException::~NotEnoughMemoryException() noexcept void NotEnoughMemoryException::raise() const { - throw *this; + throw *this; } diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/builtin_types.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/builtin_types.hpp index dd295eba8..3d55019d1 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/builtin_types.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/builtin_types.hpp @@ -1,26 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ - + * + * Copyright (c) 2016-2022 Davide Faconti + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ #ifndef ROS_BUILTIN_TYPES_HPP #define ROS_BUILTIN_TYPES_HPP @@ -32,70 +31,108 @@ #include "rosx_introspection/contrib/span.hpp" #include "rosx_introspection/contrib/SmallVector.h" -namespace RosMsgParser{ +namespace RosMsgParser +{ -template< class T> +template using Span = nonstd::span; -template< class T, size_t N> +template using SmallVector = llvm_vecsmall::SmallVector; -enum BuiltinType { - BOOL , BYTE, CHAR, - UINT8, UINT16, UINT32, UINT64, - INT8, INT16, INT32, INT64, - FLOAT32, FLOAT64, - TIME, DURATION, - STRING, OTHER +enum BuiltinType +{ + BOOL, + BYTE, + CHAR, + UINT8, + UINT16, + UINT32, + UINT64, + INT8, + INT16, + INT32, + INT64, + FLOAT32, + FLOAT64, + TIME, + DURATION, + STRING, + OTHER }; //--------------------------------------------------------- -inline int builtinSize(const BuiltinType c) { - switch (c) { - case BOOL: - case BYTE: - case INT8: - case CHAR: - case UINT8: return 1; - case UINT16: - case INT16: return 2; - case UINT32: - case INT32: - case FLOAT32: return 4; - case UINT64: - case INT64: - case FLOAT64: - case TIME: - case DURATION: return 8; - case STRING: - case OTHER: return -1; +inline int builtinSize(const BuiltinType c) +{ + switch (c) + { + case BOOL: + case BYTE: + case INT8: + case CHAR: + case UINT8: + return 1; + case UINT16: + case INT16: + return 2; + case UINT32: + case INT32: + case FLOAT32: + return 4; + case UINT64: + case INT64: + case FLOAT64: + case TIME: + case DURATION: + return 8; + case STRING: + case OTHER: + return -1; } - throw std::runtime_error( "unsupported builtin type value"); + throw std::runtime_error("unsupported builtin type value"); } inline const char* toStr(const BuiltinType& c) { - switch (c) { - case BOOL: return "BOOL"; - case BYTE: return "BYTE"; - case INT8: return "INT8"; - case CHAR: return "CHAR"; - case UINT8: return "UINT8"; - case UINT16: return "UINT16"; - case UINT32: return "UINT32"; - case UINT64: return "UINT64"; - case INT16: return "INT16"; - case INT32: return "INT32"; - case INT64: return "INT64"; - case FLOAT32: return "FLOAT32"; - case FLOAT64: return "FLOAT64"; - case TIME: return "TIME"; - case DURATION: return "DURATION"; - case STRING: return "STRING"; - case OTHER: return "OTHER"; + switch (c) + { + case BOOL: + return "BOOL"; + case BYTE: + return "BYTE"; + case INT8: + return "INT8"; + case CHAR: + return "CHAR"; + case UINT8: + return "UINT8"; + case UINT16: + return "UINT16"; + case UINT32: + return "UINT32"; + case UINT64: + return "UINT64"; + case INT16: + return "INT16"; + case INT32: + return "INT32"; + case INT64: + return "INT64"; + case FLOAT32: + return "FLOAT32"; + case FLOAT64: + return "FLOAT64"; + case TIME: + return "TIME"; + case DURATION: + return "DURATION"; + case STRING: + return "STRING"; + case OTHER: + return "OTHER"; } - throw std::runtime_error( "unsupported builtin type value"); + throw std::runtime_error("unsupported builtin type value"); } inline std::ostream& operator<<(std::ostream& os, const BuiltinType& c) @@ -104,9 +141,10 @@ inline std::ostream& operator<<(std::ostream& os, const BuiltinType& c) return os; } -template BuiltinType getType() +template +BuiltinType getType() { - return OTHER; + return OTHER; } struct Time @@ -116,32 +154,87 @@ struct Time double toSec() { - return double(sec) + double(nsec)*1e-9; + return double(sec) + double(nsec) * 1e-9; } }; +template <> +inline BuiltinType getType() +{ + return BOOL; +} -template <> inline BuiltinType getType() { return BOOL; } - -template <> inline BuiltinType getType() { return CHAR; } - -template <> inline BuiltinType getType() { return INT8; } -template <> inline BuiltinType getType() { return INT16; } -template <> inline BuiltinType getType() { return INT32; } -template <> inline BuiltinType getType() { return INT64; } +template <> +inline BuiltinType getType() +{ + return CHAR; +} -template <> inline BuiltinType getType() { return UINT8; } -template <> inline BuiltinType getType() { return UINT16; } -template <> inline BuiltinType getType() { return UINT32; } -template <> inline BuiltinType getType() { return UINT64; } +template <> +inline BuiltinType getType() +{ + return INT8; +} +template <> +inline BuiltinType getType() +{ + return INT16; +} +template <> +inline BuiltinType getType() +{ + return INT32; +} +template <> +inline BuiltinType getType() +{ + return INT64; +} -template <> inline BuiltinType getType() { return FLOAT32; } -template <> inline BuiltinType getType() { return FLOAT64; } +template <> +inline BuiltinType getType() +{ + return UINT8; +} +template <> +inline BuiltinType getType() +{ + return UINT16; +} +template <> +inline BuiltinType getType() +{ + return UINT32; +} +template <> +inline BuiltinType getType() +{ + return UINT64; +} -template <> inline BuiltinType getType() { return STRING; } +template <> +inline BuiltinType getType() +{ + return FLOAT32; +} +template <> +inline BuiltinType getType() +{ + return FLOAT64; +} -template <> inline BuiltinType getType() { return TIME; } +template <> +inline BuiltinType getType() +{ + return STRING; +} +template <> +inline BuiltinType getType() +{ + return TIME; } -#endif // ROS_BUILTIN_TYPES_HPP +} // namespace RosMsgParser + +#endif // ROS_BUILTIN_TYPES_HPP diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/SmallVector.h b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/SmallVector.h index ad2b676ff..13c9141e1 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/SmallVector.h +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/SmallVector.h @@ -29,66 +29,82 @@ #define LLVM_VECSMALL_UNLIKELY(x) (x) // LLVM External Functions -namespace llvm_vecsmall { - namespace detail { - /// NextPowerOf2 - Returns the next power of two (in 64-bits) - /// that is strictly greater than A. Returns zero on overflow. - inline uint64_t NextPowerOf2(uint64_t A) { - A |= (A >> 1); - A |= (A >> 2); - A |= (A >> 4); - A |= (A >> 8); - A |= (A >> 16); - A |= (A >> 32); - return A + 1; - } - } +namespace llvm_vecsmall +{ +namespace detail +{ +/// NextPowerOf2 - Returns the next power of two (in 64-bits) +/// that is strictly greater than A. Returns zero on overflow. +inline uint64_t NextPowerOf2(uint64_t A) +{ + A |= (A >> 1); + A |= (A >> 2); + A |= (A >> 4); + A |= (A >> 8); + A |= (A >> 16); + A |= (A >> 32); + return A + 1; } +} // namespace detail +} // namespace llvm_vecsmall - -namespace llvm_vecsmall { +namespace llvm_vecsmall +{ // std::is_pod has been deprecated in C++20. template struct IsPod : std::integral_constant::value && - std::is_trivial::value> {}; + std::is_trivial::value> +{ +}; /// This is all the non-templated stuff common to all SmallVectors. -class SmallVectorBase { +class SmallVectorBase +{ protected: void *BeginX, *EndX, *CapacityX; protected: - SmallVectorBase(void *FirstEl, size_t Size) - : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl+Size) {} + SmallVectorBase(void* FirstEl, size_t Size) + : BeginX(FirstEl), EndX(FirstEl), CapacityX((char*)FirstEl + Size) + { + } /// This is an implementation of the grow() method which only works /// on POD-like data types and is out of line to reduce code duplication. - void grow_pod(void *FirstEl, size_t MinSizeInBytes, size_t TSize); + void grow_pod(void* FirstEl, size_t MinSizeInBytes, size_t TSize); public: /// This returns size()*sizeof(T). - size_t size_in_bytes() const { + size_t size_in_bytes() const + { return size_t((char*)EndX - (char*)BeginX); } /// capacity_in_bytes - This returns capacity()*sizeof(T). - size_t capacity_in_bytes() const { + size_t capacity_in_bytes() const + { return size_t((char*)CapacityX - (char*)BeginX); } - LLVM_VECSMALL_NODISCARD bool empty() const { return BeginX == EndX; } + LLVM_VECSMALL_NODISCARD bool empty() const + { + return BeginX == EndX; + } }; -template struct SmallVectorStorage; +template +struct SmallVectorStorage; /// This is the part of SmallVectorTemplateBase which does not depend on whether /// the type T is a POD. The extra dummy template argument is used by ArrayRef /// to avoid unnecessarily requiring T to be complete. template -class SmallVectorTemplateCommon : public SmallVectorBase { +class SmallVectorTemplateCommon : public SmallVectorBase +{ private: - template friend struct SmallVectorStorage; + template + friend struct SmallVectorStorage; // Allocate raw space for N elements of type T. If T has a ctor or dtor, we // don't want it to be automatically run, so we need to represent the space as @@ -99,96 +115,157 @@ class SmallVectorTemplateCommon : public SmallVectorBase { // Space after 'FirstEl' is clobbered, do not add any instance vars after it. protected: - SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) {} + SmallVectorTemplateCommon(size_t Size) : SmallVectorBase(&FirstEl, Size) + { + } - void grow_pod(size_t MinSizeInBytes, size_t TSize) { + void grow_pod(size_t MinSizeInBytes, size_t TSize) + { SmallVectorBase::grow_pod(&FirstEl, MinSizeInBytes, TSize); } /// Return true if this is a smallvector which has not had dynamic /// memory allocated for it. - bool isSmall() const { + bool isSmall() const + { return BeginX == static_cast(&FirstEl); } /// Put this vector in a state of being small. - void resetToSmall() { + void resetToSmall() + { BeginX = EndX = CapacityX = &FirstEl; } - void setEnd(T *P) { this->EndX = P; } + void setEnd(T* P) + { + this->EndX = P; + } + public: typedef size_t size_type; typedef ptrdiff_t difference_type; typedef T value_type; - typedef T *iterator; - typedef const T *const_iterator; + typedef T* iterator; + typedef const T* const_iterator; typedef std::reverse_iterator const_reverse_iterator; typedef std::reverse_iterator reverse_iterator; - typedef T &reference; - typedef const T &const_reference; - typedef T *pointer; - typedef const T *const_pointer; + typedef T& reference; + typedef const T& const_reference; + typedef T* pointer; + typedef const T* const_pointer; // forward iterator creation methods. LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - iterator begin() { return (iterator)this->BeginX; } + iterator begin() + { + return (iterator)this->BeginX; + } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - const_iterator begin() const { return (const_iterator)this->BeginX; } + const_iterator begin() const + { + return (const_iterator)this->BeginX; + } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - iterator end() { return (iterator)this->EndX; } + iterator end() + { + return (iterator)this->EndX; + } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - const_iterator end() const { return (const_iterator)this->EndX; } + const_iterator end() const + { + return (const_iterator)this->EndX; + } + protected: - iterator capacity_ptr() { return (iterator)this->CapacityX; } - const_iterator capacity_ptr() const { return (const_iterator)this->CapacityX;} -public: + iterator capacity_ptr() + { + return (iterator)this->CapacityX; + } + const_iterator capacity_ptr() const + { + return (const_iterator)this->CapacityX; + } +public: // reverse iterator creation methods. - reverse_iterator rbegin() { return reverse_iterator(end()); } - const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); } - reverse_iterator rend() { return reverse_iterator(begin()); } - const_reverse_iterator rend() const { return const_reverse_iterator(begin());} + reverse_iterator rbegin() + { + return reverse_iterator(end()); + } + const_reverse_iterator rbegin() const + { + return const_reverse_iterator(end()); + } + reverse_iterator rend() + { + return reverse_iterator(begin()); + } + const_reverse_iterator rend() const + { + return const_reverse_iterator(begin()); + } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - size_type size() const { return end()-begin(); } - size_type max_size() const { return size_type(-1) / sizeof(T); } + size_type size() const + { + return end() - begin(); + } + size_type max_size() const + { + return size_type(-1) / sizeof(T); + } /// Return the total number of elements in the currently allocated buffer. - size_t capacity() const { return capacity_ptr() - begin(); } + size_t capacity() const + { + return capacity_ptr() - begin(); + } /// Return a pointer to the vector's buffer, even if empty(). - pointer data() { return pointer(begin()); } + pointer data() + { + return pointer(begin()); + } /// Return a pointer to the vector's buffer, even if empty(). - const_pointer data() const { return const_pointer(begin()); } + const_pointer data() const + { + return const_pointer(begin()); + } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - reference operator[](size_type idx) { + reference operator[](size_type idx) + { assert(idx < size()); return begin()[idx]; } LLVM_VECSMALL_ATTRIBUTE_ALWAYS_INLINE - const_reference operator[](size_type idx) const { + const_reference operator[](size_type idx) const + { assert(idx < size()); return begin()[idx]; } - reference front() { + reference front() + { assert(!empty()); return begin()[0]; } - const_reference front() const { + const_reference front() const + { assert(!empty()); return begin()[0]; } - reference back() { + reference back() + { assert(!empty()); return end()[-1]; } - const_reference back() const { + const_reference back() const + { assert(!empty()); return end()[-1]; } @@ -197,12 +274,17 @@ class SmallVectorTemplateCommon : public SmallVectorBase { /// SmallVectorTemplateBase - This is where we put method /// implementations that are designed to work with non-POD-like T's. template -class SmallVectorTemplateBase : public SmallVectorTemplateCommon { +class SmallVectorTemplateBase : public SmallVectorTemplateCommon +{ protected: - SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} + SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) + { + } - static void destroy_range(T *S, T *E) { - while (S != E) { + static void destroy_range(T* S, T* E) + { + while (S != E) + { --E; E->~T(); } @@ -210,16 +292,17 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon { /// Move the range [I, E) into the uninitialized memory starting with "Dest", /// constructing elements as needed. - template - static void uninitialized_move(It1 I, It1 E, It2 Dest) { - std::uninitialized_copy(std::make_move_iterator(I), - std::make_move_iterator(E), Dest); + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) + { + std::uninitialized_copy(std::make_move_iterator(I), std::make_move_iterator(E), Dest); } /// Copy the range [I, E) onto the uninitialized memory starting with "Dest", /// constructing elements as needed. - template - static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) + { std::uninitialized_copy(I, E, Dest); } @@ -229,36 +312,40 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon { void grow(size_t MinSize = 0); public: - void push_back(const T &Elt) { + void push_back(const T& Elt) + { if (LLVM_VECSMALL_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); - ::new ((void*) this->end()) T(Elt); - this->setEnd(this->end()+1); + ::new ((void*)this->end()) T(Elt); + this->setEnd(this->end() + 1); } - void push_back(T &&Elt) { + void push_back(T&& Elt) + { if (LLVM_VECSMALL_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); - ::new ((void*) this->end()) T(::std::move(Elt)); - this->setEnd(this->end()+1); + ::new ((void*)this->end()) T(::std::move(Elt)); + this->setEnd(this->end() + 1); } - void pop_back() { - this->setEnd(this->end()-1); + void pop_back() + { + this->setEnd(this->end() - 1); this->end()->~T(); } }; // Define this out-of-line to dissuade the C++ compiler from inlining it. template -void SmallVectorTemplateBase::grow(size_t MinSize) { +void SmallVectorTemplateBase::grow(size_t MinSize) +{ size_t CurCapacity = this->capacity(); size_t CurSize = this->size(); // Always grow, even from zero. - size_t NewCapacity = size_t(llvm_vecsmall::detail::NextPowerOf2(CurCapacity+2)); + size_t NewCapacity = size_t(llvm_vecsmall::detail::NextPowerOf2(CurCapacity + 2)); if (NewCapacity < MinSize) NewCapacity = MinSize; - T *NewElts = static_cast(malloc(NewCapacity*sizeof(T))); + T* NewElts = static_cast(malloc(NewCapacity * sizeof(T))); // Move the elements over. this->uninitialized_move(this->begin(), this->end(), NewElts); @@ -270,34 +357,40 @@ void SmallVectorTemplateBase::grow(size_t MinSize) { if (!this->isSmall()) free(this->begin()); - this->setEnd(NewElts+CurSize); + this->setEnd(NewElts + CurSize); this->BeginX = NewElts; - this->CapacityX = this->begin()+NewCapacity; + this->CapacityX = this->begin() + NewCapacity; } - /// SmallVectorTemplateBase - This is where we put method /// implementations that are designed to work with POD-like T's. template -class SmallVectorTemplateBase : public SmallVectorTemplateCommon { +class SmallVectorTemplateBase : public SmallVectorTemplateCommon +{ protected: - SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) {} + SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon(Size) + { + } // No need to do a destroy loop for POD's. - static void destroy_range(T *, T *) {} + static void destroy_range(T*, T*) + { + } /// Move the range [I, E) onto the uninitialized memory /// starting with "Dest", constructing elements into it as needed. - template - static void uninitialized_move(It1 I, It1 E, It2 Dest) { + template + static void uninitialized_move(It1 I, It1 E, It2 Dest) + { // Just do a copy. uninitialized_copy(I, E, Dest); } /// Copy the range [I, E) onto the uninitialized memory /// starting with "Dest", constructing elements into it as needed. - template - static void uninitialized_copy(It1 I, It1 E, It2 Dest) { + template + static void uninitialized_copy(It1 I, It1 E, It2 Dest) + { // Arbitrary iterator types; just use the basic implementation. std::uninitialized_copy(I, E, Dest); } @@ -306,9 +399,10 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon { /// starting with "Dest", constructing elements into it as needed. template static void uninitialized_copy( - T1 *I, T1 *E, T2 *Dest, - typename std::enable_if::type, - T2>::value>::type * = nullptr) { + T1* I, T1* E, T2* Dest, + typename std::enable_if< + std::is_same::type, T2>::value>::type* = nullptr) + { // Use memcpy for PODs iterated by pointers (which includes SmallVector // iterators): std::uninitialized_copy optimizes to memmove, but we can // use memcpy here. Note that I and E are iterators and thus might be @@ -319,27 +413,31 @@ class SmallVectorTemplateBase : public SmallVectorTemplateCommon { /// Double the size of the allocated memory, guaranteeing space for at /// least one more element or MinSize if specified. - void grow(size_t MinSize = 0) { - this->grow_pod(MinSize*sizeof(T), sizeof(T)); + void grow(size_t MinSize = 0) + { + this->grow_pod(MinSize * sizeof(T), sizeof(T)); } + public: - void push_back(const T &Elt) { + void push_back(const T& Elt) + { if (LLVM_VECSMALL_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); memcpy(this->end(), &Elt, sizeof(T)); - this->setEnd(this->end()+1); + this->setEnd(this->end() + 1); } - void pop_back() { - this->setEnd(this->end()-1); + void pop_back() + { + this->setEnd(this->end() - 1); } }; - /// This class consists of common code factored out of the SmallVector class to /// reduce code duplication based on the SmallVector 'N' template parameter. template -class SmallVectorImpl : public SmallVectorTemplateBase::value> { +class SmallVectorImpl : public SmallVectorTemplateBase::value> +{ typedef SmallVectorTemplateBase::value> SuperClass; SmallVectorImpl(const SmallVectorImpl&) = delete; @@ -352,11 +450,13 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { protected: // Default ctor - Initialize to empty. explicit SmallVectorImpl(unsigned N) - : SmallVectorTemplateBase::value>(N*sizeof(T)) { + : SmallVectorTemplateBase::value>(N * sizeof(T)) + { } public: - ~SmallVectorImpl() { + ~SmallVectorImpl() + { // Destroy the constructed elements in the vector. this->destroy_range(this->begin(), this->end()); @@ -365,57 +465,68 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { free(this->begin()); } - - void clear() { + void clear() + { this->destroy_range(this->begin(), this->end()); this->EndX = this->BeginX; } - void resize(size_type N) { - if (N < this->size()) { - this->destroy_range(this->begin()+N, this->end()); - this->setEnd(this->begin()+N); - } else if (N > this->size()) { + void resize(size_type N) + { + if (N < this->size()) + { + this->destroy_range(this->begin() + N, this->end()); + this->setEnd(this->begin() + N); + } + else if (N > this->size()) + { if (this->capacity() < N) this->grow(N); for (auto I = this->end(), E = this->begin() + N; I != E; ++I) new (&*I) T(); - this->setEnd(this->begin()+N); + this->setEnd(this->begin() + N); } } - void resize(size_type N, const T &NV) { - if (N < this->size()) { - this->destroy_range(this->begin()+N, this->end()); - this->setEnd(this->begin()+N); - } else if (N > this->size()) { + void resize(size_type N, const T& NV) + { + if (N < this->size()) + { + this->destroy_range(this->begin() + N, this->end()); + this->setEnd(this->begin() + N); + } + else if (N > this->size()) + { if (this->capacity() < N) this->grow(N); - std::uninitialized_fill(this->end(), this->begin()+N, NV); - this->setEnd(this->begin()+N); + std::uninitialized_fill(this->end(), this->begin() + N, NV); + this->setEnd(this->begin() + N); } } - void reserve(size_type N) { + void reserve(size_type N) + { if (this->capacity() < N) this->grow(N); } - LLVM_VECSMALL_NODISCARD T pop_back_val() { + LLVM_VECSMALL_NODISCARD T pop_back_val() + { T Result = ::std::move(this->back()); this->pop_back(); return Result; } - void swap(SmallVectorImpl &RHS); + void swap(SmallVectorImpl& RHS); /// Add the specified range to the end of the SmallVector. - template - void append(in_iter in_start, in_iter in_end) { + template + void append(in_iter in_start, in_iter in_end) + { size_type NumInputs = std::distance(in_start, in_end); // Grow allocated space if needed. - if (NumInputs > size_type(this->capacity_ptr()-this->end())) - this->grow(this->size()+NumInputs); + if (NumInputs > size_type(this->capacity_ptr() - this->end())) + this->grow(this->size() + NumInputs); // Copy the new elements over. this->uninitialized_copy(in_start, in_end, this->end()); @@ -423,34 +534,39 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { } /// Add the specified range to the end of the SmallVector. - void append(size_type NumInputs, const T &Elt) { + void append(size_type NumInputs, const T& Elt) + { // Grow allocated space if needed. - if (NumInputs > size_type(this->capacity_ptr()-this->end())) - this->grow(this->size()+NumInputs); + if (NumInputs > size_type(this->capacity_ptr() - this->end())) + this->grow(this->size() + NumInputs); // Copy the new elements over. std::uninitialized_fill_n(this->end(), NumInputs, Elt); this->setEnd(this->end() + NumInputs); } - void append(std::initializer_list IL) { + void append(std::initializer_list IL) + { append(IL.begin(), IL.end()); } - void assign(size_type NumElts, const T &Elt) { + void assign(size_type NumElts, const T& Elt) + { clear(); if (this->capacity() < NumElts) this->grow(NumElts); - this->setEnd(this->begin()+NumElts); + this->setEnd(this->begin() + NumElts); std::uninitialized_fill(this->begin(), this->end(), Elt); } - void assign(std::initializer_list IL) { + void assign(std::initializer_list IL) + { clear(); append(IL); } - iterator erase(const_iterator CI) { + iterator erase(const_iterator CI) + { // Just cast away constness because this is a non-const member function. iterator I = const_cast(CI); @@ -459,13 +575,14 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { iterator N = I; // Shift all elts down one. - std::move(I+1, this->end(), I); + std::move(I + 1, this->end(), I); // Drop the last elt. this->pop_back(); - return(N); + return (N); } - iterator erase(const_iterator CS, const_iterator CE) { + iterator erase(const_iterator CS, const_iterator CE) + { // Just cast away constness because this is a non-const member function. iterator S = const_cast(CS); iterator E = const_cast(CE); @@ -480,32 +597,35 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { // Drop the last elts. this->destroy_range(I, this->end()); this->setEnd(I); - return(N); + return (N); } - iterator insert(iterator I, T &&Elt) { - if (I == this->end()) { // Important special case for empty vector. + iterator insert(iterator I, T&& Elt) + { + if (I == this->end()) + { // Important special case for empty vector. this->push_back(::std::move(Elt)); - return this->end()-1; + return this->end() - 1; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); - if (this->EndX >= this->CapacityX) { - size_t EltNo = I-this->begin(); + if (this->EndX >= this->CapacityX) + { + size_t EltNo = I - this->begin(); this->grow(); - I = this->begin()+EltNo; + I = this->begin() + EltNo; } - ::new ((void*) this->end()) T(::std::move(this->back())); + ::new ((void*)this->end()) T(::std::move(this->back())); // Push everything else over. - std::move_backward(I, this->end()-1, this->end()); - this->setEnd(this->end()+1); + std::move_backward(I, this->end() - 1, this->end()); + this->setEnd(this->end() + 1); // If we just moved the element we're inserting, be sure to update // the reference. - T *EltPtr = &Elt; + T* EltPtr = &Elt; if (I <= EltPtr && EltPtr < this->EndX) ++EltPtr; @@ -513,28 +633,31 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { return I; } - iterator insert(iterator I, const T &Elt) { - if (I == this->end()) { // Important special case for empty vector. + iterator insert(iterator I, const T& Elt) + { + if (I == this->end()) + { // Important special case for empty vector. this->push_back(Elt); - return this->end()-1; + return this->end() - 1; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); assert(I <= this->end() && "Inserting past the end of the vector."); - if (this->EndX >= this->CapacityX) { - size_t EltNo = I-this->begin(); + if (this->EndX >= this->CapacityX) + { + size_t EltNo = I - this->begin(); this->grow(); - I = this->begin()+EltNo; + I = this->begin() + EltNo; } - ::new ((void*) this->end()) T(std::move(this->back())); + ::new ((void*)this->end()) T(std::move(this->back())); // Push everything else over. - std::move_backward(I, this->end()-1, this->end()); - this->setEnd(this->end()+1); + std::move_backward(I, this->end() - 1, this->end()); + this->setEnd(this->end() + 1); // If we just moved the element we're inserting, be sure to update // the reference. - const T *EltPtr = &Elt; + const T* EltPtr = &Elt; if (I <= EltPtr && EltPtr < this->EndX) ++EltPtr; @@ -542,13 +665,15 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { return I; } - iterator insert(iterator I, size_type NumToInsert, const T &Elt) { + iterator insert(iterator I, size_type NumToInsert, const T& Elt) + { // Convert iterator to elt# to avoid invalidating iterator when we reserve() size_t InsertElt = I - this->begin(); - if (I == this->end()) { // Important special case for empty vector. + if (I == this->end()) + { // Important special case for empty vector. append(NumToInsert, Elt); - return this->begin()+InsertElt; + return this->begin() + InsertElt; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); @@ -558,19 +683,20 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { reserve(this->size() + NumToInsert); // Uninvalidate the iterator. - I = this->begin()+InsertElt; + I = this->begin() + InsertElt; // If there are more elements between the insertion point and the end of the // range than there are being inserted, we can use a simple approach to // insertion. Since we already reserved space, we know that this won't // reallocate the vector. - if (size_t(this->end()-I) >= NumToInsert) { - T *OldEnd = this->end(); + if (size_t(this->end() - I) >= NumToInsert) + { + T* OldEnd = this->end(); append(std::move_iterator(this->end() - NumToInsert), std::move_iterator(this->end())); // Copy the existing elements that get replaced. - std::move_backward(I, OldEnd-NumToInsert, OldEnd); + std::move_backward(I, OldEnd - NumToInsert, OldEnd); std::fill_n(I, NumToInsert, Elt); return I; @@ -580,27 +706,29 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { // not inserting at the end. // Move over the elements that we're about to overwrite. - T *OldEnd = this->end(); + T* OldEnd = this->end(); this->setEnd(this->end() + NumToInsert); - size_t NumOverwritten = OldEnd-I; - this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); // Replace the overwritten part. std::fill_n(I, NumOverwritten, Elt); // Insert the non-overwritten middle part. - std::uninitialized_fill_n(OldEnd, NumToInsert-NumOverwritten, Elt); + std::uninitialized_fill_n(OldEnd, NumToInsert - NumOverwritten, Elt); return I; } - template - iterator insert(iterator I, ItTy From, ItTy To) { + template + iterator insert(iterator I, ItTy From, ItTy To) + { // Convert iterator to elt# to avoid invalidating iterator when we reserve() size_t InsertElt = I - this->begin(); - if (I == this->end()) { // Important special case for empty vector. + if (I == this->end()) + { // Important special case for empty vector. append(From, To); - return this->begin()+InsertElt; + return this->begin() + InsertElt; } assert(I >= this->begin() && "Insertion iterator is out of bounds."); @@ -612,19 +740,20 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { reserve(this->size() + NumToInsert); // Uninvalidate the iterator. - I = this->begin()+InsertElt; + I = this->begin() + InsertElt; // If there are more elements between the insertion point and the end of the // range than there are being inserted, we can use a simple approach to // insertion. Since we already reserved space, we know that this won't // reallocate the vector. - if (size_t(this->end()-I) >= NumToInsert) { - T *OldEnd = this->end(); + if (size_t(this->end() - I) >= NumToInsert) + { + T* OldEnd = this->end(); append(std::move_iterator(this->end() - NumToInsert), std::move_iterator(this->end())); // Copy the existing elements that get replaced. - std::move_backward(I, OldEnd-NumToInsert, OldEnd); + std::move_backward(I, OldEnd - NumToInsert, OldEnd); std::copy(From, To, I); return I; @@ -634,15 +763,17 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { // not inserting at the end. // Move over the elements that we're about to overwrite. - T *OldEnd = this->end(); + T* OldEnd = this->end(); this->setEnd(this->end() + NumToInsert); - size_t NumOverwritten = OldEnd-I; - this->uninitialized_move(I, OldEnd, this->end()-NumOverwritten); + size_t NumOverwritten = OldEnd - I; + this->uninitialized_move(I, OldEnd, this->end() - NumOverwritten); // Replace the overwritten part. - for (T *J = I; NumOverwritten > 0; --NumOverwritten) { + for (T* J = I; NumOverwritten > 0; --NumOverwritten) + { *J = *From; - ++J; ++From; + ++J; + ++From; } // Insert the non-overwritten middle part. @@ -650,32 +781,39 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { return I; } - void insert(iterator I, std::initializer_list IL) { + void insert(iterator I, std::initializer_list IL) + { insert(I, IL.begin(), IL.end()); } - template void emplace_back(ArgTypes &&... Args) { + template + void emplace_back(ArgTypes&&... Args) + { if (LLVM_VECSMALL_UNLIKELY(this->EndX >= this->CapacityX)) this->grow(); - ::new ((void *)this->end()) T(std::forward(Args)...); + ::new ((void*)this->end()) T(std::forward(Args)...); this->setEnd(this->end() + 1); } - SmallVectorImpl &operator=(const SmallVectorImpl &RHS); + SmallVectorImpl& operator=(const SmallVectorImpl& RHS); - SmallVectorImpl &operator=(SmallVectorImpl &&RHS); + SmallVectorImpl& operator=(SmallVectorImpl&& RHS); - bool operator==(const SmallVectorImpl &RHS) const { - if (this->size() != RHS.size()) return false; + bool operator==(const SmallVectorImpl& RHS) const + { + if (this->size() != RHS.size()) + return false; return std::equal(this->begin(), this->end(), RHS.begin()); } - bool operator!=(const SmallVectorImpl &RHS) const { + bool operator!=(const SmallVectorImpl& RHS) const + { return !(*this == RHS); } - bool operator<(const SmallVectorImpl &RHS) const { - return std::lexicographical_compare(this->begin(), this->end(), - RHS.begin(), RHS.end()); + bool operator<(const SmallVectorImpl& RHS) const + { + return std::lexicographical_compare(this->begin(), this->end(), RHS.begin(), + RHS.end()); } /// Set the array size to \p N, which the current array must have enough @@ -687,19 +825,22 @@ class SmallVectorImpl : public SmallVectorTemplateBase::value> { /// of the buffer when they know that more elements are available, and only /// update the size later. This avoids the cost of value initializing elements /// which will only be overwritten. - void set_size(size_type N) { + void set_size(size_type N) + { assert(N <= this->capacity()); this->setEnd(this->begin() + N); } }; - template -void SmallVectorImpl::swap(SmallVectorImpl &RHS) { - if (this == &RHS) return; +void SmallVectorImpl::swap(SmallVectorImpl& RHS) +{ + if (this == &RHS) + return; // We can only avoid copying elements if neither vector is small. - if (!this->isSmall() && !RHS.isSmall()) { + if (!this->isSmall() && !RHS.isSmall()) + { std::swap(this->BeginX, RHS.BeginX); std::swap(this->EndX, RHS.EndX); std::swap(this->CapacityX, RHS.CapacityX); @@ -712,41 +853,47 @@ void SmallVectorImpl::swap(SmallVectorImpl &RHS) { // Swap the shared elements. size_t NumShared = this->size(); - if (NumShared > RHS.size()) NumShared = RHS.size(); + if (NumShared > RHS.size()) + NumShared = RHS.size(); for (size_type i = 0; i != NumShared; ++i) std::swap((*this)[i], RHS[i]); // Copy over the extra elts. - if (this->size() > RHS.size()) { + if (this->size() > RHS.size()) + { size_t EltDiff = this->size() - RHS.size(); - this->uninitialized_copy(this->begin()+NumShared, this->end(), RHS.end()); - RHS.setEnd(RHS.end()+EltDiff); - this->destroy_range(this->begin()+NumShared, this->end()); - this->setEnd(this->begin()+NumShared); - } else if (RHS.size() > this->size()) { + this->uninitialized_copy(this->begin() + NumShared, this->end(), RHS.end()); + RHS.setEnd(RHS.end() + EltDiff); + this->destroy_range(this->begin() + NumShared, this->end()); + this->setEnd(this->begin() + NumShared); + } + else if (RHS.size() > this->size()) + { size_t EltDiff = RHS.size() - this->size(); - this->uninitialized_copy(RHS.begin()+NumShared, RHS.end(), this->end()); + this->uninitialized_copy(RHS.begin() + NumShared, RHS.end(), this->end()); this->setEnd(this->end() + EltDiff); - this->destroy_range(RHS.begin()+NumShared, RHS.end()); - RHS.setEnd(RHS.begin()+NumShared); + this->destroy_range(RHS.begin() + NumShared, RHS.end()); + RHS.setEnd(RHS.begin() + NumShared); } } template -SmallVectorImpl &SmallVectorImpl:: - operator=(const SmallVectorImpl &RHS) { +SmallVectorImpl& SmallVectorImpl::operator=(const SmallVectorImpl& RHS) +{ // Avoid self-assignment. - if (this == &RHS) return *this; + if (this == &RHS) + return *this; // If we already have sufficient space, assign the common elements, then // destroy any excess. size_t RHSSize = RHS.size(); size_t CurSize = this->size(); - if (CurSize >= RHSSize) { + if (CurSize >= RHSSize) + { // Assign common elements. iterator NewEnd; if (RHSSize) - NewEnd = std::copy(RHS.begin(), RHS.begin()+RHSSize, this->begin()); + NewEnd = std::copy(RHS.begin(), RHS.begin() + RHSSize, this->begin()); else NewEnd = this->begin(); @@ -761,35 +908,41 @@ SmallVectorImpl &SmallVectorImpl:: // If we have to grow to have enough elements, destroy the current elements. // This allows us to avoid copying them during the grow. // FIXME: don't do this if they're efficiently moveable. - if (this->capacity() < RHSSize) { + if (this->capacity() < RHSSize) + { // Destroy current elements. this->destroy_range(this->begin(), this->end()); this->setEnd(this->begin()); CurSize = 0; this->grow(RHSSize); - } else if (CurSize) { + } + else if (CurSize) + { // Otherwise, use assignment for the already-constructed elements. - std::copy(RHS.begin(), RHS.begin()+CurSize, this->begin()); + std::copy(RHS.begin(), RHS.begin() + CurSize, this->begin()); } // Copy construct the new elements in place. - this->uninitialized_copy(RHS.begin()+CurSize, RHS.end(), - this->begin()+CurSize); + this->uninitialized_copy(RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); // Set end. - this->setEnd(this->begin()+RHSSize); + this->setEnd(this->begin() + RHSSize); return *this; } template -SmallVectorImpl &SmallVectorImpl::operator=(SmallVectorImpl &&RHS) { +SmallVectorImpl& SmallVectorImpl::operator=(SmallVectorImpl&& RHS) +{ // Avoid self-assignment. - if (this == &RHS) return *this; + if (this == &RHS) + return *this; // If the RHS isn't small, clear this vector and then steal its buffer. - if (!RHS.isSmall()) { + if (!RHS.isSmall()) + { this->destroy_range(this->begin(), this->end()); - if (!this->isSmall()) free(this->begin()); + if (!this->isSmall()) + free(this->begin()); this->BeginX = RHS.BeginX; this->EndX = RHS.EndX; this->CapacityX = RHS.CapacityX; @@ -801,7 +954,8 @@ SmallVectorImpl &SmallVectorImpl::operator=(SmallVectorImpl &&RHS) { // destroy any excess. size_t RHSSize = RHS.size(); size_t CurSize = this->size(); - if (CurSize >= RHSSize) { + if (CurSize >= RHSSize) + { // Assign common elements. iterator NewEnd = this->begin(); if (RHSSize) @@ -821,23 +975,25 @@ SmallVectorImpl &SmallVectorImpl::operator=(SmallVectorImpl &&RHS) { // This allows us to avoid copying them during the grow. // FIXME: this may not actually make any sense if we can efficiently move // elements. - if (this->capacity() < RHSSize) { + if (this->capacity() < RHSSize) + { // Destroy current elements. this->destroy_range(this->begin(), this->end()); this->setEnd(this->begin()); CurSize = 0; this->grow(RHSSize); - } else if (CurSize) { + } + else if (CurSize) + { // Otherwise, use assignment for the already-constructed elements. - std::move(RHS.begin(), RHS.begin()+CurSize, this->begin()); + std::move(RHS.begin(), RHS.begin() + CurSize, this->begin()); } // Move-construct the new elements in place. - this->uninitialized_move(RHS.begin()+CurSize, RHS.end(), - this->begin()+CurSize); + this->uninitialized_move(RHS.begin() + CurSize, RHS.end(), this->begin() + CurSize); // Set end. - this->setEnd(this->begin()+RHSSize); + this->setEnd(this->begin() + RHSSize); RHS.clear(); return *this; @@ -848,11 +1004,18 @@ SmallVectorImpl &SmallVectorImpl::operator=(SmallVectorImpl &&RHS) { /// element is in the base class. This is specialized for the N=1 and N=0 cases /// to avoid allocating unnecessary storage. template -struct SmallVectorStorage { +struct SmallVectorStorage +{ typename SmallVectorTemplateCommon::U InlineElts[N - 1]; }; -template struct SmallVectorStorage {}; -template struct SmallVectorStorage {}; +template +struct SmallVectorStorage +{ +}; +template +struct SmallVectorStorage +{ +}; /// This is a 'vector' (really, a variable-sized array), optimized /// for the case when the array is small. It contains some number of elements @@ -863,121 +1026,140 @@ template struct SmallVectorStorage {}; /// Note that this does not attempt to be exception safe. /// template -class SmallVector : public SmallVectorImpl { +class SmallVector : public SmallVectorImpl +{ /// Inline space for elements which aren't stored in the base class. SmallVectorStorage Storage; + public: - SmallVector() : SmallVectorImpl(N) { + SmallVector() : SmallVectorImpl(N) + { } - explicit SmallVector(size_t Size, const T &Value = T()) - : SmallVectorImpl(N) { + explicit SmallVector(size_t Size, const T& Value = T()) : SmallVectorImpl(N) + { this->assign(Size, Value); } - template - SmallVector(ItTy S, ItTy E) : SmallVectorImpl(N) { + template + SmallVector(ItTy S, ItTy E) : SmallVectorImpl(N) + { this->append(S, E); } -/* - template - explicit SmallVector(const llvm_vecsmall::iterator_range &R) - : SmallVectorImpl(N) { - this->append(R.begin(), R.end()); - } -*/ + /* + template + explicit SmallVector(const llvm_vecsmall::iterator_range &R) + : SmallVectorImpl(N) { + this->append(R.begin(), R.end()); + } + */ - SmallVector(std::initializer_list IL) : SmallVectorImpl(N) { + SmallVector(std::initializer_list IL) : SmallVectorImpl(N) + { this->assign(IL); } - SmallVector(const SmallVector &RHS) : SmallVectorImpl(N) { + SmallVector(const SmallVector& RHS) : SmallVectorImpl(N) + { if (!RHS.empty()) SmallVectorImpl::operator=(RHS); } - const SmallVector &operator=(const SmallVector &RHS) { + const SmallVector& operator=(const SmallVector& RHS) + { SmallVectorImpl::operator=(RHS); return *this; } - SmallVector(SmallVector &&RHS) : SmallVectorImpl(N) { + SmallVector(SmallVector&& RHS) : SmallVectorImpl(N) + { if (!RHS.empty()) SmallVectorImpl::operator=(::std::move(RHS)); } - const SmallVector &operator=(SmallVector &&RHS) { + const SmallVector& operator=(SmallVector&& RHS) + { SmallVectorImpl::operator=(::std::move(RHS)); return *this; } - SmallVector(SmallVectorImpl &&RHS) : SmallVectorImpl(N) { + SmallVector(SmallVectorImpl&& RHS) : SmallVectorImpl(N) + { if (!RHS.empty()) SmallVectorImpl::operator=(::std::move(RHS)); } - const SmallVector &operator=(SmallVectorImpl &&RHS) { + const SmallVector& operator=(SmallVectorImpl&& RHS) + { SmallVectorImpl::operator=(::std::move(RHS)); return *this; } - const SmallVector &operator=(std::initializer_list IL) { + const SmallVector& operator=(std::initializer_list IL) + { this->assign(IL); return *this; } }; -template -static inline size_t capacity_in_bytes(const SmallVector &X) { +template +static inline size_t capacity_in_bytes(const SmallVector& X) +{ return X.capacity_in_bytes(); } -} // End llvm_vecsmall namespace +} // namespace llvm_vecsmall -namespace std { - /// Implement std::swap in terms of SmallVector swap. - template - inline void - swap(llvm_vecsmall::SmallVectorImpl &LHS, llvm_vecsmall::SmallVectorImpl &RHS) { - LHS.swap(RHS); - } +namespace std +{ +/// Implement std::swap in terms of SmallVector swap. +template +inline void swap(llvm_vecsmall::SmallVectorImpl& LHS, + llvm_vecsmall::SmallVectorImpl& RHS) +{ + LHS.swap(RHS); +} - /// Implement std::swap in terms of SmallVector swap. - template - inline void - swap(llvm_vecsmall::SmallVector &LHS, llvm_vecsmall::SmallVector &RHS) { - LHS.swap(RHS); - } +/// Implement std::swap in terms of SmallVector swap. +template +inline void swap(llvm_vecsmall::SmallVector& LHS, + llvm_vecsmall::SmallVector& RHS) +{ + LHS.swap(RHS); } +} // namespace std -namespace llvm_vecsmall { +namespace llvm_vecsmall +{ /// grow_pod - This is an implementation of the grow() method which only works /// on POD-like datatypes and is out of line to reduce code duplication. -inline -void SmallVectorBase::grow_pod(void *FirstEl, size_t MinSizeInBytes, - size_t TSize) { +inline void SmallVectorBase::grow_pod(void* FirstEl, size_t MinSizeInBytes, size_t TSize) +{ size_t CurSizeBytes = size_in_bytes(); - size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow. + size_t NewCapacityInBytes = 2 * capacity_in_bytes() + TSize; // Always grow. if (NewCapacityInBytes < MinSizeInBytes) NewCapacityInBytes = MinSizeInBytes; - void *NewElts; - if (BeginX == FirstEl) { + void* NewElts; + if (BeginX == FirstEl) + { NewElts = malloc(NewCapacityInBytes); // Copy the elements over. No need to run dtors on PODs. memcpy(NewElts, this->BeginX, CurSizeBytes); - } else { + } + else + { // If this wasn't grown from the inline copy, grow the allocated space. NewElts = realloc(this->BeginX, NewCapacityInBytes); } assert(NewElts && "Out of memory"); - this->EndX = (char*)NewElts+CurSizeBytes; + this->EndX = (char*)NewElts + CurSizeBytes; this->BeginX = NewElts; this->CapacityX = (char*)this->BeginX + NewCapacityInBytes; } -} +} // namespace llvm_vecsmall #endif diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/span.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/span.hpp index e200da4d0..ad29b2549 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/span.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/contrib/span.hpp @@ -11,47 +11,49 @@ #ifndef NONSTD_SPAN_HPP_INCLUDED #define NONSTD_SPAN_HPP_INCLUDED -#define span_lite_MAJOR 0 -#define span_lite_MINOR 10 -#define span_lite_PATCH 3 +#define span_lite_MAJOR 0 +#define span_lite_MINOR 10 +#define span_lite_PATCH 3 -#define span_lite_VERSION span_STRINGIFY(span_lite_MAJOR) "." span_STRINGIFY(span_lite_MINOR) "." span_STRINGIFY(span_lite_PATCH) +#define span_lite_VERSION \ + span_STRINGIFY(span_lite_MAJOR) "." span_STRINGIFY( \ + span_lite_MINOR) "." span_STRINGIFY(span_lite_PATCH) -#define span_STRINGIFY( x ) span_STRINGIFY_( x ) -#define span_STRINGIFY_( x ) #x +#define span_STRINGIFY(x) span_STRINGIFY_(x) +#define span_STRINGIFY_(x) #x // span configuration: -#define span_SPAN_DEFAULT 0 -#define span_SPAN_NONSTD 1 -#define span_SPAN_STD 2 +#define span_SPAN_DEFAULT 0 +#define span_SPAN_NONSTD 1 +#define span_SPAN_STD 2 // tweak header support: #ifdef __has_include -# if __has_include() -# include -# endif -#define span_HAVE_TWEAK_HEADER 1 +#if __has_include() +#include +#endif +#define span_HAVE_TWEAK_HEADER 1 #else -#define span_HAVE_TWEAK_HEADER 0 +#define span_HAVE_TWEAK_HEADER 0 //# pragma message("span.hpp: Note: Tweak header not supported.") #endif // span selection and configuration: -#define span_HAVE( feature ) ( span_HAVE_##feature ) +#define span_HAVE(feature) (span_HAVE_##feature) -#ifndef span_CONFIG_SELECT_SPAN -# define span_CONFIG_SELECT_SPAN ( span_HAVE_STD_SPAN ? span_SPAN_STD : span_SPAN_NONSTD ) +#ifndef span_CONFIG_SELECT_SPAN +#define span_CONFIG_SELECT_SPAN (span_HAVE_STD_SPAN ? span_SPAN_STD : span_SPAN_NONSTD) #endif -#ifndef span_CONFIG_EXTENT_TYPE -# define span_CONFIG_EXTENT_TYPE std::size_t +#ifndef span_CONFIG_EXTENT_TYPE +#define span_CONFIG_EXTENT_TYPE std::size_t #endif -#ifndef span_CONFIG_SIZE_TYPE -# define span_CONFIG_SIZE_TYPE std::size_t +#ifndef span_CONFIG_SIZE_TYPE +#define span_CONFIG_SIZE_TYPE std::size_t #endif #ifdef span_CONFIG_INDEX_TYPE @@ -60,157 +62,161 @@ // span configuration (features): -#ifndef span_FEATURE_WITH_CONTAINER -#ifdef span_FEATURE_WITH_CONTAINER_TO_STD -# define span_FEATURE_WITH_CONTAINER span_IN_STD( span_FEATURE_WITH_CONTAINER_TO_STD ) +#ifndef span_FEATURE_WITH_CONTAINER +#ifdef span_FEATURE_WITH_CONTAINER_TO_STD +#define span_FEATURE_WITH_CONTAINER span_IN_STD(span_FEATURE_WITH_CONTAINER_TO_STD) #else -# define span_FEATURE_WITH_CONTAINER 0 -# define span_FEATURE_WITH_CONTAINER_TO_STD 0 +#define span_FEATURE_WITH_CONTAINER 0 +#define span_FEATURE_WITH_CONTAINER_TO_STD 0 #endif #endif -#ifndef span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE -# define span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE 0 +#ifndef span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE +#define span_FEATURE_CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE 0 #endif -#ifndef span_FEATURE_MEMBER_AT -# define span_FEATURE_MEMBER_AT 0 +#ifndef span_FEATURE_MEMBER_AT +#define span_FEATURE_MEMBER_AT 0 #endif -#ifndef span_FEATURE_MEMBER_BACK_FRONT -# define span_FEATURE_MEMBER_BACK_FRONT 1 +#ifndef span_FEATURE_MEMBER_BACK_FRONT +#define span_FEATURE_MEMBER_BACK_FRONT 1 #endif -#ifndef span_FEATURE_MEMBER_CALL_OPERATOR -# define span_FEATURE_MEMBER_CALL_OPERATOR 0 +#ifndef span_FEATURE_MEMBER_CALL_OPERATOR +#define span_FEATURE_MEMBER_CALL_OPERATOR 0 #endif -#ifndef span_FEATURE_MEMBER_SWAP -# define span_FEATURE_MEMBER_SWAP 0 +#ifndef span_FEATURE_MEMBER_SWAP +#define span_FEATURE_MEMBER_SWAP 0 #endif -#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB -# define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB 0 -#elif span_FEATURE_NON_MEMBER_FIRST_LAST_SUB -# define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 1 -# define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 1 +#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB +#define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB 0 +#elif span_FEATURE_NON_MEMBER_FIRST_LAST_SUB +#define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 1 +#define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 1 #endif -#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN -# define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 0 +#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN +#define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_SPAN 0 #endif -#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER -# define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 0 +#ifndef span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER +#define span_FEATURE_NON_MEMBER_FIRST_LAST_SUB_CONTAINER 0 #endif -#ifndef span_FEATURE_COMPARISON -# define span_FEATURE_COMPARISON 0 // Note: C++20 does not provide comparison +#ifndef span_FEATURE_COMPARISON +#define span_FEATURE_COMPARISON 0 // Note: C++20 does not provide comparison #endif -#ifndef span_FEATURE_SAME -# define span_FEATURE_SAME 0 +#ifndef span_FEATURE_SAME +#define span_FEATURE_SAME 0 #endif #if span_FEATURE_SAME && !span_FEATURE_COMPARISON -# error `span_FEATURE_SAME` requires `span_FEATURE_COMPARISON` +#error `span_FEATURE_SAME` requires `span_FEATURE_COMPARISON` #endif -#ifndef span_FEATURE_MAKE_SPAN -#ifdef span_FEATURE_MAKE_SPAN_TO_STD -# define span_FEATURE_MAKE_SPAN span_IN_STD( span_FEATURE_MAKE_SPAN_TO_STD ) +#ifndef span_FEATURE_MAKE_SPAN +#ifdef span_FEATURE_MAKE_SPAN_TO_STD +#define span_FEATURE_MAKE_SPAN span_IN_STD(span_FEATURE_MAKE_SPAN_TO_STD) #else -# define span_FEATURE_MAKE_SPAN 0 -# define span_FEATURE_MAKE_SPAN_TO_STD 0 +#define span_FEATURE_MAKE_SPAN 0 +#define span_FEATURE_MAKE_SPAN_TO_STD 0 #endif #endif -#ifndef span_FEATURE_BYTE_SPAN -# define span_FEATURE_BYTE_SPAN 0 +#ifndef span_FEATURE_BYTE_SPAN +#define span_FEATURE_BYTE_SPAN 0 #endif // Control presence of exception handling (try and auto discover): #ifndef span_CONFIG_NO_EXCEPTIONS -# if defined(_MSC_VER) -# include // for _HAS_EXCEPTIONS -# endif -# if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (_HAS_EXCEPTIONS) -# define span_CONFIG_NO_EXCEPTIONS 0 -# else -# define span_CONFIG_NO_EXCEPTIONS 1 -# undef span_CONFIG_CONTRACT_VIOLATION_THROWS -# undef span_CONFIG_CONTRACT_VIOLATION_TERMINATES -# define span_CONFIG_CONTRACT_VIOLATION_THROWS 0 -# define span_CONFIG_CONTRACT_VIOLATION_TERMINATES 1 -# endif +#if defined(_MSC_VER) +#include // for _HAS_EXCEPTIONS +#endif +#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || (_HAS_EXCEPTIONS) +#define span_CONFIG_NO_EXCEPTIONS 0 +#else +#define span_CONFIG_NO_EXCEPTIONS 1 +#undef span_CONFIG_CONTRACT_VIOLATION_THROWS +#undef span_CONFIG_CONTRACT_VIOLATION_TERMINATES +#define span_CONFIG_CONTRACT_VIOLATION_THROWS 0 +#define span_CONFIG_CONTRACT_VIOLATION_TERMINATES 1 +#endif #endif // Control pre- and postcondition violation behaviour: -#if defined( span_CONFIG_CONTRACT_LEVEL_ON ) -# define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 -#elif defined( span_CONFIG_CONTRACT_LEVEL_OFF ) -# define span_CONFIG_CONTRACT_LEVEL_MASK 0x00 -#elif defined( span_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY ) -# define span_CONFIG_CONTRACT_LEVEL_MASK 0x01 -#elif defined( span_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY ) -# define span_CONFIG_CONTRACT_LEVEL_MASK 0x10 +#if defined(span_CONFIG_CONTRACT_LEVEL_ON) +#define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 +#elif defined(span_CONFIG_CONTRACT_LEVEL_OFF) +#define span_CONFIG_CONTRACT_LEVEL_MASK 0x00 +#elif defined(span_CONFIG_CONTRACT_LEVEL_EXPECTS_ONLY) +#define span_CONFIG_CONTRACT_LEVEL_MASK 0x01 +#elif defined(span_CONFIG_CONTRACT_LEVEL_ENSURES_ONLY) +#define span_CONFIG_CONTRACT_LEVEL_MASK 0x10 #else -# define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 +#define span_CONFIG_CONTRACT_LEVEL_MASK 0x11 #endif -#if defined( span_CONFIG_CONTRACT_VIOLATION_THROWS ) -# define span_CONFIG_CONTRACT_VIOLATION_THROWS_V span_CONFIG_CONTRACT_VIOLATION_THROWS +#if defined(span_CONFIG_CONTRACT_VIOLATION_THROWS) +#define span_CONFIG_CONTRACT_VIOLATION_THROWS_V span_CONFIG_CONTRACT_VIOLATION_THROWS #else -# define span_CONFIG_CONTRACT_VIOLATION_THROWS_V 0 +#define span_CONFIG_CONTRACT_VIOLATION_THROWS_V 0 #endif -#if defined( span_CONFIG_CONTRACT_VIOLATION_THROWS ) && span_CONFIG_CONTRACT_VIOLATION_THROWS && \ - defined( span_CONFIG_CONTRACT_VIOLATION_TERMINATES ) && span_CONFIG_CONTRACT_VIOLATION_TERMINATES +#if defined(span_CONFIG_CONTRACT_VIOLATION_THROWS) && \ + span_CONFIG_CONTRACT_VIOLATION_THROWS && \ + defined(span_CONFIG_CONTRACT_VIOLATION_TERMINATES) && \ + span_CONFIG_CONTRACT_VIOLATION_TERMINATES # error Please define none or one of span_CONFIG_CONTRACT_VIOLATION_THROWS and span_CONFIG_CONTRACT_VIOLATION_TERMINATES to 1, but not both. #endif // C++ language version detection (C++20 is speculative): // Note: VC14.0/1900 (VS2015) lacks too much from C++14. -#ifndef span_CPLUSPLUS -# if defined(_MSVC_LANG ) && !defined(__clang__) -# define span_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG ) -# else -# define span_CPLUSPLUS __cplusplus -# endif +#ifndef span_CPLUSPLUS +#if defined(_MSVC_LANG) && !defined(__clang__) +#define span_CPLUSPLUS (_MSC_VER == 1900 ? 201103L : _MSVC_LANG) +#else +#define span_CPLUSPLUS __cplusplus +#endif #endif -#define span_CPP98_OR_GREATER ( span_CPLUSPLUS >= 199711L ) -#define span_CPP11_OR_GREATER ( span_CPLUSPLUS >= 201103L ) -#define span_CPP14_OR_GREATER ( span_CPLUSPLUS >= 201402L ) -#define span_CPP17_OR_GREATER ( span_CPLUSPLUS >= 201703L ) -#define span_CPP20_OR_GREATER ( span_CPLUSPLUS >= 202000L ) +#define span_CPP98_OR_GREATER (span_CPLUSPLUS >= 199711L) +#define span_CPP11_OR_GREATER (span_CPLUSPLUS >= 201103L) +#define span_CPP14_OR_GREATER (span_CPLUSPLUS >= 201402L) +#define span_CPP17_OR_GREATER (span_CPLUSPLUS >= 201703L) +#define span_CPP20_OR_GREATER (span_CPLUSPLUS >= 202000L) // C++ language version (represent 98 as 3): -#define span_CPLUSPLUS_V ( span_CPLUSPLUS / 100 - (span_CPLUSPLUS > 200000 ? 2000 : 1994) ) +#define span_CPLUSPLUS_V (span_CPLUSPLUS / 100 - (span_CPLUSPLUS > 200000 ? 2000 : 1994)) -#define span_IN_STD( v ) ( ((v) == 98 ? 3 : (v)) >= span_CPLUSPLUS_V ) +#define span_IN_STD(v) (((v) == 98 ? 3 : (v)) >= span_CPLUSPLUS_V) -#define span_CONFIG( feature ) ( span_CONFIG_##feature ) -#define span_FEATURE( feature ) ( span_FEATURE_##feature ) -#define span_FEATURE_TO_STD( feature ) ( span_IN_STD( span_FEATURE( feature##_TO_STD ) ) ) +#define span_CONFIG(feature) (span_CONFIG_##feature) +#define span_FEATURE(feature) (span_FEATURE_##feature) +#define span_FEATURE_TO_STD(feature) (span_IN_STD(span_FEATURE(feature##_TO_STD))) // Use C++20 std::span if available and requested: -#if span_CPP20_OR_GREATER && defined(__has_include ) -# if __has_include( ) -# define span_HAVE_STD_SPAN 1 -# else -# define span_HAVE_STD_SPAN 0 -# endif +#if span_CPP20_OR_GREATER && defined(__has_include) +#if __has_include( ) +#define span_HAVE_STD_SPAN 1 +#else +#define span_HAVE_STD_SPAN 0 +#endif #else -# define span_HAVE_STD_SPAN 0 +#define span_HAVE_STD_SPAN 0 #endif -#define span_USES_STD_SPAN ( (span_CONFIG_SELECT_SPAN == span_SPAN_STD) || ((span_CONFIG_SELECT_SPAN == span_SPAN_DEFAULT) && span_HAVE_STD_SPAN) ) +#define span_USES_STD_SPAN \ + ((span_CONFIG_SELECT_SPAN == span_SPAN_STD) || \ + ((span_CONFIG_SELECT_SPAN == span_SPAN_DEFAULT) && span_HAVE_STD_SPAN)) // // Use C++20 std::span: @@ -220,7 +226,8 @@ #include -namespace nonstd { +namespace nonstd +{ using std::span; @@ -240,1257 +247,1319 @@ using std::span; // Compiler versions: // // MSVC++ 6.0 _MSC_VER == 1200 span_COMPILER_MSVC_VERSION == 60 (Visual Studio 6.0) -// MSVC++ 7.0 _MSC_VER == 1300 span_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET 2002) -// MSVC++ 7.1 _MSC_VER == 1310 span_COMPILER_MSVC_VERSION == 71 (Visual Studio .NET 2003) -// MSVC++ 8.0 _MSC_VER == 1400 span_COMPILER_MSVC_VERSION == 80 (Visual Studio 2005) -// MSVC++ 9.0 _MSC_VER == 1500 span_COMPILER_MSVC_VERSION == 90 (Visual Studio 2008) -// MSVC++ 10.0 _MSC_VER == 1600 span_COMPILER_MSVC_VERSION == 100 (Visual Studio 2010) -// MSVC++ 11.0 _MSC_VER == 1700 span_COMPILER_MSVC_VERSION == 110 (Visual Studio 2012) -// MSVC++ 12.0 _MSC_VER == 1800 span_COMPILER_MSVC_VERSION == 120 (Visual Studio 2013) -// MSVC++ 14.0 _MSC_VER == 1900 span_COMPILER_MSVC_VERSION == 140 (Visual Studio 2015) -// MSVC++ 14.1 _MSC_VER >= 1910 span_COMPILER_MSVC_VERSION == 141 (Visual Studio 2017) -// MSVC++ 14.2 _MSC_VER >= 1920 span_COMPILER_MSVC_VERSION == 142 (Visual Studio 2019) - -#if defined(_MSC_VER ) && !defined(__clang__) -# define span_COMPILER_MSVC_VER (_MSC_VER ) -# define span_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * ( 5 + (_MSC_VER < 1900 ) ) ) +// MSVC++ 7.0 _MSC_VER == 1300 span_COMPILER_MSVC_VERSION == 70 (Visual Studio .NET +// 2002) MSVC++ 7.1 _MSC_VER == 1310 span_COMPILER_MSVC_VERSION == 71 (Visual Studio +// .NET 2003) MSVC++ 8.0 _MSC_VER == 1400 span_COMPILER_MSVC_VERSION == 80 (Visual +// Studio 2005) MSVC++ 9.0 _MSC_VER == 1500 span_COMPILER_MSVC_VERSION == 90 (Visual +// Studio 2008) MSVC++ 10.0 _MSC_VER == 1600 span_COMPILER_MSVC_VERSION == 100 (Visual +// Studio 2010) MSVC++ 11.0 _MSC_VER == 1700 span_COMPILER_MSVC_VERSION == 110 (Visual +// Studio 2012) MSVC++ 12.0 _MSC_VER == 1800 span_COMPILER_MSVC_VERSION == 120 (Visual +// Studio 2013) MSVC++ 14.0 _MSC_VER == 1900 span_COMPILER_MSVC_VERSION == 140 (Visual +// Studio 2015) MSVC++ 14.1 _MSC_VER >= 1910 span_COMPILER_MSVC_VERSION == 141 (Visual +// Studio 2017) MSVC++ 14.2 _MSC_VER >= 1920 span_COMPILER_MSVC_VERSION == 142 (Visual +// Studio 2019) + +#if defined(_MSC_VER) && !defined(__clang__) +#define span_COMPILER_MSVC_VER (_MSC_VER) +#define span_COMPILER_MSVC_VERSION (_MSC_VER / 10 - 10 * (5 + (_MSC_VER < 1900))) #else -# define span_COMPILER_MSVC_VER 0 -# define span_COMPILER_MSVC_VERSION 0 +#define span_COMPILER_MSVC_VER 0 +#define span_COMPILER_MSVC_VERSION 0 #endif -#define span_COMPILER_VERSION( major, minor, patch ) ( 10 * ( 10 * (major) + (minor) ) + (patch) ) +#define span_COMPILER_VERSION(major, minor, patch) \ + (10 * (10 * (major) + (minor)) + (patch)) #if defined(__clang__) -# define span_COMPILER_CLANG_VERSION span_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) +#define span_COMPILER_CLANG_VERSION \ + span_COMPILER_VERSION(__clang_major__, __clang_minor__, __clang_patchlevel__) #else -# define span_COMPILER_CLANG_VERSION 0 +#define span_COMPILER_CLANG_VERSION 0 #endif #if defined(__GNUC__) && !defined(__clang__) -# define span_COMPILER_GNUC_VERSION span_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#define span_COMPILER_GNUC_VERSION \ + span_COMPILER_VERSION(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) #else -# define span_COMPILER_GNUC_VERSION 0 +#define span_COMPILER_GNUC_VERSION 0 #endif // half-open range [lo..hi): -#define span_BETWEEN( v, lo, hi ) ( (lo) <= (v) && (v) < (hi) ) +#define span_BETWEEN(v, lo, hi) ((lo) <= (v) && (v) < (hi)) // Compiler warning suppression: #if defined(__clang__) -# pragma clang diagnostic push -# pragma clang diagnostic ignored "-Wundef" -# pragma clang diagnostic ignored "-Wmismatched-tags" -# define span_RESTORE_WARNINGS() _Pragma( "clang diagnostic pop" ) +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wundef" +#pragma clang diagnostic ignored "-Wmismatched-tags" +#define span_RESTORE_WARNINGS() _Pragma("clang diagnostic pop") #elif defined __GNUC__ -# pragma GCC diagnostic push -# pragma GCC diagnostic ignored "-Wundef" -# define span_RESTORE_WARNINGS() _Pragma( "GCC diagnostic pop" ) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wundef" +#define span_RESTORE_WARNINGS() _Pragma("GCC diagnostic pop") #elif span_COMPILER_MSVC_VER >= 1900 -# define span_DISABLE_MSVC_WARNINGS(codes) __pragma(warning(push)) __pragma(warning(disable: codes)) -# define span_RESTORE_WARNINGS() __pragma(warning(pop )) +#define span_DISABLE_MSVC_WARNINGS(codes) \ + __pragma(warning(push)) __pragma(warning(disable : codes)) +#define span_RESTORE_WARNINGS() __pragma(warning(pop)) // Suppress the following MSVC GSL warnings: // - C26439, gsl::f.6 : special function 'function' can be declared 'noexcept' // - C26440, gsl::f.6 : function 'function' can be declared 'noexcept' // - C26472, gsl::t.1 : don't use a static_cast for arithmetic conversions; // use brace initialization, gsl::narrow_cast or gsl::narrow -// - C26473: gsl::t.1 : don't cast between pointer types where the source type and the target type are the same +// - C26473: gsl::t.1 : don't cast between pointer types where the source type and the +// target type are the same // - C26481: gsl::b.1 : don't use pointer arithmetic. Use span instead // - C26490: gsl::t.1 : don't use reinterpret_cast -span_DISABLE_MSVC_WARNINGS( 26439 26440 26472 26473 26481 26490 ) +span_DISABLE_MSVC_WARNINGS(26439 26440 26472 26473 26481 26490) #else -# define span_RESTORE_WARNINGS() /*empty*/ +#define span_RESTORE_WARNINGS() /*empty*/ #endif // Presence of language and library features: #ifdef _HAS_CPP0X -# define span_HAS_CPP0X _HAS_CPP0X +#define span_HAS_CPP0X _HAS_CPP0X #else -# define span_HAS_CPP0X 0 +#define span_HAS_CPP0X 0 #endif -#define span_CPP11_80 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1400) -#define span_CPP11_90 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1500) -#define span_CPP11_100 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1600) -#define span_CPP11_110 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1700) -#define span_CPP11_120 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) -#define span_CPP11_140 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) +#define span_CPP11_80 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1400) +#define span_CPP11_90 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1500) +#define span_CPP11_100 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1600) +#define span_CPP11_110 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1700) +#define span_CPP11_120 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) +#define span_CPP11_140 (span_CPP11_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) -#define span_CPP14_000 (span_CPP14_OR_GREATER) -#define span_CPP14_120 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) -#define span_CPP14_140 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) +#define span_CPP14_000 (span_CPP14_OR_GREATER) +#define span_CPP14_120 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1800) +#define span_CPP14_140 (span_CPP14_OR_GREATER || span_COMPILER_MSVC_VER >= 1900) -#define span_CPP17_000 (span_CPP17_OR_GREATER) +#define span_CPP17_000 (span_CPP17_OR_GREATER) // Presence of C++11 language features: -#define span_HAVE_ALIAS_TEMPLATE span_CPP11_140 -#define span_HAVE_AUTO span_CPP11_100 -#define span_HAVE_CONSTEXPR_11 span_CPP11_140 -#define span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG span_CPP11_120 -#define span_HAVE_EXPLICIT_CONVERSION span_CPP11_140 -#define span_HAVE_INITIALIZER_LIST span_CPP11_120 -#define span_HAVE_IS_DEFAULT span_CPP11_140 -#define span_HAVE_IS_DELETE span_CPP11_140 -#define span_HAVE_NOEXCEPT span_CPP11_140 -#define span_HAVE_NULLPTR span_CPP11_100 -#define span_HAVE_STATIC_ASSERT span_CPP11_100 +#define span_HAVE_ALIAS_TEMPLATE span_CPP11_140 +#define span_HAVE_AUTO span_CPP11_100 +#define span_HAVE_CONSTEXPR_11 span_CPP11_140 +#define span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG span_CPP11_120 +#define span_HAVE_EXPLICIT_CONVERSION span_CPP11_140 +#define span_HAVE_INITIALIZER_LIST span_CPP11_120 +#define span_HAVE_IS_DEFAULT span_CPP11_140 +#define span_HAVE_IS_DELETE span_CPP11_140 +#define span_HAVE_NOEXCEPT span_CPP11_140 +#define span_HAVE_NULLPTR span_CPP11_100 +#define span_HAVE_STATIC_ASSERT span_CPP11_100 // Presence of C++14 language features: -#define span_HAVE_CONSTEXPR_14 span_CPP14_000 +#define span_HAVE_CONSTEXPR_14 span_CPP14_000 // Presence of C++17 language features: -#define span_HAVE_DEPRECATED span_CPP17_000 -#define span_HAVE_NODISCARD span_CPP17_000 -#define span_HAVE_NORETURN span_CPP17_000 +#define span_HAVE_DEPRECATED span_CPP17_000 +#define span_HAVE_NODISCARD span_CPP17_000 +#define span_HAVE_NORETURN span_CPP17_000 // MSVC: template parameter deduction guides since Visual Studio 2017 v15.7 #if defined(__cpp_deduction_guides) -# define span_HAVE_DEDUCTION_GUIDES 1 +#define span_HAVE_DEDUCTION_GUIDES 1 #else -# define span_HAVE_DEDUCTION_GUIDES (span_CPP17_OR_GREATER && ! span_BETWEEN( span_COMPILER_MSVC_VER, 1, 1913 )) +#define span_HAVE_DEDUCTION_GUIDES \ + (span_CPP17_OR_GREATER && !span_BETWEEN(span_COMPILER_MSVC_VER, 1, 1913)) #endif // Presence of C++ library features: -#define span_HAVE_ADDRESSOF span_CPP17_000 -#define span_HAVE_ARRAY span_CPP11_110 -#define span_HAVE_BYTE span_CPP17_000 -#define span_HAVE_CONDITIONAL span_CPP11_120 -#define span_HAVE_CONTAINER_DATA_METHOD (span_CPP11_140 || ( span_COMPILER_MSVC_VER >= 1500 && span_HAS_CPP0X )) -#define span_HAVE_DATA span_CPP17_000 -#define span_HAVE_LONGLONG span_CPP11_80 -#define span_HAVE_REMOVE_CONST span_CPP11_110 -#define span_HAVE_SNPRINTF span_CPP11_140 -#define span_HAVE_STRUCT_BINDING span_CPP11_120 -#define span_HAVE_TYPE_TRAITS span_CPP11_90 +#define span_HAVE_ADDRESSOF span_CPP17_000 +#define span_HAVE_ARRAY span_CPP11_110 +#define span_HAVE_BYTE span_CPP17_000 +#define span_HAVE_CONDITIONAL span_CPP11_120 +#define span_HAVE_CONTAINER_DATA_METHOD \ + (span_CPP11_140 || (span_COMPILER_MSVC_VER >= 1500 && span_HAS_CPP0X)) +#define span_HAVE_DATA span_CPP17_000 +#define span_HAVE_LONGLONG span_CPP11_80 +#define span_HAVE_REMOVE_CONST span_CPP11_110 +#define span_HAVE_SNPRINTF span_CPP11_140 +#define span_HAVE_STRUCT_BINDING span_CPP11_120 +#define span_HAVE_TYPE_TRAITS span_CPP11_90 // Presence of byte-lite: #ifdef NONSTD_BYTE_LITE_HPP -# define span_HAVE_NONSTD_BYTE 1 +#define span_HAVE_NONSTD_BYTE 1 #else -# define span_HAVE_NONSTD_BYTE 0 +#define span_HAVE_NONSTD_BYTE 0 #endif // C++ feature usage: #if span_HAVE_ADDRESSOF -# define span_ADDRESSOF(x) std::addressof(x) +#define span_ADDRESSOF(x) std::addressof(x) #else -# define span_ADDRESSOF(x) (&x) +#define span_ADDRESSOF(x) (&x) #endif #if span_HAVE_CONSTEXPR_11 -# define span_constexpr constexpr +#define span_constexpr constexpr #else -# define span_constexpr /*span_constexpr*/ +#define span_constexpr /*span_constexpr*/ #endif #if span_HAVE_CONSTEXPR_14 -# define span_constexpr14 constexpr +#define span_constexpr14 constexpr #else -# define span_constexpr14 /*span_constexpr*/ +#define span_constexpr14 /*span_constexpr*/ #endif #if span_HAVE_EXPLICIT_CONVERSION -# define span_explicit explicit +#define span_explicit explicit #else -# define span_explicit /*explicit*/ +#define span_explicit /*explicit*/ #endif #if span_HAVE_IS_DELETE -# define span_is_delete = delete +#define span_is_delete = delete #else -# define span_is_delete +#define span_is_delete #endif #if span_HAVE_IS_DELETE -# define span_is_delete_access public +#define span_is_delete_access public #else -# define span_is_delete_access private +#define span_is_delete_access private #endif -#if span_HAVE_NOEXCEPT && ! span_CONFIG_CONTRACT_VIOLATION_THROWS_V -# define span_noexcept noexcept +#if span_HAVE_NOEXCEPT && !span_CONFIG_CONTRACT_VIOLATION_THROWS_V +#define span_noexcept noexcept #else -# define span_noexcept /*noexcept*/ +#define span_noexcept /*noexcept*/ #endif #if span_HAVE_NULLPTR -# define span_nullptr nullptr +#define span_nullptr nullptr #else -# define span_nullptr NULL +#define span_nullptr NULL #endif #if span_HAVE_DEPRECATED -# define span_deprecated(msg) [[deprecated(msg)]] +#define span_deprecated(msg) [[deprecated(msg)]] #else -# define span_deprecated(msg) /*[[deprecated]]*/ +#define span_deprecated(msg) /*[[deprecated]]*/ #endif #if span_HAVE_NODISCARD -# define span_nodiscard [[nodiscard]] +#define span_nodiscard [[nodiscard]] #else -# define span_nodiscard /*[[nodiscard]]*/ +#define span_nodiscard /*[[nodiscard]]*/ #endif #if span_HAVE_NORETURN -# define span_noreturn [[noreturn]] +#define span_noreturn [[noreturn]] #else -# define span_noreturn /*[[noreturn]]*/ +#define span_noreturn /*[[noreturn]]*/ #endif // Other features: -#define span_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG -#define span_HAVE_ITERATOR_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG +#define span_HAVE_CONSTRAINED_SPAN_CONTAINER_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG +#define span_HAVE_ITERATOR_CTOR span_HAVE_DEFAULT_FUNCTION_TEMPLATE_ARG // Additional includes: -#if span_HAVE( ADDRESSOF ) -# include +#if span_HAVE(ADDRESSOF) +#include #endif -#if span_HAVE( ARRAY ) -# include +#if span_HAVE(ARRAY) +#include #endif -#if span_HAVE( BYTE ) -# include +#if span_HAVE(BYTE) +#include #endif -#if span_HAVE( DATA ) -# include // for std::data(), std::size() +#if span_HAVE(DATA) +#include // for std::data(), std::size() #endif -#if span_HAVE( TYPE_TRAITS ) -# include +#if span_HAVE(TYPE_TRAITS) +#include #endif -#if ! span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) -# include +#if !span_HAVE(CONSTRAINED_SPAN_CONTAINER_CTOR) +#include #endif -#if span_FEATURE( MEMBER_AT ) > 1 -# include +#if span_FEATURE(MEMBER_AT) > 1 +#include #endif -#if ! span_CONFIG( NO_EXCEPTIONS ) -# include +#if !span_CONFIG(NO_EXCEPTIONS) +#include #endif // Contract violation -#define span_ELIDE_CONTRACT_EXPECTS ( 0 == ( span_CONFIG_CONTRACT_LEVEL_MASK & 0x01 ) ) -#define span_ELIDE_CONTRACT_ENSURES ( 0 == ( span_CONFIG_CONTRACT_LEVEL_MASK & 0x10 ) ) +#define span_ELIDE_CONTRACT_EXPECTS (0 == (span_CONFIG_CONTRACT_LEVEL_MASK & 0x01)) +#define span_ELIDE_CONTRACT_ENSURES (0 == (span_CONFIG_CONTRACT_LEVEL_MASK & 0x10)) #if span_ELIDE_CONTRACT_EXPECTS -# define span_constexpr_exp span_constexpr -# define span_EXPECTS( cond ) /* Expect elided */ +#define span_constexpr_exp span_constexpr +#define span_EXPECTS(cond) /* Expect elided */ #else -# define span_constexpr_exp span_constexpr14 -# define span_EXPECTS( cond ) span_CONTRACT_CHECK( "Precondition", cond ) +#define span_constexpr_exp span_constexpr14 +#define span_EXPECTS(cond) span_CONTRACT_CHECK("Precondition", cond) #endif #if span_ELIDE_CONTRACT_ENSURES -# define span_constexpr_ens span_constexpr -# define span_ENSURES( cond ) /* Ensures elided */ +#define span_constexpr_ens span_constexpr +#define span_ENSURES(cond) /* Ensures elided */ #else -# define span_constexpr_ens span_constexpr14 -# define span_ENSURES( cond ) span_CONTRACT_CHECK( "Postcondition", cond ) +#define span_constexpr_ens span_constexpr14 +#define span_ENSURES(cond) span_CONTRACT_CHECK("Postcondition", cond) #endif -#define span_CONTRACT_CHECK( type, cond ) \ - cond ? static_cast< void >( 0 ) \ - : nonstd::span_lite::detail::report_contract_violation( span_LOCATION( __FILE__, __LINE__ ) ": " type " violation." ) +#define span_CONTRACT_CHECK(type, cond) \ + cond ? static_cast(0) : \ + nonstd::span_lite::detail::report_contract_violation( \ + span_LOCATION(__FILE__, __LINE__) ": " type " violation.") #ifdef __GNUG__ -# define span_LOCATION( file, line ) file ":" span_STRINGIFY( line ) +#define span_LOCATION(file, line) file ":" span_STRINGIFY(line) #else -# define span_LOCATION( file, line ) file "(" span_STRINGIFY( line ) ")" +#define span_LOCATION(file, line) file "(" span_STRINGIFY(line) ")" #endif // Method enabling -#if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) +#if span_HAVE(DEFAULT_FUNCTION_TEMPLATE_ARG) -#define span_REQUIRES_0(VA) \ - template< bool B = (VA), typename std::enable_if::type = 0 > +#define span_REQUIRES_0(VA) \ + template ::type = 0> -# if span_BETWEEN( span_COMPILER_MSVC_VERSION, 1, 140 ) +#if span_BETWEEN(span_COMPILER_MSVC_VERSION, 1, 140) // VS 2013 and earlier seem to have trouble with SFINAE for default non-type arguments -# define span_REQUIRES_T(VA) \ - , typename = typename std::enable_if< ( VA ), nonstd::span_lite::detail::enabler >::type -# else -# define span_REQUIRES_T(VA) \ - , typename std::enable_if< (VA), int >::type = 0 -# endif +#define span_REQUIRES_T(VA) \ + , typename = typename std::enable_if<(VA), nonstd::span_lite::detail::enabler>::type +#else +#define span_REQUIRES_T(VA) , typename std::enable_if<(VA), int>::type = 0 +#endif -#define span_REQUIRES_R(R, VA) \ - typename std::enable_if< (VA), R>::type +#define span_REQUIRES_R(R, VA) typename std::enable_if<(VA), R>::type -#define span_REQUIRES_A(VA) \ - , typename std::enable_if< (VA), void*>::type = nullptr +#define span_REQUIRES_A(VA) , typename std::enable_if<(VA), void*>::type = nullptr #else -# define span_REQUIRES_0(VA) /*empty*/ -# define span_REQUIRES_T(VA) /*empty*/ -# define span_REQUIRES_R(R, VA) R -# define span_REQUIRES_A(VA) /*empty*/ +#define span_REQUIRES_0(VA) /*empty*/ +#define span_REQUIRES_T(VA) /*empty*/ +#define span_REQUIRES_R(R, VA) R +#define span_REQUIRES_A(VA) /*empty*/ #endif -namespace nonstd { -namespace span_lite { +namespace nonstd +{ +namespace span_lite +{ // [views.constants], constants typedef span_CONFIG_EXTENT_TYPE extent_t; -typedef span_CONFIG_SIZE_TYPE size_t; +typedef span_CONFIG_SIZE_TYPE size_t; -span_constexpr const extent_t dynamic_extent = static_cast( -1 ); +span_constexpr const extent_t dynamic_extent = static_cast(-1); -template< class T, extent_t Extent = dynamic_extent > +template class span; // Tag to select span constructor taking a container (prevent ms-gsl warning C26426): -struct with_container_t { span_constexpr with_container_t() span_noexcept {} }; -const span_constexpr with_container_t with_container; +struct with_container_t +{ + span_constexpr with_container_t() span_noexcept + { + } +}; +const span_constexpr with_container_t with_container; // C++11 emulation: -namespace std11 { +namespace std11 +{ -#if span_HAVE( REMOVE_CONST ) +#if span_HAVE(REMOVE_CONST) -using std::remove_cv; using std::remove_const; +using std::remove_cv; using std::remove_volatile; #else -template< class T > struct remove_const { typedef T type; }; -template< class T > struct remove_const< T const > { typedef T type; }; +template +struct remove_const +{ + typedef T type; +}; +template +struct remove_const +{ + typedef T type; +}; -template< class T > struct remove_volatile { typedef T type; }; -template< class T > struct remove_volatile< T volatile > { typedef T type; }; +template +struct remove_volatile +{ + typedef T type; +}; +template +struct remove_volatile +{ + typedef T type; +}; -template< class T > +template struct remove_cv { - typedef typename std11::remove_volatile< typename std11::remove_const< T >::type >::type type; + typedef + typename std11::remove_volatile::type>::type type; }; #endif // span_HAVE( REMOVE_CONST ) -#if span_HAVE( TYPE_TRAITS ) +#if span_HAVE(TYPE_TRAITS) +using std::false_type; +using std::integral_constant; using std::is_same; using std::is_signed; -using std::integral_constant; -using std::true_type; -using std::false_type; using std::remove_reference; +using std::true_type; #else -template< class T, T v > struct integral_constant { enum { value = v }; }; -typedef integral_constant< bool, true > true_type; -typedef integral_constant< bool, false > false_type; +template +struct integral_constant +{ + enum + { + value = v + }; +}; +typedef integral_constant true_type; +typedef integral_constant false_type; -template< class T, class U > struct is_same : false_type{}; -template< class T > struct is_same : true_type{}; +template +struct is_same : false_type +{ +}; +template +struct is_same : true_type +{ +}; -template< typename T > struct is_signed : false_type {}; -template<> struct is_signed : true_type {}; -template<> struct is_signed : true_type {}; -template<> struct is_signed : true_type {}; +template +struct is_signed : false_type +{ +}; +template <> +struct is_signed : true_type +{ +}; +template <> +struct is_signed : true_type +{ +}; +template <> +struct is_signed : true_type +{ +}; #endif -} // namespace std11 +} // namespace std11 // C++17 emulation: -namespace std17 { +namespace std17 +{ -template< bool v > struct bool_constant : std11::integral_constant{}; +template +struct bool_constant : std11::integral_constant +{ +}; #if span_CPP11_120 -template< class...> +template using void_t = void; #endif -#if span_HAVE( DATA ) +#if span_HAVE(DATA) using std::data; using std::size; -#elif span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) +#elif span_HAVE(CONSTRAINED_SPAN_CONTAINER_CTOR) -template< typename T, std::size_t N > -inline span_constexpr auto size( const T(&)[N] ) span_noexcept -> size_t +template +inline span_constexpr auto size(const T (&)[N]) span_noexcept->size_t { - return N; + return N; } -template< typename C > -inline span_constexpr auto size( C const & cont ) -> decltype( cont.size() ) +template +inline span_constexpr auto size(C const& cont) -> decltype(cont.size()) { - return cont.size(); + return cont.size(); } -template< typename T, std::size_t N > -inline span_constexpr auto data( T(&arr)[N] ) span_noexcept -> T* +template +inline span_constexpr auto data(T (&arr)[N]) span_noexcept->T* { - return &arr[0]; + return &arr[0]; } -template< typename C > -inline span_constexpr auto data( C & cont ) -> decltype( cont.data() ) +template +inline span_constexpr auto data(C& cont) -> decltype(cont.data()) { - return cont.data(); + return cont.data(); } -template< typename C > -inline span_constexpr auto data( C const & cont ) -> decltype( cont.data() ) +template +inline span_constexpr auto data(C const& cont) -> decltype(cont.data()) { - return cont.data(); + return cont.data(); } -template< typename E > -inline span_constexpr auto data( std::initializer_list il ) span_noexcept -> E const * +template +inline span_constexpr auto data(std::initializer_list il) span_noexcept->E const* { - return il.begin(); + return il.begin(); } -#endif // span_HAVE( DATA ) +#endif // span_HAVE( DATA ) -#if span_HAVE( BYTE ) +#if span_HAVE(BYTE) using std::byte; -#elif span_HAVE( NONSTD_BYTE ) +#elif span_HAVE(NONSTD_BYTE) using nonstd::byte; #endif -} // namespace std17 +} // namespace std17 // C++20 emulation: -namespace std20 { +namespace std20 +{ -#if span_HAVE( DEDUCTION_GUIDES ) -template< class T > -using iter_reference_t = decltype( *std::declval() ); +#if span_HAVE(DEDUCTION_GUIDES) +template +using iter_reference_t = decltype(*std::declval()); #endif -} // namespace std20 +} // namespace std20 // Implementation details: -namespace detail { +namespace detail +{ -/*enum*/ struct enabler{}; +/*enum*/ struct enabler +{ +}; -template< typename T > -span_constexpr bool is_positive( T x ) +template +span_constexpr bool is_positive(T x) { - return std11::is_signed::value ? x >= 0 : true; + return std11::is_signed::value ? x >= 0 : true; } -#if span_HAVE( TYPE_TRAITS ) +#if span_HAVE(TYPE_TRAITS) -template< class Q > -struct is_span_oracle : std::false_type{}; +template +struct is_span_oracle : std::false_type +{ +}; -template< class T, span_CONFIG_EXTENT_TYPE Extent > -struct is_span_oracle< span > : std::true_type{}; +template +struct is_span_oracle > : std::true_type +{ +}; -template< class Q > -struct is_span : is_span_oracle< typename std::remove_cv::type >{}; +template +struct is_span : is_span_oracle::type> +{ +}; -template< class Q > -struct is_std_array_oracle : std::false_type{}; +template +struct is_std_array_oracle : std::false_type +{ +}; -#if span_HAVE( ARRAY ) +#if span_HAVE(ARRAY) -template< class T, std::size_t Extent > -struct is_std_array_oracle< std::array > : std::true_type{}; +template +struct is_std_array_oracle > : std::true_type +{ +}; #endif -template< class Q > -struct is_std_array : is_std_array_oracle< typename std::remove_cv::type >{}; - -template< class Q > -struct is_array : std::false_type {}; +template +struct is_std_array : is_std_array_oracle::type> +{ +}; -template< class T > -struct is_array : std::true_type {}; +template +struct is_array : std::false_type +{ +}; -template< class T, std::size_t N > -struct is_array : std::true_type {}; +template +struct is_array : std::true_type +{ +}; -#if span_CPP11_140 && ! span_BETWEEN( span_COMPILER_GNUC_VERSION, 1, 500 ) +template +struct is_array : std::true_type +{ +}; -template< class, class = void > -struct has_size_and_data : std::false_type{}; +#if span_CPP11_140 && !span_BETWEEN(span_COMPILER_GNUC_VERSION, 1, 500) -template< class C > -struct has_size_and_data -< - C, std17::void_t< - decltype( std17::size(std::declval()) ), - decltype( std17::data(std::declval()) ) > -> : std::true_type{}; +template +struct has_size_and_data : std::false_type +{ +}; -template< class, class, class = void > -struct is_compatible_element : std::false_type {}; +template +struct has_size_and_data())), + decltype(std17::data(std::declval()))> > + : std::true_type +{ +}; -template< class C, class E > -struct is_compatible_element -< - C, E, std17::void_t< - decltype( std17::data(std::declval()) ) > -> : std::is_convertible< typename std::remove_pointer() ) )>::type(*)[], E(*)[] >{}; +template +struct is_compatible_element : std::false_type +{ +}; -template< class C > -struct is_container : std17::bool_constant -< - ! is_span< C >::value - && ! is_array< C >::value - && ! is_std_array< C >::value - && has_size_and_data< C >::value ->{}; +template +struct is_compatible_element()))> > + : std::is_convertible()))>::type (*)[], + E (*)[]> +{ +}; -template< class C, class E > -struct is_compatible_container : std17::bool_constant -< - is_container::value - && is_compatible_element::value ->{}; +template +struct is_container + : std17::bool_constant::value && !is_array::value && + !is_std_array::value && has_size_and_data::value> +{ +}; -#else // span_CPP11_140 +template +struct is_compatible_container + : std17::bool_constant::value && is_compatible_element::value> +{ +}; -template< - class C, class E - span_REQUIRES_T(( - ! is_span< C >::value - && ! is_array< C >::value - && ! is_std_array< C >::value - && ( std::is_convertible< typename std::remove_pointer() ) )>::type(*)[], E(*)[] >::value) - // && has_size_and_data< C >::value - )) - , class = decltype( std17::size(std::declval()) ) - , class = decltype( std17::data(std::declval()) ) -> -struct is_compatible_container : std::true_type{}; +#else // span_CPP11_140 + +template ::value && !is_array::value && !is_std_array::value && + (std::is_convertible()))>::type (*)[], + E (*)[]>::value) + // && has_size_and_data< C >::value + )), + class = decltype(std17::size(std::declval())), + class = decltype(std17::data(std::declval()))> +struct is_compatible_container : std::true_type +{ +}; -#endif // span_CPP11_140 +#endif // span_CPP11_140 -#endif // span_HAVE( TYPE_TRAITS ) +#endif // span_HAVE( TYPE_TRAITS ) -#if ! span_CONFIG( NO_EXCEPTIONS ) -#if span_FEATURE( MEMBER_AT ) > 1 +#if !span_CONFIG(NO_EXCEPTIONS) +#if span_FEATURE(MEMBER_AT) > 1 // format index and size: #if defined(__clang__) -# pragma clang diagnostic ignored "-Wlong-long" +#pragma clang diagnostic ignored "-Wlong-long" #elif defined __GNUC__ -# pragma GCC diagnostic ignored "-Wformat=ll" -# pragma GCC diagnostic ignored "-Wlong-long" +#pragma GCC diagnostic ignored "-Wformat=ll" +#pragma GCC diagnostic ignored "-Wlong-long" #endif -span_noreturn inline void throw_out_of_range( size_t idx, size_t size ) +span_noreturn inline void throw_out_of_range(size_t idx, size_t size) { - const char fmt[] = "span::at(): index '%lli' is out of range [0..%lli)"; - char buffer[ 2 * 20 + sizeof fmt ]; - sprintf( buffer, fmt, static_cast(idx), static_cast(size) ); + const char fmt[] = "span::at(): index '%lli' is out of range [0..%lli)"; + char buffer[2 * 20 + sizeof fmt]; + sprintf(buffer, fmt, static_cast(idx), static_cast(size)); - throw std::out_of_range( buffer ); + throw std::out_of_range(buffer); } -#else // MEMBER_AT +#else // MEMBER_AT -span_noreturn inline void throw_out_of_range( size_t /*idx*/, size_t /*size*/ ) +span_noreturn inline void throw_out_of_range(size_t /*idx*/, size_t /*size*/) { - throw std::out_of_range( "span::at(): index outside span" ); + throw std::out_of_range("span::at(): index outside span"); } #endif // MEMBER_AT #endif // NO_EXCEPTIONS -#if span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#if span_CONFIG(CONTRACT_VIOLATION_THROWS_V) struct contract_violation : std::logic_error { - explicit contract_violation( char const * const message ) - : std::logic_error( message ) - {} + explicit contract_violation(char const* const message) : std::logic_error(message) + { + } }; -inline void report_contract_violation( char const * msg ) +inline void report_contract_violation(char const* msg) { - throw contract_violation( msg ); + throw contract_violation(msg); } -#else // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#else // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) -span_noreturn inline void report_contract_violation( char const * /*msg*/ ) span_noexcept +span_noreturn inline void report_contract_violation(char const* /*msg*/) span_noexcept { - std::terminate(); + std::terminate(); } -#endif // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) +#endif // span_CONFIG( CONTRACT_VIOLATION_THROWS_V ) } // namespace detail // Prevent signed-unsigned mismatch: -#define span_sizeof(T) static_cast( sizeof(T) ) +#define span_sizeof(T) static_cast(sizeof(T)) -template< class T > -inline span_constexpr size_t to_size( T size ) +template +inline span_constexpr size_t to_size(T size) { - return static_cast( size ); + return static_cast(size); } // // [views.span] - A view over a contiguous, single-dimension sequence of objects // -template< class T, extent_t Extent /*= dynamic_extent*/ > +template class span { public: - // constants and types - - typedef T element_type; - typedef typename std11::remove_cv< T >::type value_type; - - typedef T & reference; - typedef T * pointer; - typedef T const * const_pointer; - typedef T const & const_reference; - - typedef size_t size_type; - typedef extent_t extent_type; - - typedef pointer iterator; - typedef const_pointer const_iterator; - - typedef std::ptrdiff_t difference_type; - - typedef std::reverse_iterator< iterator > reverse_iterator; - typedef std::reverse_iterator< const_iterator > const_reverse_iterator; - -// static constexpr extent_type extent = Extent; - enum { extent = Extent }; - - // 26.7.3.2 Constructors, copy, and assignment [span.cons] - - span_REQUIRES_0( - ( Extent == 0 ) || - ( Extent == dynamic_extent ) - ) - span_constexpr span() span_noexcept - : data_( span_nullptr ) - , size_( 0 ) - { - // span_EXPECTS( data() == span_nullptr ); - // span_EXPECTS( size() == 0 ); - } - -#if span_HAVE( ITERATOR_CTOR ) - // Didn't yet succeed in combining the next two constructors: - - span_constexpr_exp span( std::nullptr_t, size_type count ) - : data_( span_nullptr ) - , size_( count ) - { - span_EXPECTS( data_ == span_nullptr && count == 0 ); - } - - template< typename It - span_REQUIRES_T(( - std::is_convertible()), element_type &>::value - )) - > - span_constexpr_exp span( It first, size_type count ) - : data_( to_address( first ) ) - , size_( count ) - { - span_EXPECTS( - ( data_ == span_nullptr && count == 0 ) || - ( data_ != span_nullptr && detail::is_positive( count ) ) - ); - } + // constants and types + + typedef T element_type; + typedef typename std11::remove_cv::type value_type; + + typedef T& reference; + typedef T* pointer; + typedef T const* const_pointer; + typedef T const& const_reference; + + typedef size_t size_type; + typedef extent_t extent_type; + + typedef pointer iterator; + typedef const_pointer const_iterator; + + typedef std::ptrdiff_t difference_type; + + typedef std::reverse_iterator reverse_iterator; + typedef std::reverse_iterator const_reverse_iterator; + + // static constexpr extent_type extent = Extent; + enum + { + extent = Extent + }; + + // 26.7.3.2 Constructors, copy, and assignment [span.cons] + + span_REQUIRES_0((Extent == 0) || (Extent == dynamic_extent)) span_constexpr + span() span_noexcept : data_(span_nullptr), + size_(0) + { + // span_EXPECTS( data() == span_nullptr ); + // span_EXPECTS( size() == 0 ); + } + +#if span_HAVE(ITERATOR_CTOR) + // Didn't yet succeed in combining the next two constructors: + + span_constexpr_exp span(std::nullptr_t, size_type count) + : data_(span_nullptr), size_(count) + { + span_EXPECTS(data_ == span_nullptr && count == 0); + } + + template ()), element_type&>::value))> + span_constexpr_exp span(It first, size_type count) + : data_(to_address(first)), size_(count) + { + span_EXPECTS((data_ == span_nullptr && count == 0) || + (data_ != span_nullptr && detail::is_positive(count))); + } #else - span_constexpr_exp span( pointer ptr, size_type count ) - : data_( ptr ) - , size_( count ) - { - span_EXPECTS( - ( ptr == span_nullptr && count == 0 ) || - ( ptr != span_nullptr && detail::is_positive( count ) ) - ); - } -#endif - -#if span_HAVE( ITERATOR_CTOR ) - template< typename It, typename End - span_REQUIRES_T(( - std::is_convertible()), element_type *>::value - && ! std::is_convertible::value - )) - > - span_constexpr_exp span( It first, End last ) - : data_( to_address( first ) ) - , size_( to_size( last - first ) ) - { - span_EXPECTS( - last - first >= 0 - ); - } + span_constexpr_exp span(pointer ptr, size_type count) : data_(ptr), size_(count) + { + span_EXPECTS((ptr == span_nullptr && count == 0) || + (ptr != span_nullptr && detail::is_positive(count))); + } +#endif + +#if span_HAVE(ITERATOR_CTOR) + template ()), + element_type*>::value && + !std::is_convertible::value))> + span_constexpr_exp span(It first, End last) + : data_(to_address(first)), size_(to_size(last - first)) + { + span_EXPECTS(last - first >= 0); + } #else - span_constexpr_exp span( pointer first, pointer last ) - : data_( first ) - , size_( to_size( last - first ) ) - { - span_EXPECTS( - last - first >= 0 - ); - } -#endif - - template< std::size_t N - span_REQUIRES_T(( - (Extent == dynamic_extent || Extent == static_cast(N)) - && std::is_convertible< value_type(*)[], element_type(*)[] >::value - )) - > - span_constexpr span( element_type ( &arr )[ N ] ) span_noexcept - : data_( span_ADDRESSOF( arr[0] ) ) - , size_( N ) - {} - -#if span_HAVE( ARRAY ) - - template< std::size_t N - span_REQUIRES_T(( - (Extent == dynamic_extent || Extent == static_cast(N)) - && std::is_convertible< value_type(*)[], element_type(*)[] >::value - )) - > -# if span_FEATURE( CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE ) - span_constexpr span( std::array< element_type, N > & arr ) span_noexcept -# else - span_constexpr span( std::array< value_type, N > & arr ) span_noexcept -# endif - : data_( arr.data() ) - , size_( to_size( arr.size() ) ) - {} - - template< std::size_t N -# if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - span_REQUIRES_T(( - (Extent == dynamic_extent || Extent == static_cast(N)) - && std::is_convertible< value_type(*)[], element_type(*)[] >::value - )) -# endif - > - span_constexpr span( std::array< value_type, N> const & arr ) span_noexcept - : data_( arr.data() ) - , size_( to_size( arr.size() ) ) - {} - -#endif // span_HAVE( ARRAY ) - -#if span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) - template< class Container - span_REQUIRES_T(( - detail::is_compatible_container< Container, element_type >::value - )) - > - span_constexpr span( Container & cont ) - : data_( std17::data( cont ) ) - , size_( to_size( std17::size( cont ) ) ) - {} - - template< class Container - span_REQUIRES_T(( - std::is_const< element_type >::value - && detail::is_compatible_container< Container, element_type >::value - )) - > - span_constexpr span( Container const & cont ) - : data_( std17::data( cont ) ) - , size_( to_size( std17::size( cont ) ) ) - {} - -#endif // span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) - -#if span_FEATURE( WITH_CONTAINER ) - - template< class Container > - span_constexpr span( with_container_t, Container & cont ) - : data_( cont.size() == 0 ? span_nullptr : span_ADDRESSOF( cont[0] ) ) - , size_( to_size( cont.size() ) ) - {} - - template< class Container > - span_constexpr span( with_container_t, Container const & cont ) - : data_( cont.size() == 0 ? span_nullptr : const_cast( span_ADDRESSOF( cont[0] ) ) ) - , size_( to_size( cont.size() ) ) - {} -#endif - -#if span_HAVE( IS_DEFAULT ) - span_constexpr span( span const & other ) span_noexcept = default; - - ~span() span_noexcept = default; - - span_constexpr14 span & operator=( span const & other ) span_noexcept = default; + span_constexpr_exp span(pointer first, pointer last) + : data_(first), size_(to_size(last - first)) + { + span_EXPECTS(last - first >= 0); + } +#endif + + template (N)) && + std::is_convertible::value))> + span_constexpr span(element_type (&arr)[N]) span_noexcept + : data_(span_ADDRESSOF(arr[0])), + size_(N) + { + } + +#if span_HAVE(ARRAY) + + template (N)) && + std::is_convertible::value))> +#if span_FEATURE(CONSTRUCTION_FROM_STDARRAY_ELEMENT_TYPE) + span_constexpr span(std::array& arr) span_noexcept #else - span_constexpr span( span const & other ) span_noexcept - : data_( other.data_ ) - , size_( other.size_ ) - {} - - ~span() span_noexcept - {} - - span_constexpr14 span & operator=( span const & other ) span_noexcept - { - data_ = other.data_; - size_ = other.size_; - - return *this; - } -#endif - - template< class OtherElementType, extent_type OtherExtent - span_REQUIRES_T(( - (Extent == dynamic_extent || OtherExtent == dynamic_extent || Extent == OtherExtent) - && std::is_convertible::value - )) - > - span_constexpr_exp span( span const & other ) span_noexcept - : data_( other.data() ) - , size_( other.size() ) - { - span_EXPECTS( OtherExtent == dynamic_extent || other.size() == to_size(OtherExtent) ); - } - - // 26.7.3.3 Subviews [span.sub] - - template< extent_type Count > - span_constexpr_exp span< element_type, Count > - first() const - { - span_EXPECTS( detail::is_positive( Count ) && Count <= size() ); - - return span< element_type, Count >( data(), Count ); - } - - template< extent_type Count > - span_constexpr_exp span< element_type, Count > - last() const - { - span_EXPECTS( detail::is_positive( Count ) && Count <= size() ); - - return span< element_type, Count >( data() + (size() - Count), Count ); - } - -#if span_HAVE( DEFAULT_FUNCTION_TEMPLATE_ARG ) - template< size_type Offset, extent_type Count = dynamic_extent > + span_constexpr span(std::array& arr) span_noexcept +#endif + : data_(arr.data()), + size_(to_size(arr.size())) + { + } + + template (N)) && + std::is_convertible::value)) +#endif + > + span_constexpr span(std::array const& arr) span_noexcept + : data_(arr.data()), + size_(to_size(arr.size())) + { + } + +#endif // span_HAVE( ARRAY ) + +#if span_HAVE(CONSTRAINED_SPAN_CONTAINER_CTOR) + template ::value))> + span_constexpr span(Container& cont) + : data_(std17::data(cont)), size_(to_size(std17::size(cont))) + { + } + + template ::value && + detail::is_compatible_container::value))> + span_constexpr span(Container const& cont) + : data_(std17::data(cont)), size_(to_size(std17::size(cont))) + { + } + +#endif // span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) + +#if span_FEATURE(WITH_CONTAINER) + + template + span_constexpr span(with_container_t, Container& cont) + : data_(cont.size() == 0 ? span_nullptr : span_ADDRESSOF(cont[0])) + , size_(to_size(cont.size())) + { + } + + template + span_constexpr span(with_container_t, Container const& cont) + : data_(cont.size() == 0 ? span_nullptr : + const_cast(span_ADDRESSOF(cont[0]))) + , size_(to_size(cont.size())) + { + } +#endif + +#if span_HAVE(IS_DEFAULT) + span_constexpr span(span const& other) span_noexcept = default; + + ~span() span_noexcept = default; + + span_constexpr14 span& operator=(span const& other) span_noexcept = default; #else - template< size_type Offset, extent_type Count /*= dynamic_extent*/ > -#endif - span_constexpr_exp span< element_type, Count > - subspan() const - { - span_EXPECTS( - ( detail::is_positive( Offset ) && Offset <= size() ) && - ( Count == dynamic_extent || (detail::is_positive( Count ) && Count + Offset <= size()) ) - ); - - return span< element_type, Count >( - data() + Offset, Count != dynamic_extent ? Count : (Extent != dynamic_extent ? Extent - Offset : size() - Offset) ); - } - - span_constexpr_exp span< element_type, dynamic_extent > - first( size_type count ) const - { - span_EXPECTS( detail::is_positive( count ) && count <= size() ); - - return span< element_type, dynamic_extent >( data(), count ); - } - - span_constexpr_exp span< element_type, dynamic_extent > - last( size_type count ) const - { - span_EXPECTS( detail::is_positive( count ) && count <= size() ); - - return span< element_type, dynamic_extent >( data() + ( size() - count ), count ); - } - - span_constexpr_exp span< element_type, dynamic_extent > - subspan( size_type offset, size_type count = static_cast(dynamic_extent) ) const - { - span_EXPECTS( - ( ( detail::is_positive( offset ) && offset <= size() ) ) && - ( count == static_cast(dynamic_extent) || ( detail::is_positive( count ) && offset + count <= size() ) ) - ); - - return span< element_type, dynamic_extent >( - data() + offset, count == static_cast(dynamic_extent) ? size() - offset : count ); - } - - // 26.7.3.4 Observers [span.obs] - - span_constexpr size_type size() const span_noexcept - { - return size_; - } - - span_constexpr std::ptrdiff_t ssize() const span_noexcept - { - return static_cast( size_ ); - } - - span_constexpr size_type size_bytes() const span_noexcept - { - return size() * to_size( sizeof( element_type ) ); - } - - span_nodiscard span_constexpr bool empty() const span_noexcept - { - return size() == 0; - } - - // 26.7.3.5 Element access [span.elem] - - span_constexpr_exp reference operator[]( size_type idx ) const + span_constexpr span(span const& other) span_noexcept : data_(other.data_), + size_(other.size_) + { + } + + ~span() span_noexcept + { + } + + span_constexpr14 span& operator=(span const& other) span_noexcept + { + data_ = other.data_; + size_ = other.size_; + + return *this; + } +#endif + + template ::value))> + span_constexpr_exp span(span const& other) span_noexcept + : data_(other.data()), + size_(other.size()) + { + span_EXPECTS(OtherExtent == dynamic_extent || other.size() == to_size(OtherExtent)); + } + + // 26.7.3.3 Subviews [span.sub] + + template + span_constexpr_exp span first() const + { + span_EXPECTS(detail::is_positive(Count) && Count <= size()); + + return span(data(), Count); + } + + template + span_constexpr_exp span last() const + { + span_EXPECTS(detail::is_positive(Count) && Count <= size()); + + return span(data() + (size() - Count), Count); + } + +#if span_HAVE(DEFAULT_FUNCTION_TEMPLATE_ARG) + template +#else + template +#endif + span_constexpr_exp span subspan() const + { + span_EXPECTS((detail::is_positive(Offset) && Offset <= size()) && + (Count == dynamic_extent || + (detail::is_positive(Count) && Count + Offset <= size()))); + + return span( + data() + Offset, + Count != dynamic_extent ? + Count : + (Extent != dynamic_extent ? Extent - Offset : size() - Offset)); + } + + span_constexpr_exp span first(size_type count) const + { + span_EXPECTS(detail::is_positive(count) && count <= size()); + + return span(data(), count); + } + + span_constexpr_exp span last(size_type count) const + { + span_EXPECTS(detail::is_positive(count) && count <= size()); + + return span(data() + (size() - count), count); + } + + span_constexpr_exp span subspan( + size_type offset, size_type count = static_cast(dynamic_extent)) const + { + span_EXPECTS(((detail::is_positive(offset) && offset <= size())) && + (count == static_cast(dynamic_extent) || + (detail::is_positive(count) && offset + count <= size()))); + + return span( + data() + offset, + count == static_cast(dynamic_extent) ? size() - offset : count); + } + + // 26.7.3.4 Observers [span.obs] + + span_constexpr size_type size() const span_noexcept + { + return size_; + } + + span_constexpr std::ptrdiff_t ssize() const span_noexcept + { + return static_cast(size_); + } + + span_constexpr size_type size_bytes() const span_noexcept + { + return size() * to_size(sizeof(element_type)); + } + + span_nodiscard span_constexpr bool empty() const span_noexcept + { + return size() == 0; + } + + // 26.7.3.5 Element access [span.elem] + + span_constexpr_exp reference operator[](size_type idx) const + { + span_EXPECTS(detail::is_positive(idx) && idx < size()); + + return *(data() + idx); + } + +#if span_FEATURE(MEMBER_CALL_OPERATOR) + span_deprecated("replace operator() with operator[]") + + span_constexpr_exp reference + operator()(size_type idx) const + { + span_EXPECTS(detail::is_positive(idx) && idx < size()); + + return *(data() + idx); + } +#endif + +#if span_FEATURE(MEMBER_AT) + span_constexpr14 reference at(size_type idx) const + { +#if span_CONFIG(NO_EXCEPTIONS) + return this->operator[](idx); +#else + if (!detail::is_positive(idx) || size() <= idx) { - span_EXPECTS( detail::is_positive( idx ) && idx < size() ); - - return *( data() + idx ); - } - -#if span_FEATURE( MEMBER_CALL_OPERATOR ) - span_deprecated("replace operator() with operator[]") - - span_constexpr_exp reference operator()( size_type idx ) const - { - span_EXPECTS( detail::is_positive( idx ) && idx < size() ); - - return *( data() + idx ); + detail::throw_out_of_range(idx, size()); } + return *(data() + idx); #endif - -#if span_FEATURE( MEMBER_AT ) - span_constexpr14 reference at( size_type idx ) const - { -#if span_CONFIG( NO_EXCEPTIONS ) - return this->operator[]( idx ); -#else - if ( !detail::is_positive( idx ) || size() <= idx ) - { - detail::throw_out_of_range( idx, size() ); - } - return *( data() + idx ); -#endif - } + } #endif - span_constexpr pointer data() const span_noexcept - { - return data_; - } + span_constexpr pointer data() const span_noexcept + { + return data_; + } -#if span_FEATURE( MEMBER_BACK_FRONT ) +#if span_FEATURE(MEMBER_BACK_FRONT) - span_constexpr_exp reference front() const span_noexcept - { - span_EXPECTS( ! empty() ); + span_constexpr_exp reference front() const span_noexcept + { + span_EXPECTS(!empty()); - return *data(); - } + return *data(); + } - span_constexpr_exp reference back() const span_noexcept - { - span_EXPECTS( ! empty() ); + span_constexpr_exp reference back() const span_noexcept + { + span_EXPECTS(!empty()); - return *( data() + size() - 1 ); - } + return *(data() + size() - 1); + } #endif - // xx.x.x.x Modifiers [span.modifiers] + // xx.x.x.x Modifiers [span.modifiers] -#if span_FEATURE( MEMBER_SWAP ) +#if span_FEATURE(MEMBER_SWAP) - span_constexpr14 void swap( span & other ) span_noexcept - { - using std::swap; - swap( data_, other.data_ ); - swap( size_, other.size_ ); - } + span_constexpr14 void swap(span& other) span_noexcept + { + using std::swap; + swap(data_, other.data_); + swap(size_, other.size_); + } #endif - // 26.7.3.6 Iterator support [span.iterators] + // 26.7.3.6 Iterator support [span.iterators] - span_constexpr iterator begin() const span_noexcept - { + span_constexpr iterator begin() const span_noexcept + { #if span_CPP11_OR_GREATER - return { data() }; + return { data() }; #else - return iterator( data() ); + return iterator(data()); #endif - } + } - span_constexpr iterator end() const span_noexcept - { + span_constexpr iterator end() const span_noexcept + { #if span_CPP11_OR_GREATER - return { data() + size() }; + return { data() + size() }; #else - return iterator( data() + size() ); + return iterator(data() + size()); #endif - } + } - span_constexpr const_iterator cbegin() const span_noexcept - { + span_constexpr const_iterator cbegin() const span_noexcept + { #if span_CPP11_OR_GREATER - return { data() }; + return { data() }; #else - return const_iterator( data() ); + return const_iterator(data()); #endif - } + } - span_constexpr const_iterator cend() const span_noexcept - { + span_constexpr const_iterator cend() const span_noexcept + { #if span_CPP11_OR_GREATER - return { data() + size() }; + return { data() + size() }; #else - return const_iterator( data() + size() ); + return const_iterator(data() + size()); #endif - } + } - span_constexpr reverse_iterator rbegin() const span_noexcept - { - return reverse_iterator( end() ); - } + span_constexpr reverse_iterator rbegin() const span_noexcept + { + return reverse_iterator(end()); + } - span_constexpr reverse_iterator rend() const span_noexcept - { - return reverse_iterator( begin() ); - } + span_constexpr reverse_iterator rend() const span_noexcept + { + return reverse_iterator(begin()); + } - span_constexpr const_reverse_iterator crbegin() const span_noexcept - { - return const_reverse_iterator ( cend() ); - } + span_constexpr const_reverse_iterator crbegin() const span_noexcept + { + return const_reverse_iterator(cend()); + } - span_constexpr const_reverse_iterator crend() const span_noexcept - { - return const_reverse_iterator( cbegin() ); - } + span_constexpr const_reverse_iterator crend() const span_noexcept + { + return const_reverse_iterator(cbegin()); + } private: - - // Note: C++20 has std::pointer_traits::to_address( it ); - -#if span_HAVE( ITERATOR_CTOR ) - static inline span_constexpr pointer to_address( std::nullptr_t ) span_noexcept - { - return nullptr; - } - - template< typename U > - static inline span_constexpr U * to_address( U * p ) span_noexcept - { - return p; - } - - template< typename Ptr - span_REQUIRES_T(( ! std::is_pointer::value )) - > - static inline span_constexpr pointer to_address( Ptr const & it ) span_noexcept - { - return to_address( it.operator->() ); - } -#endif // span_HAVE( ITERATOR_CTOR ) + // Note: C++20 has std::pointer_traits::to_address( it ); + +#if span_HAVE(ITERATOR_CTOR) + static inline span_constexpr pointer to_address(std::nullptr_t) span_noexcept + { + return nullptr; + } + + template + static inline span_constexpr U* to_address(U* p) span_noexcept + { + return p; + } + + template ::value))> + static inline span_constexpr pointer to_address(Ptr const& it) span_noexcept + { + return to_address(it.operator->()); + } +#endif // span_HAVE( ITERATOR_CTOR ) private: - pointer data_; - size_type size_; + pointer data_; + size_type size_; }; // class template argument deduction guides: -#if span_HAVE( DEDUCTION_GUIDES ) +#if span_HAVE(DEDUCTION_GUIDES) -template< class T, size_t N > -span( T (&)[N] ) -> span(N)>; +template +span(T (&)[N]) -> span(N)>; -template< class T, size_t N > -span( std::array & ) -> span(N)>; +template +span(std::array&) -> span(N)>; -template< class T, size_t N > -span( std::array const & ) -> span(N)>; +template +span(std::array const&) -> span(N)>; -#if span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) +#if span_HAVE(CONSTRAINED_SPAN_CONTAINER_CTOR) -template< class Container > -span( Container& ) -> span; +template +span(Container&) -> span; -template< class Container > -span( Container const & ) -> span; +template +span(Container const&) -> span; #endif // iterator: constraints: It satisfies contiguous_­iterator. -template< class It, class EndOrSize > -span( It, EndOrSize ) -> span< typename std11::remove_reference< typename std20::iter_reference_t >::type >; +template +span(It, EndOrSize) -> span< + typename std11::remove_reference >::type>; -#endif // span_HAVE( DEDUCTION_GUIDES ) +#endif // span_HAVE( DEDUCTION_GUIDES ) // 26.7.3.7 Comparison operators [span.comparison] -#if span_FEATURE( COMPARISON ) -#if span_FEATURE( SAME ) +#if span_FEATURE(COMPARISON) +#if span_FEATURE(SAME) -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool same( span const & l, span const & r ) span_noexcept +template +inline span_constexpr bool same(span const& l, + span const& r) span_noexcept { - return std11::is_same::value - && l.size() == r.size() - && static_cast( l.data() ) == r.data(); + return std11::is_same::value && l.size() == r.size() && + static_cast(l.data()) == r.data(); } #endif -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator==( span const & l, span const & r ) +template +inline span_constexpr bool operator==(span const& l, span const& r) { - return -#if span_FEATURE( SAME ) - same( l, r ) || + return +#if span_FEATURE(SAME) + same(l, r) || #endif - ( l.size() == r.size() && std::equal( l.begin(), l.end(), r.begin() ) ); + (l.size() == r.size() && std::equal(l.begin(), l.end(), r.begin())); } -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator<( span const & l, span const & r ) +template +inline span_constexpr bool operator<(span const& l, span const& r) { - return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end() ); + return std::lexicographical_compare(l.begin(), l.end(), r.begin(), r.end()); } -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator!=( span const & l, span const & r ) +template +inline span_constexpr bool operator!=(span const& l, span const& r) { - return !( l == r ); + return !(l == r); } -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator<=( span const & l, span const & r ) +template +inline span_constexpr bool operator<=(span const& l, span const& r) { - return !( r < l ); + return !(r < l); } -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator>( span const & l, span const & r ) +template +inline span_constexpr bool operator>(span const& l, span const& r) { - return ( r < l ); + return (r < l); } -template< class T1, extent_t E1, class T2, extent_t E2 > -inline span_constexpr bool operator>=( span const & l, span const & r ) +template +inline span_constexpr bool operator>=(span const& l, span const& r) { - return !( l < r ); + return !(l < r); } -#endif // span_FEATURE( COMPARISON ) +#endif // span_FEATURE( COMPARISON ) // 26.7.2.6 views of object representation [span.objectrep] -#if span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) +#if span_HAVE(BYTE) || span_HAVE(NONSTD_BYTE) // Avoid MSVC 14.1 (1910), VS 2017: warning C4307: '*': integral constant overflow: -template< typename T, extent_t Extent > +template struct BytesExtent { #if span_CPP11_OR_GREATER - enum ET : extent_t { value = span_sizeof(T) * Extent }; + enum ET : extent_t + { + value = span_sizeof(T) * Extent + }; #else - enum ET { value = span_sizeof(T) * Extent }; + enum ET + { + value = span_sizeof(T) * Extent + }; #endif }; -template< typename T > -struct BytesExtent< T, dynamic_extent > +template +struct BytesExtent { #if span_CPP11_OR_GREATER - enum ET : extent_t { value = dynamic_extent }; + enum ET : extent_t{ value = dynamic_extent }; #else - enum ET { value = dynamic_extent }; + enum ET + { + value = dynamic_extent + }; #endif }; -template< class T, extent_t Extent > -inline span_constexpr span< const std17::byte, BytesExtent::value > -as_bytes( span spn ) span_noexcept +template +inline span_constexpr span::value> +as_bytes(span spn) span_noexcept { #if 0 return { reinterpret_cast< std17::byte const * >( spn.data() ), spn.size_bytes() }; #else - return span< const std17::byte, BytesExtent::value >( - reinterpret_cast< std17::byte const * >( spn.data() ), spn.size_bytes() ); // NOLINT + return span::value>( + reinterpret_cast(spn.data()), spn.size_bytes()); // NOLINT #endif } -template< class T, extent_t Extent > -inline span_constexpr span< std17::byte, BytesExtent::value > -as_writable_bytes( span spn ) span_noexcept +template +inline span_constexpr span::value> +as_writable_bytes(span spn) span_noexcept { #if 0 return { reinterpret_cast< std17::byte * >( spn.data() ), spn.size_bytes() }; #else - return span< std17::byte, BytesExtent::value >( - reinterpret_cast< std17::byte * >( spn.data() ), spn.size_bytes() ); // NOLINT + return span::value>( + reinterpret_cast(spn.data()), spn.size_bytes()); // NOLINT #endif } -#endif // span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) +#endif // span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) // 27.8 Container and view access [iterator.container] -template< class T, extent_t Extent /*= dynamic_extent*/ > -span_constexpr std::size_t size( span const & spn ) +template +span_constexpr std::size_t size(span const& spn) { - return static_cast( spn.size() ); + return static_cast(spn.size()); } -template< class T, extent_t Extent /*= dynamic_extent*/ > -span_constexpr std::ptrdiff_t ssize( span const & spn ) +template +span_constexpr std::ptrdiff_t ssize(span const& spn) { - return static_cast( spn.size() ); + return static_cast(spn.size()); } } // namespace span_lite @@ -1498,7 +1567,8 @@ span_constexpr std::ptrdiff_t ssize( span const & spn ) // make available in nonstd: -namespace nonstd { +namespace nonstd +{ using span_lite::dynamic_extent; @@ -1506,8 +1576,8 @@ using span_lite::span; using span_lite::with_container; -#if span_FEATURE( COMPARISON ) -#if span_FEATURE( SAME ) +#if span_FEATURE(COMPARISON) +#if span_FEATURE(SAME) using span_lite::same; #endif @@ -1519,7 +1589,7 @@ using span_lite::operator>; using span_lite::operator>=; #endif -#if span_HAVE( BYTE ) +#if span_HAVE(BYTE) using span_lite::as_bytes; using span_lite::as_writable_bytes; #endif @@ -1533,267 +1603,264 @@ using span_lite::ssize; // make_span() [span-lite extension]: -#if span_FEATURE( MAKE_SPAN ) || span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) || span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) +#if span_FEATURE(MAKE_SPAN) || span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_SPAN) || \ + span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_CONTAINER) #if span_USES_STD_SPAN -# define span_constexpr constexpr -# define span_noexcept noexcept -# define span_nullptr nullptr -# ifndef span_CONFIG_EXTENT_TYPE -# define span_CONFIG_EXTENT_TYPE std::size_t -# endif +#define span_constexpr constexpr +#define span_noexcept noexcept +#define span_nullptr nullptr +#ifndef span_CONFIG_EXTENT_TYPE +#define span_CONFIG_EXTENT_TYPE std::size_t +#endif using extent_t = span_CONFIG_EXTENT_TYPE; #endif // span_USES_STD_SPAN -namespace nonstd { -namespace span_lite { +namespace nonstd +{ +namespace span_lite +{ -template< class T > -inline span_constexpr span -make_span( T * ptr, size_t count ) span_noexcept +template +inline span_constexpr span make_span(T* ptr, size_t count) span_noexcept { - return span( ptr, count ); + return span(ptr, count); } -template< class T > -inline span_constexpr span -make_span( T * first, T * last ) span_noexcept +template +inline span_constexpr span make_span(T* first, T* last) span_noexcept { - return span( first, last ); + return span(first, last); } -template< class T, std::size_t N > +template inline span_constexpr span(N)> -make_span( T ( &arr )[ N ] ) span_noexcept +make_span(T (&arr)[N]) span_noexcept { - return span(N)>( &arr[ 0 ], N ); + return span(N)>(&arr[0], N); } -#if span_USES_STD_SPAN || span_HAVE( ARRAY ) +#if span_USES_STD_SPAN || span_HAVE(ARRAY) -template< class T, std::size_t N > +template inline span_constexpr span(N)> -make_span( std::array< T, N > & arr ) span_noexcept +make_span(std::array& arr) span_noexcept { - return span(N)>( arr ); + return span(N)>(arr); } -template< class T, std::size_t N > -inline span_constexpr span< const T, static_cast(N) > -make_span( std::array< T, N > const & arr ) span_noexcept +template +inline span_constexpr span(N)> +make_span(std::array const& arr) span_noexcept { - return span(N)>( arr ); + return span(N)>(arr); } -#endif // span_HAVE( ARRAY ) +#endif // span_HAVE( ARRAY ) #if span_USES_STD_SPAN -template< class Container, class EP = decltype( std::data(std::declval())) > +template ()))> inline span_constexpr auto -make_span( Container & cont ) span_noexcept -> span< typename std::remove_pointer::type > +make_span(Container& cont) span_noexcept->span::type> { - return span< typename std::remove_pointer::type >( cont ); + return span::type>(cont); } -template< class Container, class EP = decltype( std::data(std::declval())) > -inline span_constexpr auto -make_span( Container const & cont ) span_noexcept -> span< const typename std::remove_pointer::type > +template ()))> +inline span_constexpr auto make_span(Container const& cont) + span_noexcept->span::type> { - return span< const typename std::remove_pointer::type >( cont ); + return span::type>(cont); } -#elif span_HAVE( CONSTRAINED_SPAN_CONTAINER_CTOR ) && span_HAVE( AUTO ) +#elif span_HAVE(CONSTRAINED_SPAN_CONTAINER_CTOR) && span_HAVE(AUTO) -template< class Container, class EP = decltype( std17::data(std::declval())) > +template ()))> inline span_constexpr auto -make_span( Container & cont ) span_noexcept -> span< typename std::remove_pointer::type > +make_span(Container& cont) span_noexcept->span::type> { - return span< typename std::remove_pointer::type >( cont ); + return span::type>(cont); } -template< class Container, class EP = decltype( std17::data(std::declval())) > -inline span_constexpr auto -make_span( Container const & cont ) span_noexcept -> span< const typename std::remove_pointer::type > +template ()))> +inline span_constexpr auto make_span(Container const& cont) + span_noexcept->span::type> { - return span< const typename std::remove_pointer::type >( cont ); + return span::type>(cont); } #else -template< class T > -inline span_constexpr span -make_span( span spn ) span_noexcept +template +inline span_constexpr span make_span(span spn) span_noexcept { - return spn; + return spn; } -template< class T, class Allocator > -inline span_constexpr span -make_span( std::vector & cont ) span_noexcept +template +inline span_constexpr span make_span(std::vector& cont) span_noexcept { - return span( with_container, cont ); + return span(with_container, cont); } -template< class T, class Allocator > +template inline span_constexpr span -make_span( std::vector const & cont ) span_noexcept +make_span(std::vector const& cont) span_noexcept { - return span( with_container, cont ); + return span(with_container, cont); } -#endif // span_USES_STD_SPAN || ( ... ) +#endif // span_USES_STD_SPAN || ( ... ) -#if ! span_USES_STD_SPAN && span_FEATURE( WITH_CONTAINER ) +#if !span_USES_STD_SPAN && span_FEATURE(WITH_CONTAINER) -template< class Container > +template inline span_constexpr span -make_span( with_container_t, Container & cont ) span_noexcept +make_span(with_container_t, Container& cont) span_noexcept { - return span< typename Container::value_type >( with_container, cont ); + return span(with_container, cont); } -template< class Container > +template inline span_constexpr span -make_span( with_container_t, Container const & cont ) span_noexcept +make_span(with_container_t, Container const& cont) span_noexcept { - return span< const typename Container::value_type >( with_container, cont ); + return span(with_container, cont); } -#endif // ! span_USES_STD_SPAN && span_FEATURE( WITH_CONTAINER ) +#endif // ! span_USES_STD_SPAN && span_FEATURE( WITH_CONTAINER ) // extensions: non-member views: // this feature implies the presence of make_span() -#if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) +#if span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_SPAN) -template< extent_t Count, class T, extent_t Extent > -span_constexpr span -first( span spn ) +template +span_constexpr span first(span spn) { - return spn.template first(); + return spn.template first(); } -template< class T, extent_t Extent > -span_constexpr span -first( span spn, size_t count ) +template +span_constexpr span first(span spn, size_t count) { - return spn.first( count ); + return spn.first(count); } -template< extent_t Count, class T, extent_t Extent > -span_constexpr span -last( span spn ) +template +span_constexpr span last(span spn) { - return spn.template last(); + return spn.template last(); } -template< class T, extent_t Extent > -span_constexpr span -last( span spn, size_t count ) +template +span_constexpr span last(span spn, size_t count) { - return spn.last( count ); + return spn.last(count); } -template< size_t Offset, extent_t Count, class T, extent_t Extent > -span_constexpr span -subspan( span spn ) +template +span_constexpr span subspan(span spn) { - return spn.template subspan(); + return spn.template subspan(); } -template< class T, extent_t Extent > -span_constexpr span -subspan( span spn, size_t offset, extent_t count = dynamic_extent ) +template +span_constexpr span subspan(span spn, size_t offset, + extent_t count = dynamic_extent) { - return spn.subspan( offset, count ); + return spn.subspan(offset, count); } -#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) +#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) -#if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) && span_CPP11_120 +#if span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_CONTAINER) && span_CPP11_120 -template< extent_t Count, class T > -span_constexpr auto -first( T & t ) -> decltype( make_span(t).template first() ) +template +span_constexpr auto first(T& t) -> decltype(make_span(t).template first()) { - return make_span( t ).template first(); + return make_span(t).template first(); } -template< class T > -span_constexpr auto -first( T & t, size_t count ) -> decltype( make_span(t).first(count) ) +template +span_constexpr auto first(T& t, size_t count) -> decltype(make_span(t).first(count)) { - return make_span( t ).first( count ); + return make_span(t).first(count); } -template< extent_t Count, class T > -span_constexpr auto -last( T & t ) -> decltype( make_span(t).template last() ) +template +span_constexpr auto last(T& t) -> decltype(make_span(t).template last()) { - return make_span(t).template last(); + return make_span(t).template last(); } -template< class T > -span_constexpr auto -last( T & t, extent_t count ) -> decltype( make_span(t).last(count) ) +template +span_constexpr auto last(T& t, extent_t count) -> decltype(make_span(t).last(count)) { - return make_span( t ).last( count ); + return make_span(t).last(count); } -template< size_t Offset, extent_t Count = dynamic_extent, class T > -span_constexpr auto -subspan( T & t ) -> decltype( make_span(t).template subspan() ) +template +span_constexpr auto subspan(T& t) + -> decltype(make_span(t).template subspan()) { - return make_span( t ).template subspan(); + return make_span(t).template subspan(); } -template< class T > -span_constexpr auto -subspan( T & t, size_t offset, extent_t count = dynamic_extent ) -> decltype( make_span(t).subspan(offset, count) ) +template +span_constexpr auto subspan(T& t, size_t offset, extent_t count = dynamic_extent) + -> decltype(make_span(t).subspan(offset, count)) { - return make_span( t ).subspan( offset, count ); + return make_span(t).subspan(offset, count); } -#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) +#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) } // namespace span_lite } // namespace nonstd // make available in nonstd: -namespace nonstd { +namespace nonstd +{ using span_lite::make_span; -#if span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_SPAN ) || ( span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_CONTAINER ) && span_CPP11_120 ) +#if span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_SPAN) || \ + (span_FEATURE(NON_MEMBER_FIRST_LAST_SUB_CONTAINER) && span_CPP11_120) using span_lite::first; using span_lite::last; using span_lite::subspan; -#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_[SPAN|CONTAINER] ) +#endif // span_FEATURE( NON_MEMBER_FIRST_LAST_SUB_[SPAN|CONTAINER] ) } // namespace nonstd -#endif // #if span_FEATURE_TO_STD( MAKE_SPAN ) +#endif // #if span_FEATURE_TO_STD( MAKE_SPAN ) -#if span_CPP11_OR_GREATER && span_FEATURE( BYTE_SPAN ) && ( span_HAVE( BYTE ) || span_HAVE( NONSTD_BYTE ) ) +#if span_CPP11_OR_GREATER && span_FEATURE(BYTE_SPAN) && \ + (span_HAVE(BYTE) || span_HAVE(NONSTD_BYTE)) -namespace nonstd { -namespace span_lite { +namespace nonstd +{ +namespace span_lite +{ -template< class T > +template inline span_constexpr auto -byte_span( T & t ) span_noexcept -> span< std17::byte, span_sizeof(T) > +byte_span(T& t) span_noexcept->span { - return span< std17::byte, span_sizeof(t) >( reinterpret_cast< std17::byte * >( &t ), span_sizeof(T) ); + return span(reinterpret_cast(&t), + span_sizeof(T)); } -template< class T > +template inline span_constexpr auto -byte_span( T const & t ) span_noexcept -> span< const std17::byte, span_sizeof(T) > +byte_span(T const& t) span_noexcept->span { - return span< const std17::byte, span_sizeof(t) >( reinterpret_cast< std17::byte const * >( &t ), span_sizeof(T) ); + return span(reinterpret_cast(&t), + span_sizeof(T)); } } // namespace span_lite @@ -1801,83 +1868,97 @@ byte_span( T const & t ) span_noexcept -> span< const std17::byte, span_sizeof(T // make available in nonstd: -namespace nonstd { +namespace nonstd +{ using span_lite::byte_span; } // namespace nonstd -#endif // span_FEATURE( BYTE_SPAN ) +#endif // span_FEATURE( BYTE_SPAN ) -#if span_HAVE( STRUCT_BINDING ) +#if span_HAVE(STRUCT_BINDING) -#if span_CPP14_OR_GREATER -# include +#if span_CPP14_OR_GREATER +#include #elif span_CPP11_OR_GREATER -# include -namespace std { - template< std::size_t I, typename T > - using tuple_element_t = typename tuple_element::type; +#include +namespace std +{ +template +using tuple_element_t = typename tuple_element::type; } #else -namespace std { - template< typename T > - class tuple_size; /*undefined*/ +namespace std +{ +template +class tuple_size; /*undefined*/ - template< std::size_t I, typename T > - class tuple_element; /* undefined */ -} -#endif // span_CPP14_OR_GREATER +template +class tuple_element; /* undefined */ +} // namespace std +#endif // span_CPP14_OR_GREATER -namespace std { +namespace std +{ // 26.7.X Tuple interface // std::tuple_size<>: -template< typename ElementType, nonstd::span_lite::extent_t Extent > -class tuple_size< nonstd::span > : public integral_constant(Extent)> {}; +template +class tuple_size > + : public integral_constant(Extent)> +{ +}; // std::tuple_size<>: Leave undefined for dynamic extent: -template< typename ElementType > -class tuple_size< nonstd::span >; +template +class tuple_size >; // std::tuple_element<>: -template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > -class tuple_element< I, nonstd::span > +template +class tuple_element > { public: -#if span_HAVE( STATIC_ASSERT ) - static_assert( Extent != nonstd::dynamic_extent && I < Extent, "tuple_element: dynamic extent or index out of range" ); +#if span_HAVE(STATIC_ASSERT) + static_assert(Extent != nonstd::dynamic_extent && I < Extent, "tuple_element: " + "dynamic extent or index " + "out of range"); #endif - using type = ElementType; + using type = ElementType; }; // std::get<>(), 2 variants: -template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > -span_constexpr ElementType & get( nonstd::span & spn ) span_noexcept +template +span_constexpr ElementType& get(nonstd::span& spn) span_noexcept { -#if span_HAVE( STATIC_ASSERT ) - static_assert( Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic extent or index out of range" ); +#if span_HAVE(STATIC_ASSERT) + static_assert(Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic " + "extent or index out of " + "range"); #endif - return spn[I]; + return spn[I]; } -template< size_t I, typename ElementType, nonstd::span_lite::extent_t Extent > -span_constexpr ElementType const & get( nonstd::span const & spn ) span_noexcept +template +span_constexpr ElementType const& +get(nonstd::span const& spn) span_noexcept { -#if span_HAVE( STATIC_ASSERT ) - static_assert( Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic extent or index out of range" ); +#if span_HAVE(STATIC_ASSERT) + static_assert(Extent != nonstd::dynamic_extent && I < Extent, "get<>(span): dynamic " + "extent or index out of " + "range"); #endif - return spn[I]; + return spn[I]; } -} // end namespace std +} // end namespace std -#endif // span_HAVE( STRUCT_BINDING ) +#endif // span_HAVE( STRUCT_BINDING ) -#if ! span_USES_STD_SPAN +#if !span_USES_STD_SPAN span_RESTORE_WARNINGS() #endif // span_USES_STD_SPAN diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/deserializer.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/deserializer.hpp index 4ad0c9bff..658d63261 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/deserializer.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/deserializer.hpp @@ -12,7 +12,7 @@ namespace eprosima::fastcdr { class FastBuffer; class Cdr; -} +} // namespace eprosima::fastcdr namespace RosMsgParser { @@ -20,7 +20,6 @@ namespace RosMsgParser class Deserializer { public: - virtual void init(Span buffer) { _buffer = buffer; @@ -46,7 +45,7 @@ class Deserializer virtual size_t bytesLeft() const { - return _buffer.size() - ( getCurrentPtr() - _buffer.data() ); + return _buffer.size() - (getCurrentPtr() - _buffer.data()); } // reset the pointer to beginning of buffer @@ -62,7 +61,6 @@ class Deserializer class ROS_Deserializer : public Deserializer { public: - Variant deserialize(BuiltinType type) override; void deserializeString(std::string& dst) override; @@ -78,18 +76,18 @@ class ROS_Deserializer : public Deserializer void reset() override; protected: - const uint8_t* _ptr; size_t _bytes_left; - template T deserialize() + template + T deserialize() { T out; - if ( sizeof(T) > _bytes_left ) + if (sizeof(T) > _bytes_left) { throw std::runtime_error("Buffer overrun in Deserializer"); } - out = ( *(reinterpret_cast( _ptr )) ); + out = (*(reinterpret_cast(_ptr))); _bytes_left -= sizeof(T); _ptr += sizeof(T); return out; @@ -103,7 +101,6 @@ class ROS_Deserializer : public Deserializer class FastCDR_Deserializer : public Deserializer { public: - Variant deserialize(BuiltinType type) override; void deserializeString(std::string& dst) override; @@ -119,14 +116,12 @@ class FastCDR_Deserializer : public Deserializer virtual void reset() override; protected: - std::shared_ptr _cdr_buffer; std::shared_ptr _cdr; - }; using ROS2_Deserializer = FastCDR_Deserializer; -} +} // namespace RosMsgParser -#endif // DESERIALIZER_HPP +#endif // DESERIALIZER_HPP diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/conversion_impl.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/conversion_impl.hpp index 80e232883..2f01aac65 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/conversion_impl.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/conversion_impl.hpp @@ -1,36 +1,36 @@ /********************************************************************* -* Software License Agreement (BSD License) -* -* Copyright 2016-2017 Davide Faconti -* 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 Willow Garage, Inc. 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. -* *******************************************************************/ + * Software License Agreement (BSD License) + * + * Copyright 2016-2017 Davide Faconti + * 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 Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * *******************************************************************/ #ifndef VARIANT_IMPL_H #define VARIANT_IMPL_H @@ -45,127 +45,131 @@ namespace RosMsgParser { -namespace details{ +namespace details +{ template using Invoke = typename T::type; - template -using EnableIf = Invoke >; - +using EnableIf = Invoke>; template -struct is_integer : std::integral_constant::value - && !std::is_same::value - && !std::is_same::value> -{}; +struct is_integer : std::integral_constant::value && + !std::is_same::value && + !std::is_same::value> +{ +}; template -struct is_same_real : std::integral_constant::value - && std::is_floating_point::value > -{}; - +struct is_same_real : std::integral_constant::value && + std::is_floating_point::value> +{ +}; template struct is_safe_integer_conversion - : std::integral_constant::value - && is_integer::value - && sizeof(From) <= sizeof(To) - && std::is_signed::value == std::is_signed::value> -{}; + : std::integral_constant::value && is_integer::value && + sizeof(From) <= sizeof(To) && + std::is_signed::value == std::is_signed::value> +{ +}; template struct float_conversion - : std::integral_constant::value - && std::is_floating_point::value - && !std::is_same::value > -{}; + : std::integral_constant::value && + std::is_floating_point::value && + !std::is_same::value> +{ +}; template struct unsigned_to_smaller_conversion - : std::integral_constant::value - && is_integer::value - && (sizeof(From) > sizeof(To)) - && !std::is_signed::value - && !std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + (sizeof(From) > sizeof(To)) && + !std::is_signed::value && + !std::is_signed::value> +{ +}; template struct signed_to_smaller_conversion - : std::integral_constant::value - && is_integer::value - && (sizeof(From) > sizeof(To)) - && std::is_signed::value - && std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + (sizeof(From) > sizeof(To)) && + std::is_signed::value && + std::is_signed::value> +{ +}; //--------------------------- template struct signed_to_smaller_unsigned_conversion - : std::integral_constant::value - && is_integer::value - && sizeof(From) >= sizeof(To) - && std::is_signed::value - && !std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + sizeof(From) >= sizeof(To) && + std::is_signed::value && + !std::is_signed::value> +{ +}; template struct signed_to_larger_unsigned_conversion - : std::integral_constant::value - && is_integer::value - && sizeof(From) < sizeof(To) - && std::is_signed::value - && !std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + sizeof(From) < sizeof(To) && + std::is_signed::value && + !std::is_signed::value> +{ +}; template struct unsigned_to_smaller_signed_conversion - : std::integral_constant::value - && is_integer::value - && (sizeof(From) >= sizeof(To)) - && !std::is_signed::value - && std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + (sizeof(From) >= sizeof(To)) && + !std::is_signed::value && + std::is_signed::value> +{ +}; template struct unsigned_to_larger_signed_conversion - : std::integral_constant::value - && is_integer::value - && sizeof(From) < sizeof(To) - && !std::is_signed::value - && std::is_signed::value > -{}; + : std::integral_constant::value && is_integer::value && + sizeof(From) < sizeof(To) && + !std::is_signed::value && + std::is_signed::value> +{ +}; template struct floating_to_signed_conversion - : std::integral_constant::value - && is_integer::value - && std::is_signed::value > -{}; + : std::integral_constant::value && + is_integer::value && std::is_signed::value> +{ +}; template struct floating_to_unsigned_conversion - : std::integral_constant::value - && is_integer::value - && !std::is_signed::value > -{}; + : std::integral_constant::value && + is_integer::value && !std::is_signed::value> +{ +}; template struct integer_to_floating_conversion - : std::integral_constant::value - && std::is_floating_point::value > -{}; + : std::integral_constant::value && std::is_floating_point::value> +{ +}; template inline void checkUpperLimit(const From& from) { if ((sizeof(To) < sizeof(From)) && - (from > static_cast(std::numeric_limits::max()))) { + (from > static_cast(std::numeric_limits::max()))) + { throw RangeException("Value too large."); } - else if (static_cast(from) > std::numeric_limits::max()) { + else if (static_cast(from) > std::numeric_limits::max()) + { throw RangeException("Value too large."); } } @@ -173,7 +177,8 @@ inline void checkUpperLimit(const From& from) template inline void checkUpperLimitFloat(const From& from) { - if (from > std::numeric_limits::max()){ + if (from > std::numeric_limits::max()) + { throw RangeException("Value too large."); } } @@ -181,7 +186,8 @@ inline void checkUpperLimitFloat(const From& from) template inline void checkLowerLimitFloat(const From& from) { - if (from < -std::numeric_limits::max()){ + if (from < -std::numeric_limits::max()) + { throw RangeException("Value too small."); } } @@ -189,7 +195,8 @@ inline void checkLowerLimitFloat(const From& from) template inline void checkLowerLimit(const From& from) { - if (from < std::numeric_limits::min()){ + if (from < std::numeric_limits::min()) + { throw RangeException("Value too small."); } } @@ -197,139 +204,150 @@ inline void checkLowerLimit(const From& from) template inline void checkTruncation(const From& from) { - if(from != static_cast(static_cast( from))){ + if (from != static_cast(static_cast(from))) + { throw RangeException("Floating point truncated"); } } - //----------------------- Implementation ---------------------------------------------- -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { target = from; } - -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template < + typename SRC, typename DST, + typename details::EnableIf>* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - target = static_cast( from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - if(!std::isnan(from)) { - checkTruncation(from); + if (!std::isnan(from)) + { + checkTruncation(from); } - target = static_cast( from ); + target = static_cast(from); } - -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = + nullptr> +inline void convert_impl(const SRC& from, DST& target) { - checkUpperLimit(from); + checkUpperLimit(from); target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = + nullptr> +inline void convert_impl(const SRC& from, DST& target) { - checkLowerLimit(from); - checkUpperLimit(from); - target = static_cast( from); + checkLowerLimit(from); + checkUpperLimit(from); + target = static_cast(from); } - -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - if (from < 0){ + if (from < 0) + { throw RangeException("Value is negative and can't be converted to signed"); } - checkUpperLimit(from); - target = static_cast( from); + checkUpperLimit(from); + target = static_cast(from); } - -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - if (from < 0){ + if (from < 0) + { throw RangeException("Value is negative and can't be converted to signed"); } - target = static_cast( from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - target = static_cast( from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - checkUpperLimit(from); - target = static_cast( from); + checkUpperLimit(from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = + nullptr> +inline void convert_impl(const SRC& from, DST& target) { - checkLowerLimitFloat(from); - checkUpperLimitFloat(from); + checkLowerLimitFloat(from); + checkUpperLimitFloat(from); - if( from != static_cast(static_cast( from))){ - throw RangeException("Floating point truncated"); + if (from != static_cast(static_cast(from))) + { + throw RangeException("Floating point truncated"); } - target = static_cast( from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = nullptr> +inline void convert_impl(const SRC& from, DST& target) { - if (from < 0 ){ + if (from < 0) + { throw RangeException("Value is negative and can't be converted to signed"); } - checkLowerLimitFloat(from); + checkLowerLimitFloat(from); - if( from != static_cast(static_cast( from))){ + if (from != static_cast(static_cast(from))) + { throw RangeException("Floating point truncated"); } - target = static_cast( from); + target = static_cast(from); } -template>* = nullptr > -inline void convert_impl( const SRC& from, DST& target ) +template >* = + nullptr> +inline void convert_impl(const SRC& from, DST& target) { - checkTruncation(from); - target = static_cast( from); + checkTruncation(from); + target = static_cast(from); } -} //end namespace details - -} //end namespace +} // end namespace details -#endif // VARIANT_H +} // namespace RosMsgParser +#endif // VARIANT_H diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/exceptions.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/exceptions.hpp index 84558dc06..01f8ed00d 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/exceptions.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/details/exceptions.hpp @@ -1,37 +1,36 @@ /********************************************************************* -* Software License Agreement (BSD License) -* -* Copyright 2016-2017 Davide Faconti -* 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 Willow Garage, Inc. 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. -* *******************************************************************/ - + * Software License Agreement (BSD License) + * + * Copyright 2016-2017 Davide Faconti + * 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 Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * *******************************************************************/ #ifndef VARIANT_NUMBER_EXCEPTIONS_H #define VARIANT_NUMBER_EXCEPTIONS_H @@ -42,38 +41,48 @@ namespace RosMsgParser { -class RangeException: public std::exception +class RangeException : public std::exception { public: - - explicit RangeException(const char* message): msg_(message) {} - explicit RangeException(const std::string& message): msg_(message) {} - ~RangeException() throw () {} - const char* what() const throw () - { - return msg_.c_str(); - } + explicit RangeException(const char* message) : msg_(message) + { + } + explicit RangeException(const std::string& message) : msg_(message) + { + } + ~RangeException() throw() + { + } + const char* what() const throw() + { + return msg_.c_str(); + } protected: - std::string msg_; + std::string msg_; }; -class TypeException: public std::exception +class TypeException : public std::exception { public: - - explicit TypeException(const char* message): msg_(message) {} - explicit TypeException(const std::string& message): msg_(message) {} - ~TypeException() throw () {} - const char* what() const throw () - { - return msg_.c_str(); - } + explicit TypeException(const char* message) : msg_(message) + { + } + explicit TypeException(const std::string& message) : msg_(message) + { + } + ~TypeException() throw() + { + } + const char* what() const throw() + { + return msg_.c_str(); + } protected: - std::string msg_; + std::string msg_; }; -} //end namespace +} // namespace RosMsgParser #endif diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_field.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_field.hpp index 6d08ba763..e7e2d8e28 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_field.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_field.hpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #pragma once @@ -30,7 +30,8 @@ #include #include "rosx_introspection/ros_type.hpp" -namespace RosMsgParser{ +namespace RosMsgParser +{ class ROSMessage; @@ -42,19 +43,27 @@ class Parser; * @brief A ROSMessage will contain one or more ROSField(s). Each field is little more * than a name / type pair. */ -class ROSField { - +class ROSField +{ public: + ROSField(const ROSType& type, const std::string& name); - ROSField(const ROSType& type, const std::string& name ); - - ROSField(const std::string& definition ); + ROSField(const std::string& definition); - const std::string& name() const { return _fieldname; } + const std::string& name() const + { + return _fieldname; + } - const ROSType& type() const { return _type; } + const ROSType& type() const + { + return _type; + } - void changeType(const ROSType& type) { _type = type; } + void changeType(const ROSType& type) + { + _type = type; + } /// True if field is a constant in message definition bool isConstant() const @@ -63,14 +72,23 @@ class ROSField { } /// If constant, value of field, else undefined - const std::string& value() const { return _value; } + const std::string& value() const + { + return _value; + } /// True if the type is an array - bool isArray() const { return _is_array; } + bool isArray() const + { + return _is_array; + } /// 1 if !is_array, -1 if is_array and array is /// variable length, otherwise length in name - int arraySize() const { return _array_size; } + int arraySize() const + { + return _array_size; + } friend class ROSMessage; @@ -78,7 +96,7 @@ class ROSField { protected: std::string _fieldname; - ROSType _type; + ROSType _type; std::string _value; bool _is_array; bool _is_constant = false; @@ -94,6 +112,4 @@ void TrimStringRight(std::string& s); void TrimString(std::string& s); -} - - +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_message.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_message.hpp index 90f121a04..24d28ee0c 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_message.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_message.hpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ #ifndef ROS_INTROSPECTION_ROSMESSAGE_H #define ROS_INTROSPECTION_ROSMESSAGE_H @@ -38,20 +38,34 @@ class ROSMessage /// This constructor does most of the work in terms of parsing. /// It uses the message definition to extract fields and types. - ROSMessage(const std::string& msg_def ); + ROSMessage(const std::string& msg_def); - const ROSField& field(size_t i) const { return _fields[i]; } + const ROSField& field(size_t i) const + { + return _fields[i]; + } - const std::vector& fields() const { return _fields; } + const std::vector& fields() const + { + return _fields; + } - std::vector& fields() { return _fields; } + std::vector& fields() + { + return _fields; + } - const ROSType& type() const { return _type; } + const ROSType& type() const + { + return _type; + } - void setType(const ROSType& new_type ) { _type = new_type; } + void setType(const ROSType& new_type) + { + _type = new_type; + } private: - ROSType _type; std::vector _fields; }; @@ -64,31 +78,31 @@ struct MessageSchema using Ptr = std::shared_ptr; std::string topic_name; - FieldTree field_tree; + FieldTree field_tree; ROSMessage::Ptr root_msg; RosMessageLibrary msg_library; }; //------------------------------------------------ -inline std::ostream& operator<<(std::ostream &os, const ROSMessage& msg ) +inline std::ostream& operator<<(std::ostream& os, const ROSMessage& msg) { os << msg.type(); return os; } -inline std::ostream& operator<<(std::ostream &os, const ROSMessage* msg ) +inline std::ostream& operator<<(std::ostream& os, const ROSMessage* msg) { os << msg->type(); return os; } std::vector ParseMessageDefinitions(const std::string& multi_def, - const ROSType &type); + const ROSType& type); MessageSchema::Ptr BuildMessageSchema(const std::string& topic_name, - const std::vector& parsed_msgs); + const std::vector& parsed_msgs); -} +} // namespace RosMsgParser #endif diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_parser.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_parser.hpp index 8faf616cd..2b05e7103 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_parser.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_parser.hpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #pragma once #include @@ -27,29 +27,29 @@ #include "rosx_introspection/stringtree_leaf.hpp" #include "rosx_introspection/deserializer.hpp" -namespace RosMsgParser{ - -struct FlatMessage { +namespace RosMsgParser +{ +struct FlatMessage +{ std::shared_ptr schema; /// List of all those parsed fields that can be represented by a /// builtin value different from "string". - std::vector< std::pair > value; + std::vector> value; /// List of all those parsed fields that can be represented by a "string". - std::vector< std::pair > name; + std::vector> name; /// Store "blobs", i.e all those fields which are vectors of BYTES (AKA uint8_t), /// where the vector size is greater than the argument [max_array_size]. - std::vector< std::pair>> blob; + std::vector>> blob; std::vector> blob_storage; }; - -class Parser{ - +class Parser +{ public: /** * @@ -60,25 +60,25 @@ class Parser{ * - rosbag::MessageInstance::getMessageDefinition() * - ros::message_traits::Definition< __your_type__ >::value() * */ - Parser(const std::string& topic_name, - const ROSType& msg_type, + Parser(const std::string& topic_name, const ROSType& msg_type, const std::string& definition); - enum MaxArrayPolicy: bool { + enum MaxArrayPolicy : bool + { DISCARD_LARGE_ARRAYS = true, KEEP_LARGE_ARRAYS = false }; /// Default values are DISCARD_LARGE_ARRAYS and 100. /// The maximum permissible value of max_array_size is 10.000 (but don't) - void setMaxArrayPolicy( MaxArrayPolicy discard_entire_array, size_t max_array_size ) + void setMaxArrayPolicy(MaxArrayPolicy discard_entire_array, size_t max_array_size) { - _discard_large_array = discard_entire_array; - _max_array_size = max_array_size; - if( _max_array_size > 10000 ) - { - throw std::runtime_error("max_array_size limited to 10000 at most"); - } + _discard_large_array = discard_entire_array; + _max_array_size = max_array_size; + if (_max_array_size > 10000) + { + throw std::runtime_error("max_array_size limited to 10000 at most"); + } } MaxArrayPolicy maxArrayPolicy() const @@ -91,15 +91,17 @@ class Parser{ return _max_array_size; } - enum BlobPolicy { + enum BlobPolicy + { STORE_BLOB_AS_COPY, - STORE_BLOB_AS_REFERENCE}; + STORE_BLOB_AS_REFERENCE + }; - // If set to STORE_BLOB_AS_COPY, a copy of the original vector will be stored in the FlatMessage. - // This may have a large impact on performance. - // if STORE_BLOB_AS_REFERENCE is used instead, it is dramatically faster, but you must be careful with - // dangling pointers. - void setBlobPolicy( BlobPolicy policy ) + // If set to STORE_BLOB_AS_COPY, a copy of the original vector will be stored in the + // FlatMessage. This may have a large impact on performance. if STORE_BLOB_AS_REFERENCE + // is used instead, it is dramatically faster, but you must be careful with dangling + // pointers. + void setBlobPolicy(BlobPolicy policy) { _blob_policy = policy; } @@ -119,8 +121,8 @@ class Parser{ /** * @brief deserializeIntoFlatContainer takes a raw buffer of memory * and extract information from it. - * This data is stored in two key/value vectors, FlatMessage::value and FlatMessage::name. - * It must be noted that the key type is FieldsVector. This type is + * This data is stored in two key/value vectors, FlatMessage::value and + * FlatMessage::name. It must be noted that the key type is FieldsVector. This type is * not particularly user-friendly, but allows a much faster post-processing. * * IMPORTANT: this approach is not meant to be used with use arrays such as maps, @@ -137,9 +139,8 @@ class Parser{ * @return true if the entire message was parsed or false if parts of the message were * skipped because an array has (size > max_array_size) */ - bool deserialize(Span buffer, - FlatMessage* flat_output, - Deserializer *deserializer) const; + bool deserialize(Span buffer, FlatMessage* flat_output, + Deserializer* deserializer) const; typedef std::function&)> VisitingCallback; @@ -148,22 +149,26 @@ class Parser{ * a chunk of memory storing an instance of ROSType = monitored_type * is reached. * Note that the VisitingCallback can modify the original message, but can NOT - * change its size. This means that strings and vectors can not be change their length. + * change its size. This means that strings and vectors can not be change their + * length. * - * @param msg_identifier String ID to identify the registered message (use registerMessageDefinition first). + * @param msg_identifier String ID to identify the registered message (use + * registerMessageDefinition first). * @param monitored_type ROSType that triggers the invokation to the callback - * @param buffer Original buffer, passed as mutable since it might be modified. + * @param buffer Original buffer, passed as mutable since it might be + * modified. * @param callback The callback. */ - void applyVisitorToBuffer(const ROSType &msg_type, - Span &buffer, + void applyVisitorToBuffer(const ROSType& msg_type, Span& buffer, VisitingCallback callback) const; /// Change where the warning messages are displayed. - void setWarningsStream(std::ostream* output) { _global_warnings = output; } + void setWarningsStream(std::ostream* output) + { + _global_warnings = output; + } private: - std::shared_ptr _schema; std::ostream* _global_warnings; @@ -181,23 +186,20 @@ class Parser{ std::unique_ptr _deserializer; }; -typedef std::vector > RenamedValues; +typedef std::vector> RenamedValues; void CreateRenamedValues(const FlatMessage& flat_msg, RenamedValues& renamed); - template -class ParsersCollection{ - +class ParsersCollection +{ public: - ParsersCollection() { _deserializer = std::make_unique(); } - void registerParser(const std::string& topic_name, - const ROSType& msg_type, + void registerParser(const std::string& topic_name, const ROSType& msg_type, const std::string& definition) { if (_pack.count(topic_name) == 0) @@ -218,7 +220,7 @@ class ParsersCollection{ return nullptr; } - const FlatMessage *deserialize(const std::string& topic_name, + const FlatMessage* deserialize(const std::string& topic_name, Span buffer) { auto it = _pack.find(topic_name); @@ -234,7 +236,8 @@ class ParsersCollection{ } private: - struct CachedPack{ + struct CachedPack + { Parser parser; FlatMessage msg; }; @@ -243,7 +246,4 @@ class ParsersCollection{ std::unique_ptr _deserializer; }; - - -} - +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_type.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_type.hpp index 79b2bf0b5..3765f6978 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_type.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/ros_type.hpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ #ifndef ROS_INTROSPECTION_ROSTYPE_H #define ROS_INTROSPECTION_ROSTYPE_H @@ -30,35 +30,44 @@ #include #include "rosx_introspection/variant.hpp" -namespace RosMsgParser{ +namespace RosMsgParser +{ /** * @brief ROSType */ -class ROSType { +class ROSType +{ public: - - ROSType(){} + ROSType() + { + } ROSType(const std::string& name); - ROSType(const ROSType& other) { *this = other; } + ROSType(const ROSType& other) + { + *this = other; + } - ROSType(ROSType&& other) { *this = other; } + ROSType(ROSType&& other) + { + *this = other; + } - ROSType& operator= (const ROSType& other); + ROSType& operator=(const ROSType& other); - ROSType& operator= (ROSType&& other); + ROSType& operator=(ROSType&& other); /// Concatenation of msg_name and pkg_name. /// ex.: geometry_msgs/Pose" const std::string& baseName() const; /// ex.: geometry_msgs/Pose -> "Pose" - const std::string_view& msgName() const; + const std::string_view& msgName() const; /// ex.: geometry_msgs/Pose -> "geometry_msgs" - const std::string_view& pkgName() const; + const std::string_view& pkgName() const; void setPkgName(std::string_view new_pkg); @@ -71,33 +80,37 @@ class ROSType { /// If type is builtin, returns the id. BuiltinType::OTHER otherwise. BuiltinType typeID() const; - bool operator==(const ROSType& other) const { + bool operator==(const ROSType& other) const + { return _hash == other._hash; } - bool operator!=(const ROSType& other) const { + bool operator!=(const ROSType& other) const + { return (_hash != other._hash); } - bool operator<(const ROSType& other) const { + bool operator<(const ROSType& other) const + { return this->baseName() < other.baseName(); } - size_t hash() const { return _hash; } + size_t hash() const + { + return _hash; + } protected: - BuiltinType _id = OTHER; std::string _base_name; std::string_view _msg_name; std::string_view _pkg_name; size_t _hash = 0; - }; //----------- definitions ------------- -inline const std::string &ROSType::baseName() const +inline const std::string& ROSType::baseName() const { return _base_name; } @@ -107,7 +120,7 @@ inline const std::string_view& ROSType::msgName() const return _msg_name; } -inline const std::string_view &ROSType::pkgName() const +inline const std::string_view& ROSType::pkgName() const { return _pkg_name; } @@ -119,7 +132,7 @@ inline bool ROSType::isBuiltin() const inline int ROSType::typeSize() const { - return builtinSize( _id ); + return builtinSize(_id); } inline BuiltinType ROSType::typeID() const @@ -129,50 +142,41 @@ inline BuiltinType ROSType::typeID() const //--------- helper functions -------------- -inline std::ostream& operator<<(std::ostream &os, const ROSType& t ) +inline std::ostream& operator<<(std::ostream& os, const ROSType& t) { os << t.baseName(); return os; } -inline BuiltinType toBuiltinType(const std::string_view& s) { - static std::map string_to_builtin_map { - { "bool", BOOL }, - { "byte", BYTE }, - { "char", CHAR }, - { "uint8", UINT8 }, - { "uint16", UINT16 }, - { "uint32", UINT32 }, - { "uint64", UINT64 }, - { "int8", INT8 }, - { "int16", INT16 }, - { "int32", INT32 }, - { "int64", INT64 }, - { "float32", FLOAT32 }, - { "float64", FLOAT64 }, - { "time", TIME }, - { "duration", DURATION }, +inline BuiltinType toBuiltinType(const std::string_view& s) +{ + static std::map string_to_builtin_map{ + { "bool", BOOL }, { "byte", BYTE }, { "char", CHAR }, + { "uint8", UINT8 }, { "uint16", UINT16 }, { "uint32", UINT32 }, + { "uint64", UINT64 }, { "int8", INT8 }, { "int16", INT16 }, + { "int32", INT32 }, { "int64", INT64 }, { "float32", FLOAT32 }, + { "float64", FLOAT64 }, { "time", TIME }, { "duration", DURATION }, { "string", STRING }, }; const auto it = string_to_builtin_map.find(s); return (it != string_to_builtin_map.cend()) ? it->second : OTHER; } -} - -namespace std { - template <> struct hash - { - - typedef RosMsgParser::ROSType argument_type; - typedef std::size_t result_type; +} // namespace RosMsgParser - result_type operator()(RosMsgParser::ROSType const& type) const - { - return type.hash(); - } - }; -} +namespace std +{ +template <> +struct hash +{ + typedef RosMsgParser::ROSType argument_type; + typedef std::size_t result_type; + result_type operator()(RosMsgParser::ROSType const& type) const + { + return type.hash(); + } +}; +} // namespace std -#endif // ROSTYPE_H +#endif // ROSTYPE_H diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/stringtree_leaf.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/stringtree_leaf.hpp index ff2e0420b..20c70e056 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/stringtree_leaf.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/stringtree_leaf.hpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + */ #ifndef ROS_INTROSPECTION_FieldTreeLeaf_H #define ROS_INTROSPECTION_FieldTreeLeaf_H @@ -33,34 +33,36 @@ // Brutally faster for numbers below 100 inline int print_number(char* buffer, uint16_t value) { - const char DIGITS[] = - "00010203040506070809" - "10111213141516171819" - "20212223242526272829" - "30313233343536373839" - "40414243444546474849" - "50515253545556575859" - "60616263646566676869" - "70717273747576777879" - "80818283848586878889" - "90919293949596979899"; + const char DIGITS[] = "00010203040506070809" + "10111213141516171819" + "20212223242526272829" + "30313233343536373839" + "40414243444546474849" + "50515253545556575859" + "60616263646566676869" + "70717273747576777879" + "80818283848586878889" + "90919293949596979899"; if (value < 10) { buffer[0] = static_cast('0' + value); return 1; } - else if (value < 100) { + else if (value < 100) + { value *= 2; - buffer[0] = DIGITS[ value ]; - buffer[1] = DIGITS[ value+1 ]; + buffer[0] = DIGITS[value]; + buffer[1] = DIGITS[value + 1]; return 2; } - else{ - return sprintf( buffer,"%d", value ); + else + { + return sprintf(buffer, "%d", value); } } -namespace RosMsgParser{ +namespace RosMsgParser +{ /** * @brief The FieldTreeLeaf is, as the name suggests, a leaf (terminal node) @@ -72,8 +74,8 @@ namespace RosMsgParser{ * * foo/2/bar/3/hello/world * - * This would correspond to a branch of the tree (from root to the leaf) equal to these 6 nodes, - * where "foo" is the root and "world" is the leaf + * This would correspond to a branch of the tree (from root to the leaf) equal to these 6 + * nodes, where "foo" is the root and "world" is the leaf * * foo -> # -> bar -> # ->hello -> world * @@ -96,7 +98,7 @@ struct FieldsVector SmallVector index_array; /// Utility functions to print the entire branch - void toStr(std::string &destination) const; + void toStr(std::string& destination) const; std::string toStdString() const { @@ -108,7 +110,7 @@ struct FieldsVector //--------------------------------- -inline std::ostream& operator<<(std::ostream &os, const FieldsVector& leaf ) +inline std::ostream& operator<<(std::ostream& os, const FieldsVector& leaf) { std::string dest; leaf.toStr(dest); @@ -116,7 +118,6 @@ inline std::ostream& operator<<(std::ostream &os, const FieldsVector& leaf ) return os; } +} // namespace RosMsgParser -} - -#endif // ROSTYPE_H +#endif // ROSTYPE_H diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/tree.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/tree.hpp index 525245475..7739477cf 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/tree.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/tree.hpp @@ -1,37 +1,36 @@ /********************************************************************* -* Software License Agreement (BSD License) -* -* Copyright 2016-2017 Davide Faconti -* 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 Willow Garage, Inc. 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. -* *******************************************************************/ - + * Software License Agreement (BSD License) + * + * Copyright 2016-2017 Davide Faconti + * 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 Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * *******************************************************************/ #ifndef STRINGTREE_H #define STRINGTREE_H @@ -43,65 +42,100 @@ #include "rosx_introspection/builtin_types.hpp" -namespace RosMsgParser { +namespace RosMsgParser +{ -namespace details{ +namespace details +{ /** * @brief Element of the tree. it has a single parent and N >= 0 children. */ -template class TreeNode +template +class TreeNode { - public: + typedef std::vector ChildrenVector; // dangerous because of pointer + // invalidation (but faster) - typedef std::vector ChildrenVector; // dangerous because of pointer invalidation (but faster) - - TreeNode(const TreeNode* parent ); + TreeNode(const TreeNode* parent); - const TreeNode* parent() const { return _parent; } + const TreeNode* parent() const + { + return _parent; + } - const T& value() const { return _value; } - void setValue( const T& value) { _value = value; } + const T& value() const + { + return _value; + } + void setValue(const T& value) + { + _value = value; + } - const ChildrenVector& children()const { return _children; } - ChildrenVector& children() { return _children; } + const ChildrenVector& children() const + { + return _children; + } + ChildrenVector& children() + { + return _children; + } - const TreeNode* child(size_t index) const { return &(_children[index]); } - TreeNode* child(size_t index) { return &(_children[index]); } + const TreeNode* child(size_t index) const + { + return &(_children[index]); + } + TreeNode* child(size_t index) + { + return &(_children[index]); + } - TreeNode *addChild(const T& child ); + TreeNode* addChild(const T& child); - bool isLeaf() const { return _children.empty(); } + bool isLeaf() const + { + return _children.empty(); + } private: - const TreeNode* _parent = nullptr; - T _value; - ChildrenVector _children; + const TreeNode* _parent = nullptr; + T _value; + ChildrenVector _children; }; - -template class Tree +template +class Tree { public: - Tree(): _root( new TreeNode(nullptr) ) {} + Tree() : _root(new TreeNode(nullptr)) + { + } /** - * Find a set of elements in the tree and return the pointer to the leaf. - * The first element of the concatenated_values should be a root of the Tree. - * The leaf corresponds to the last element of concatenated_values in the Tree. - */ - template const TreeNode* find( const Vect& concatenated_values, bool partial_allowed = false); + * Find a set of elements in the tree and return the pointer to the leaf. + * The first element of the concatenated_values should be a root of the Tree. + * The leaf corresponds to the last element of concatenated_values in the Tree. + */ + template + const TreeNode* find(const Vect& concatenated_values, bool partial_allowed = false); /// Constant pointer to the root of the tree. - const TreeNode* croot() const { return _root.get(); } + const TreeNode* croot() const + { + return _root.get(); + } /// Mutable pointer to the root of the tree. - TreeNode* root() { return _root.get(); } - + TreeNode* root() + { + return _root.get(); + } - friend std::ostream& operator<<(std::ostream& os, const Tree& _this){ - _this.print_impl(os, _this.croot() , 0); + friend std::ostream& operator<<(std::ostream& os, const Tree& _this) + { + _this.print_impl(os, _this.croot(), 0); return os; } @@ -109,35 +143,35 @@ template class Tree void visit(Functor& func, const TreeNode* node) const { func(node); - for(auto child: node->children()) + for (auto child : node->children()) { visit(func, &child); } } private: - - void print_impl(std::ostream& os, const TreeNode *node, int indent ) const; + void print_impl(std::ostream& os, const TreeNode* node, int indent) const; std::unique_ptr> _root; }; //----------------------------------------- - -template inline -std::ostream& operator<<(std::ostream &os, const std::pair*, const TreeNode* >& tail_head ) +template +inline std::ostream& operator<<( + std::ostream& os, const std::pair*, const TreeNode*>& tail_head) { const TreeNode* tail = tail_head.first; const TreeNode* head = tail_head.second; - if( !head ) return os; + if (!head) + return os; const TreeNode* array[64]; int index = 0; array[index++] = head; - while( !head || head != tail) + while (!head || head != tail) { head = head->parent(); array[index++] = head; @@ -145,77 +179,79 @@ std::ostream& operator<<(std::ostream &os, const std::pair*, c array[index] = nullptr; index--; - while ( index >=0) + while (index >= 0) { - if( array[index] ){ + if (array[index]) + { os << array[index]->value(); } - if( index >0 ) os << "."; + if (index > 0) + os << "."; index--; } return os; } -template inline -void Tree::print_impl(std::ostream &os, const TreeNode* node, int indent) const +template +inline void Tree::print_impl(std::ostream& os, const TreeNode* node, + int indent) const { - for (int i=0; ivalue() << std::endl; - for (const auto& child: node->children() ) + for (const auto& child : node->children()) { - print_impl(os, &child, indent+3); + print_impl(os, &child, indent + 3); } } -template inline -TreeNode::TreeNode(const TreeNode *parent): - _parent(parent) +template +inline TreeNode::TreeNode(const TreeNode* parent) : _parent(parent) { - } -template inline -TreeNode *TreeNode::addChild(const T& value) +template +inline TreeNode* TreeNode::addChild(const T& value) { - assert(_children.capacity() > _children.size() ); - _children.emplace_back( this ); - _children.back().setValue( value ); + assert(_children.capacity() > _children.size()); + _children.emplace_back(this); + _children.back().setValue(value); return &_children.back(); } - -template template inline -const TreeNode *Tree::find(const Vect& concatenated_values, bool partial_allowed ) +template +template +inline const TreeNode* Tree::find(const Vect& concatenated_values, + bool partial_allowed) { TreeNode* node = &_root; - for (const auto& value: concatenated_values) + for (const auto& value : concatenated_values) { bool found = false; - for (auto& child: (node->children() ) ) + for (auto& child : (node->children())) { - if( child.value() == value) + if (child.value() == value) { node = &(child); found = true; break; } } - if( !found ) return nullptr; + if (!found) + return nullptr; } - if( partial_allowed || node->children().empty() ) + if (partial_allowed || node->children().empty()) { - return node; + return node; } return nullptr; } -} - -} - +} // namespace details +} // namespace RosMsgParser -#endif // STRINGTREE_H +#endif // STRINGTREE_H diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/variant.hpp b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/variant.hpp index ea4aac51f..ba4a77c01 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/variant.hpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/include/rosx_introspection/variant.hpp @@ -1,36 +1,36 @@ /********************************************************************* -* Software License Agreement (BSD License) -* -* Copyright 2016-2017 Davide Faconti -* 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 Willow Garage, Inc. 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. -* *******************************************************************/ + * Software License Agreement (BSD License) + * + * Copyright 2016-2017 Davide Faconti + * 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 Willow Garage, Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS + * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE + * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, + * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER + * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN + * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE + * POSSIBILITY OF SUCH DAMAGE. + * *******************************************************************/ #ifndef VARIANT_H #define VARIANT_H @@ -48,73 +48,79 @@ namespace RosMsgParser class Variant { - public: - - Variant() { + Variant() + { _type = OTHER; _storage.raw_string = nullptr; } ~Variant(); - Variant(const Variant& other): _type(OTHER) + Variant(const Variant& other) : _type(OTHER) { - if( other._type == STRING) + if (other._type == STRING) { const char* raw = other._storage.raw_string; - const uint32_t size = *(reinterpret_cast( &raw[0] )); + const uint32_t size = *(reinterpret_cast(&raw[0])); const char* data = (&raw[4]); - assign( data, size ); + assign(data, size); } - else{ + else + { _type = other._type; _storage.raw_data = other._storage.raw_data; } } - Variant(Variant&& other): _type(OTHER) + Variant(Variant&& other) : _type(OTHER) { - if( other._type == STRING) + if (other._type == STRING) { _storage.raw_string = nullptr; - std::swap( _storage.raw_string, other._storage.raw_string); - std::swap( _type, other._type); + std::swap(_storage.raw_string, other._storage.raw_string); + std::swap(_type, other._type); } - else{ + else + { _type = other._type; _storage.raw_data = other._storage.raw_data; } } - Variant& operator = (const Variant& other) + Variant& operator=(const Variant& other) { - if( other._type == STRING) + if (other._type == STRING) { const char* raw = other._storage.raw_string; - const uint32_t size = *(reinterpret_cast( &raw[0] )); + const uint32_t size = *(reinterpret_cast(&raw[0])); const char* data = (&raw[4]); - assign( data, size ); + assign(data, size); } - else{ + else + { _type = other._type; _storage.raw_data = other._storage.raw_data; } return *this; } - template Variant(const T& value); + template + Variant(const T& value); // specialization for raw string Variant(const char* buffer, size_t length); BuiltinType getTypeID() const; - template T convert( ) const; + template + T convert() const; - template T extract( ) const; + template + T extract() const; - template void assign(const T& value); + template + void assign(const T& value); void assign(const char* buffer, size_t length); @@ -122,39 +128,36 @@ class Variant const uint8_t* getRawStorage() const; private: - - union { - std::array raw_data; + union + { + std::array raw_data; char* raw_string; - }_storage; + } _storage; void clearStringIfNecessary(); BuiltinType _type; }; - //----------------------- Implementation ---------------------------------------------- - -template -inline Variant::Variant(const T& value): - _type(OTHER) +template +inline Variant::Variant(const T& value) : _type(OTHER) { - static_assert (std::numeric_limits::is_specialized || - std::is_same::value || - std::is_same::value || - std::is_same::value - , "not a valid type"); + static_assert(std::numeric_limits::is_specialized || + std::is_same::value || + std::is_same::value || + std::is_same::value, + "not a valid type"); _storage.raw_string = (nullptr); assign(value); } -inline Variant::Variant(const char* buffer, size_t length):_type(OTHER) +inline Variant::Variant(const char* buffer, size_t length) : _type(OTHER) { _storage.raw_string = (nullptr); - assign(buffer,length); + assign(buffer, length); } inline Variant::~Variant() @@ -164,68 +167,73 @@ inline Variant::~Variant() //------------------------------------- -inline BuiltinType Variant::getTypeID() const { +inline BuiltinType Variant::getTypeID() const +{ return _type; } -inline const uint8_t* Variant::getRawStorage() const { - return _storage.raw_data.data(); +inline const uint8_t* Variant::getRawStorage() const +{ + return _storage.raw_data.data(); } -template inline T Variant::extract( ) const +template +inline T Variant::extract() const { - static_assert (std::numeric_limits::is_specialized || - std::is_same::value - , "not a valid type"); + static_assert(std::numeric_limits::is_specialized || + std::is_same::value, + "not a valid type"); - if( _type != RosMsgParser::getType() ) + if (_type != RosMsgParser::getType()) { throw TypeException("Variant::extract -> wrong type"); } - return * reinterpret_cast( &_storage.raw_data[0] ); + return *reinterpret_cast(&_storage.raw_data[0]); } -template<> inline std::string_view Variant::extract( ) const +template <> +inline std::string_view Variant::extract() const { - - if( _type != STRING ) + if (_type != STRING) { throw TypeException("Variant::extract -> wrong type"); } - const uint32_t size = *(reinterpret_cast( &_storage.raw_string[0] )); + const uint32_t size = *(reinterpret_cast(&_storage.raw_string[0])); char* data = static_cast(&_storage.raw_string[4]); return std::string_view(data, size); } -template<> inline std::string Variant::extract( ) const +template <> +inline std::string Variant::extract() const { - if( _type != STRING ) + if (_type != STRING) { throw TypeException("Variant::extract -> wrong type"); } - const uint32_t size = *(reinterpret_cast( &_storage.raw_string[0] )); + const uint32_t size = *(reinterpret_cast(&_storage.raw_string[0])); char* data = static_cast(&_storage.raw_string[4]); return std::string(data, size); } //------------------------------------- -template inline void Variant::assign(const T& value) +template +inline void Variant::assign(const T& value) { - static_assert (std::numeric_limits::is_specialized || - std::is_same::value - , "not a valid type"); + static_assert(std::numeric_limits::is_specialized || + std::is_same::value, + "not a valid type"); clearStringIfNecessary(); - _type = RosMsgParser::getType() ; - *reinterpret_cast( &_storage.raw_data[0] ) = value; + _type = RosMsgParser::getType(); + *reinterpret_cast(&_storage.raw_data[0]) = value; } inline void Variant::clearStringIfNecessary() { - if( _storage.raw_string && _type == STRING) + if (_storage.raw_string && _type == STRING) { - delete [] _storage.raw_string; + delete[] _storage.raw_string; _storage.raw_string = nullptr; } } @@ -235,134 +243,186 @@ inline void Variant::assign(const char* buffer, size_t size) clearStringIfNecessary(); _type = STRING; - _storage.raw_string = new char[size+5]; - *reinterpret_cast( &_storage.raw_string[0] ) = size; - memcpy(&_storage.raw_string[4] , buffer, size ); - _storage.raw_string[size+4] = '\0'; + _storage.raw_string = new char[size + 5]; + *reinterpret_cast(&_storage.raw_string[0]) = size; + memcpy(&_storage.raw_string[4], buffer, size); + _storage.raw_string[size + 4] = '\0'; } - - -template <> inline void Variant::assign(const std::string_view& value) +template <> +inline void Variant::assign(const std::string_view& value) { - assign( value.data(), value.size() ); + assign(value.data(), value.size()); } -template <> inline void Variant::assign(const std::string& value) +template <> +inline void Variant::assign(const std::string& value) { - assign( value.data(), value.size() ); + assign(value.data(), value.size()); } //------------------------------------- -template inline DST Variant::convert() const +template +inline DST Variant::convert() const { - static_assert (std::numeric_limits::is_specialized || - std::is_same::value - , "not a valid type"); + static_assert(std::numeric_limits::is_specialized || + std::is_same::value, + "not a valid type"); using namespace RosMsgParser::details; DST target; const auto& raw_data = &_storage.raw_data[0]; //---------- - switch( _type ) + switch (_type) { - case CHAR: - case INT8: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case INT16: convert_impl(*reinterpret_cast( raw_data), target ); break; - case INT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case INT64: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case BOOL: - case BYTE: - case UINT8: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case UINT16: convert_impl(*reinterpret_cast( raw_data), target ); break; - case UINT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case UINT64: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case FLOAT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case FLOAT64: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case STRING: { - throw TypeException("String will not be converted to a numerical value implicitly"); - } break; - - case DURATION: - case TIME: { - throw TypeException("ros::Duration and ros::Time can be converted only to double (will be seconds)"); - } break; + case CHAR: + case INT8: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case INT16: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case INT32: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case INT64: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case BOOL: + case BYTE: + case UINT8: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case UINT16: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case UINT32: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case UINT64: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case FLOAT32: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case FLOAT64: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case STRING: { + throw TypeException("String will not be converted to a numerical value implicitly"); + } + break; - default: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type)); break; + case DURATION: + case TIME: { + throw TypeException("ros::Duration and ros::Time can be converted only to double " + "(will be seconds)"); + } + break; + default: + throw TypeException("Variant::convert -> cannot convert type" + + std::to_string(_type)); + break; } - return target; + return target; } -template<> inline double Variant::convert() const +template <> +inline double Variant::convert() const { using namespace RosMsgParser::details; double target = 0; const auto& raw_data = &_storage.raw_data[0]; //---------- - switch( _type ) + switch (_type) { - case CHAR: - case INT8: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case INT16: convert_impl(*reinterpret_cast( raw_data), target ); break; - case INT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case INT64: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case BOOL: - case BYTE: - case UINT8: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case UINT16: convert_impl(*reinterpret_cast( raw_data), target ); break; - case UINT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case UINT64: convert_impl(*reinterpret_cast( raw_data), target ); break; - - case FLOAT32: convert_impl(*reinterpret_cast( raw_data), target ); break; - case FLOAT64: return extract(); - - case STRING: { - throw TypeException("String will not be converted to a double implicitly"); - }break; - - case DURATION: - case TIME: { - RosMsgParser::Time tmp = extract(); - target = tmp.toSec(); - }break; + case CHAR: + case INT8: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case INT16: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case INT32: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case INT64: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case BOOL: + case BYTE: + case UINT8: + convert_impl(*reinterpret_cast(raw_data), target); + break; + + case UINT16: + convert_impl(*reinterpret_cast(raw_data), + target); + break; + case UINT32: + convert_impl(*reinterpret_cast(raw_data), + target); + break; + case UINT64: + convert_impl(*reinterpret_cast(raw_data), + target); + break; + + case FLOAT32: + convert_impl(*reinterpret_cast(raw_data), target); + break; + case FLOAT64: + return extract(); + + case STRING: { + throw TypeException("String will not be converted to a double implicitly"); + } + break; - default: throw TypeException("Variant::convert -> cannot convert type" + std::to_string(_type)); + case DURATION: + case TIME: { + RosMsgParser::Time tmp = extract(); + target = tmp.toSec(); + } + break; + default: + throw TypeException("Variant::convert -> cannot convert type" + + std::to_string(_type)); } - return target; + return target; } -template<> inline RosMsgParser::Time Variant::convert() const +template <> +inline RosMsgParser::Time Variant::convert() const { - if( _type != TIME ) + if (_type != TIME) { - throw TypeException("Variant::convert -> cannot convert RosMsgParser::Time"); + throw TypeException("Variant::convert -> cannot convert RosMsgParser::Time"); } return extract(); } - -template<> inline std::string Variant::convert() const +template <> +inline std::string Variant::convert() const { - if( _type != STRING ) + if (_type != STRING) { - throw TypeException("Variant::convert -> cannot convert to std::string"); + throw TypeException("Variant::convert -> cannot convert to std::string"); } return extract(); } -} //end namespace - +} // namespace RosMsgParser -#endif // VARIANT_H +#endif // VARIANT_H diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/deserializer.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/deserializer.cpp index d242f70cb..10d8082b8 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/deserializer.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/deserializer.cpp @@ -4,26 +4,37 @@ namespace RosMsgParser { - Variant ROS_Deserializer::deserialize(BuiltinType type) { - switch(type) + switch (type) { - case BOOL: return deserialize(); - case CHAR: return deserialize(); + case BOOL: + return deserialize(); + case CHAR: + return deserialize(); case BYTE: - case UINT8: return deserialize(); - case UINT16: return deserialize(); - case UINT32: return deserialize(); - case UINT64: return deserialize(); - - case INT8: return deserialize(); - case INT16: return deserialize(); - case INT32: return deserialize(); - case INT64: return deserialize(); - - case FLOAT32: return deserialize(); - case FLOAT64: return deserialize(); + case UINT8: + return deserialize(); + case UINT16: + return deserialize(); + case UINT32: + return deserialize(); + case UINT64: + return deserialize(); + + case INT8: + return deserialize(); + case INT16: + return deserialize(); + case INT32: + return deserialize(); + case INT64: + return deserialize(); + + case FLOAT32: + return deserialize(); + case FLOAT64: + return deserialize(); case DURATION: case TIME: { @@ -40,22 +51,23 @@ Variant ROS_Deserializer::deserialize(BuiltinType type) return {}; } -void ROS_Deserializer::deserializeString(std::string &dst) +void ROS_Deserializer::deserializeString(std::string& dst) { uint32_t string_size = deserialize(); - if( string_size > _bytes_left ) + if (string_size > _bytes_left) { throw std::runtime_error("Buffer overrun in ROS_Deserializer::deserializeString"); } - if (string_size == 0) { + if (string_size == 0) + { dst = {}; return; } - const char* buffer_ptr = reinterpret_cast( _ptr ); - dst.assign( buffer_ptr, string_size ); + const char* buffer_ptr = reinterpret_cast(_ptr); + dst.assign(buffer_ptr, string_size); _ptr += string_size; _bytes_left -= string_size; @@ -66,14 +78,16 @@ uint32_t ROS_Deserializer::deserializeUInt32() return deserialize(); } -Span ROS_Deserializer::deserializeByteSequence() +Span ROS_Deserializer::deserializeByteSequence() { uint32_t vect_size = deserialize(); - if( vect_size > _bytes_left ) + if (vect_size > _bytes_left) { - throw std::runtime_error("Buffer overrun in ROS_Deserializer::deserializeByteSequence"); + throw std::runtime_error("Buffer overrun in " + "ROS_Deserializer::deserializeByteSequence"); } - if (vect_size == 0) { + if (vect_size == 0) + { return {}; } Span out(_ptr, vect_size); @@ -81,14 +95,14 @@ Span ROS_Deserializer::deserializeByteSequence() return out; } -const uint8_t *ROS_Deserializer::getCurrentPtr() const +const uint8_t* ROS_Deserializer::getCurrentPtr() const { return _ptr; } void ROS_Deserializer::jump(size_t bytes) { - if( bytes > _bytes_left ) + if (bytes > _bytes_left) { throw std::runtime_error("Buffer overrun"); } @@ -114,23 +128,35 @@ static T Deserialize(eprosima::fastcdr::Cdr& cdr) Variant FastCDR_Deserializer::deserialize(BuiltinType type) { - switch(type) + switch (type) { - case BOOL: return Deserialize(*_cdr); - case CHAR: return Deserialize(*_cdr); + case BOOL: + return Deserialize(*_cdr); + case CHAR: + return Deserialize(*_cdr); case BYTE: - case UINT8: return Deserialize(*_cdr); - case UINT16: return Deserialize(*_cdr); - case UINT32: return Deserialize(*_cdr); - case UINT64: return Deserialize(*_cdr); - - case INT8: return Deserialize(*_cdr); - case INT16: return Deserialize(*_cdr); - case INT32: return Deserialize(*_cdr); - case INT64: return Deserialize(*_cdr); - - case FLOAT32: return Deserialize(*_cdr); - case FLOAT64: return Deserialize(*_cdr); + case UINT8: + return Deserialize(*_cdr); + case UINT16: + return Deserialize(*_cdr); + case UINT32: + return Deserialize(*_cdr); + case UINT64: + return Deserialize(*_cdr); + + case INT8: + return Deserialize(*_cdr); + case INT16: + return Deserialize(*_cdr); + case INT32: + return Deserialize(*_cdr); + case INT64: + return Deserialize(*_cdr); + + case FLOAT32: + return Deserialize(*_cdr); + case FLOAT64: + return Deserialize(*_cdr); case DURATION: case TIME: { @@ -147,7 +173,7 @@ Variant FastCDR_Deserializer::deserialize(BuiltinType type) return {}; } -void FastCDR_Deserializer::deserializeString(std::string &dst) +void FastCDR_Deserializer::deserializeString(std::string& dst) { _cdr->deserialize(dst); } @@ -159,9 +185,9 @@ uint32_t FastCDR_Deserializer::deserializeUInt32() Span FastCDR_Deserializer::deserializeByteSequence() { -// thread_local std::vector tmp; -// _cdr->deserialize(tmp); -// return {tmp.data(), tmp.size()}; + // thread_local std::vector tmp; + // _cdr->deserialize(tmp); + // return {tmp.data(), tmp.size()}; uint32_t seqLength = 0; _cdr->deserialize(seqLength); @@ -173,12 +199,12 @@ Span FastCDR_Deserializer::deserializeByteSequence() _cdr->deserialize(dummy); _cdr->jump(seqLength - 1); - return {reinterpret_cast(ptr), seqLength}; + return { reinterpret_cast(ptr), seqLength }; } -const uint8_t *FastCDR_Deserializer::getCurrentPtr() const +const uint8_t* FastCDR_Deserializer::getCurrentPtr() const { - return reinterpret_cast(_cdr->getBufferPointer()); + return reinterpret_cast(_cdr->getBufferPointer()); } void FastCDR_Deserializer::jump(size_t bytes) @@ -197,4 +223,4 @@ void FastCDR_Deserializer::reset() _cdr->read_encapsulation(); } -} +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_field.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_field.cpp index d9419c1d9..d9e6600ea 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_field.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_field.cpp @@ -1,54 +1,52 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #include #include #include "rosx_introspection/ros_field.hpp" #include "rosx_introspection/ros_message.hpp" -namespace RosMsgParser{ - - -ROSField::ROSField(const ROSType &type, const std::string &name): - _fieldname(name), _type(type), _is_array(false), _array_size(1) +namespace RosMsgParser { +ROSField::ROSField(const ROSType& type, const std::string& name) + : _fieldname(name), _type(type), _is_array(false), _array_size(1) +{ } -ROSField::ROSField(const std::string &definition): - _is_array(false), _array_size(1) +ROSField::ROSField(const std::string& definition) : _is_array(false), _array_size(1) { - static const std::regex type_regex("[a-zA-Z][a-zA-Z0-9_]*" - "(/[a-zA-Z][a-zA-Z0-9_]*){0,1}" - "(\\[[0-9]*\\]){0,1}"); + static const std::regex type_regex("[a-zA-Z][a-zA-Z0-9_]*" + "(/[a-zA-Z][a-zA-Z0-9_]*){0,1}" + "(\\[[0-9]*\\]){0,1}"); - static const std::regex field_regex("[a-zA-Z][a-zA-Z0-9_]*"); + static const std::regex field_regex("[a-zA-Z][a-zA-Z0-9_]*"); static const std::regex array_regex("(.+)(\\[([0-9]*)\\])"); using std::regex; std::string::const_iterator begin = definition.begin(); - std::string::const_iterator end = definition.end(); + std::string::const_iterator end = definition.end(); std::match_results what; // Get type and field @@ -56,12 +54,13 @@ ROSField::ROSField(const std::string &definition): //------------------------------- // Find type, field and array size - if( std::regex_search(begin, end, what, type_regex)) + if (std::regex_search(begin, end, what, type_regex)) { type = what[0]; begin = what[0].second; } - else { + else + { throw std::runtime_error("Bad type when parsing field: " + definition); } @@ -70,7 +69,8 @@ ROSField::ROSField(const std::string &definition): _fieldname = what[0]; begin = what[0].second; } - else { + else + { throw std::runtime_error("Bad field when parsing field: " + definition); } @@ -79,16 +79,19 @@ ROSField::ROSField(const std::string &definition): { type = what[1]; - if (what.size() == 3) { + if (what.size() == 3) + { _array_size = -1; _is_array = true; } - else if (what.size() == 4) { + else if (what.size() == 4) + { std::string size(what[3].first, what[3].second); _array_size = size.empty() ? -1 : atoi(size.c_str()); _is_array = true; } - else { + else + { throw std::runtime_error("Bad array size when parsing field: " + definition); } } @@ -104,7 +107,8 @@ ROSField::ROSField(const std::string &definition): { begin = what[0].second; // Copy constant - if (type == "string") { + if (type == "string") + { value.assign(begin, end); } else @@ -113,7 +117,8 @@ ROSField::ROSField(const std::string &definition): { value.assign(begin, what[0].first); } - else { + else + { value.assign(begin, end); } } @@ -125,34 +130,36 @@ ROSField::ROSField(const std::string &definition): { // Ignore comment } - else // default value, not constant ? + else // default value, not constant ? { if (regex_search(begin, end, what, std::regex("\\s*#"))) { value.assign(begin, what[0].first); } - else { + else + { value.assign(begin, end); } } } - _type = ROSType( type ); + _type = ROSType(type); // TODO: Raise error if string is not numeric ? _value = value; } -std::shared_ptr ROSField::getMessagePtr(const RosMessageLibrary &library) const +std::shared_ptr +ROSField::getMessagePtr(const RosMessageLibrary& library) const { - if( _type.typeID() != BuiltinType::OTHER ) + if (_type.typeID() != BuiltinType::OTHER) { return {}; } - if( &library == _cache_library && _cache_message ) + if (&library == _cache_library && _cache_message) { return _cache_message; } auto it = library.find(_type.baseName()); - if( it == library.end() ) + if (it == library.end()) { return nullptr; } @@ -161,24 +168,24 @@ std::shared_ptr ROSField::getMessagePtr(const RosMessageLibrary &lib return _cache_message; } -void TrimStringLeft(std::string &s) +void TrimStringLeft(std::string& s) { - s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { - return !std::isspace(ch); - })); + s.erase(s.begin(), std::find_if(s.begin(), s.end(), + [](unsigned char ch) { return !std::isspace(ch); })); } -void TrimStringRight(std::string &s) +void TrimStringRight(std::string& s) { - s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { - return !std::isspace(ch); - }).base(), s.end()); + s.erase(std::find_if(s.rbegin(), s.rend(), + [](unsigned char ch) { return !std::isspace(ch); }) + .base(), + s.end()); } -void TrimString(std::string &s) +void TrimString(std::string& s) { TrimStringLeft(s); TrimStringRight(s); } -} +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_message.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_message.cpp index f8eb87a29..a4a45d538 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_message.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_message.cpp @@ -1,90 +1,91 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #include #include #include #include "rosx_introspection/ros_message.hpp" -namespace RosMsgParser{ +namespace RosMsgParser +{ -ROSMessage::ROSMessage(const std::string &msg_def) +ROSMessage::ROSMessage(const std::string& msg_def) { std::istringstream messageDescriptor(msg_def); std::match_results what; - for (std::string line; std::getline(messageDescriptor, line, '\n') ; ) + for (std::string line; std::getline(messageDescriptor, line, '\n');) { std::string::const_iterator begin = line.begin(), end = line.end(); // Skip empty line or one that is a comment - if (std::regex_search( begin, end, what, - std::regex("(^\\s*$|^\\s*#)"))) + if (std::regex_search(begin, end, what, std::regex("(^\\s*$|^\\s*#)"))) { continue; } TrimStringLeft(line); - if( line.compare(0, 5, "MSG: ") == 0) + if (line.compare(0, 5, "MSG: ") == 0) { - line.erase(0,5); + line.erase(0, 5); _type = ROSType(line); } - else{ + else + { auto new_field = ROSField(line); _fields.push_back(new_field); } } } -std::vector SplitMultipleMessageDefinitions(const std::string &multi_def) +std::vector SplitMultipleMessageDefinitions(const std::string& multi_def) { std::istringstream ss_msg(multi_def); std::vector parts; std::string part; - for (std::string line; std::getline(ss_msg, line, '\n') ; ) + for (std::string line; std::getline(ss_msg, line, '\n');) { - if( line.find("========") == 0) + if (line.find("========") == 0) { - parts.emplace_back( std::move(part) ); + parts.emplace_back(std::move(part)); part = {}; } - else{ + else + { part.append(line); part.append("\n"); } } - parts.emplace_back( std::move(part) ); + parts.emplace_back(std::move(part)); return parts; } -std::vector ParseMessageDefinitions( - const std::string& multi_def, - const ROSType& root_type ) +std::vector ParseMessageDefinitions(const std::string& multi_def, + const ROSType& root_type) { auto parts = SplitMultipleMessageDefinitions(multi_def); std::vector known_type; @@ -94,16 +95,16 @@ std::vector ParseMessageDefinitions( // iterating in reverse to fill known_type in the right order // i.e. with no missing dependencies - for( int i = parts.size()-1; i>=0; i--) + for (int i = parts.size() - 1; i >= 0; i--) { auto msg = std::make_shared(parts[i]); - if( i == 0 ) + if (i == 0) { // type NOT found in the definition, but provided as argument - if( msg->type() == no_type && root_type != no_type ) + if (msg->type() == no_type && root_type != no_type) { - msg->setType( root_type ); + msg->setType(root_type); } else if (msg->type() == no_type && root_type == no_type) { @@ -113,12 +114,12 @@ std::vector ParseMessageDefinitions( } // add to vector - parsed_msgs.push_back( msg ); - known_type.push_back( msg->type() ); + parsed_msgs.push_back(msg); + known_type.push_back(msg->type()); } // adjust types with undefined package type - for (auto& msg: parsed_msgs) + for (auto& msg : parsed_msgs) { for (ROSField& field : msg->fields()) { @@ -141,23 +142,22 @@ std::vector ParseMessageDefinitions( return parsed_msgs; } -MessageSchema::Ptr BuildMessageSchema(const std::string &topic_name, - const std::vector& parsed_msgs) +MessageSchema::Ptr BuildMessageSchema(const std::string& topic_name, + const std::vector& parsed_msgs) { auto schema = std::make_shared(); schema->topic_name = topic_name; schema->root_msg = parsed_msgs.front(); - for(const auto& msg: parsed_msgs ) + for (const auto& msg : parsed_msgs) { - schema->msg_library.insert( {msg->type(), msg} ); + schema->msg_library.insert({ msg->type(), msg }); } /// build field tree std::function recursiveTreeCreator; - recursiveTreeCreator = [&](ROSMessage::Ptr msg, FieldTreeNode* field_node) - { + recursiveTreeCreator = [&](ROSMessage::Ptr msg, FieldTreeNode* field_node) { // note: should use reserve here, NOT resize const size_t NUM_FIELDS = msg->fields().size(); field_node->children().reserve(NUM_FIELDS); @@ -176,26 +176,23 @@ MessageSchema::Ptr BuildMessageSchema(const std::string &topic_name, if (field.type().isBuiltin() == false) { auto new_msg = field.getMessagePtr(schema->msg_library); - if( !new_msg ) + if (!new_msg) { throw std::runtime_error("Missing ROSType in library"); } recursiveTreeCreator(new_msg, new_string_node); - } - } // end of for fields - }; // end of recursiveTreeCreator + } // end of for fields + }; // end of recursiveTreeCreator // build root and start recursion - auto root_field = new ROSField( schema->root_msg->type(), topic_name); - schema->field_tree.root()->setValue( root_field ); + auto root_field = new ROSField(schema->root_msg->type(), topic_name); + schema->field_tree.root()->setValue(root_field); recursiveTreeCreator(schema->root_msg, schema->field_tree.root()); return schema; } -} // end namespace - - +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_parser.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_parser.cpp index 57d9c6233..ab0f762f4 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_parser.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_parser.cpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #include @@ -33,15 +33,14 @@ inline bool operator==(const std::string& a, const std::string_view& b) return (a.size() == b.size() && std::strncmp(a.data(), b.data(), a.size()) == 0); } -Parser::Parser(const std::string &topic_name, - const ROSType &msg_type, - const std::string &definition) +Parser::Parser(const std::string& topic_name, const ROSType& msg_type, + const std::string& definition) : _global_warnings(&std::cerr) , _topic_name(topic_name) , _discard_large_array(DISCARD_LARGE_ARRAYS) , _max_array_size(100) , _blob_policy(STORE_BLOB_AS_COPY) - , _dummy_root_field( new ROSField(msg_type, topic_name) ) + , _dummy_root_field(new ROSField(msg_type, topic_name)) { auto parsed_msgs = ParseMessageDefinitions(definition, msg_type); _schema = BuildMessageSchema(topic_name, parsed_msgs); @@ -74,8 +73,7 @@ inline void ExpandVectorIfNecessary(Container& container, size_t new_size) } } -bool Parser::deserialize(Span buffer, - FlatMessage* flat_container, +bool Parser::deserialize(Span buffer, FlatMessage* flat_container, Deserializer* deserializer) const { deserializer->init(buffer); @@ -89,8 +87,7 @@ bool Parser::deserialize(Span buffer, std::function deserializeImpl; - deserializeImpl = [&](const ROSMessage* msg, FieldLeaf tree_leaf, bool store) - { + deserializeImpl = [&](const ROSMessage* msg, FieldLeaf tree_leaf, bool store) { size_t index_s = 0; size_t index_m = 0; @@ -137,13 +134,15 @@ bool Parser::deserialize(Span buffer, } } - if (IS_BLOB) // special case. This is a "blob", typically an image, a map, pointcloud, etc. + if (IS_BLOB) // special case. This is a "blob", typically an image, a map, + // pointcloud, etc. { ExpandVectorIfNecessary(flat_container->blob, blob_index); - if ( array_size > deserializer->bytesLeft() ) + if (array_size > deserializer->bytesLeft()) { - throw std::runtime_error("Buffer overrun in deserializeIntoFlatContainer (blob)"); + throw std::runtime_error("Buffer overrun in deserializeIntoFlatContainer " + "(blob)"); } if (DO_STORE) { @@ -167,7 +166,7 @@ bool Parser::deserialize(Span buffer, blob = Span(deserializer->getCurrentPtr(), array_size); } } - deserializer->jump( array_size ); + deserializer->jump(array_size); } else // NOT a BLOB { @@ -189,7 +188,7 @@ bool Parser::deserialize(Span buffer, ExpandVectorIfNecessary(flat_container->name, name_index); std::string str; - deserializer->deserializeString( str ); + deserializer->deserializeString(str); if (DO_STORE_ARRAY) { @@ -205,13 +204,14 @@ bool Parser::deserialize(Span buffer, Variant var = deserializer->deserialize(field_type.typeID()); if (DO_STORE_ARRAY) { - flat_container->value[value_index] = std::make_pair(new_tree_leaf, std::move(var)); + flat_container->value[value_index] = + std::make_pair(new_tree_leaf, std::move(var)); value_index++; } } else { // field_type.typeID() == OTHER - auto msg_node = field.getMessagePtr( _schema->msg_library ); + auto msg_node = field.getMessagePtr(_schema->msg_library); deserializeImpl(msg_node.get(), new_tree_leaf, DO_STORE_ARRAY); } } // end for array_size @@ -230,7 +230,8 @@ bool Parser::deserialize(Span buffer, FieldLeaf rootnode; rootnode.node = _schema->field_tree.croot(); - auto root_msg = _schema->field_tree.croot()->value()->getMessagePtr( _schema->msg_library ); + auto root_msg = + _schema->field_tree.croot()->value()->getMessagePtr(_schema->msg_library); deserializeImpl(root_msg.get(), rootnode, true); @@ -242,19 +243,16 @@ bool Parser::deserialize(Span buffer, return entire_message_parse; } - void CreateRenamedValues(const FlatMessage& flat_msg, RenamedValues& renamed) { -/* renamed.resize(flat_msg.value.size()); - for (size_t i = 0; i < flat_msg.value.size(); i++) - { - const auto& in = flat_msg.value[i]; - auto& out = renamed[i]; - in.first.toStr(out.first); - out.second = in.second.convert(); - }*/ + /* renamed.resize(flat_msg.value.size()); + for (size_t i = 0; i < flat_msg.value.size(); i++) + { + const auto& in = flat_msg.value[i]; + auto& out = renamed[i]; + in.first.toStr(out.first); + out.second = in.second.convert(); + }*/ } - - } // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_type.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_type.cpp index 916d774b7..84b8ef4f2 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_type.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/ros_type.cpp @@ -1,82 +1,85 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #include #include "rosx_introspection/ros_type.hpp" -namespace RosMsgParser{ +namespace RosMsgParser +{ -ROSType::ROSType(const std::string& name): - _base_name(name) +ROSType::ROSType(const std::string& name) : _base_name(name) { int pos = -1; - for (size_t i=0; i{}( _base_name ); + _id = toBuiltinType(_msg_name); + _hash = std::hash{}(_base_name); } -ROSType& ROSType::operator= (const ROSType &other) +ROSType& ROSType::operator=(const ROSType& other) { - int pos = other._pkg_name.size(); - _base_name = other._base_name; - _pkg_name = std::string_view( _base_name.data(), pos); - if( pos > 0) pos++; - _msg_name = std::string_view( _base_name.data() + pos, _base_name.size() - pos); - _id = other._id; - _hash = other._hash; - return *this; + int pos = other._pkg_name.size(); + _base_name = other._base_name; + _pkg_name = std::string_view(_base_name.data(), pos); + if (pos > 0) + pos++; + _msg_name = std::string_view(_base_name.data() + pos, _base_name.size() - pos); + _id = other._id; + _hash = other._hash; + return *this; } -ROSType& ROSType::operator= (ROSType &&other) +ROSType& ROSType::operator=(ROSType&& other) { - int pos = other._pkg_name.size(); - _base_name = std::move( other._base_name ); - _pkg_name = std::string_view( _base_name.data(), pos); - if( pos > 0) pos++; - _msg_name = std::string_view( _base_name.data() + pos, _base_name.size() - pos); - _id = other._id; - _hash = other._hash; - return *this; + int pos = other._pkg_name.size(); + _base_name = std::move(other._base_name); + _pkg_name = std::string_view(_base_name.data(), pos); + if (pos > 0) + pos++; + _msg_name = std::string_view(_base_name.data() + pos, _base_name.size() - pos); + _id = other._id; + _hash = other._hash; + return *this; } - void ROSType::setPkgName(std::string_view new_pkg) { assert(_pkg_name.size() == 0); @@ -84,11 +87,10 @@ void ROSType::setPkgName(std::string_view new_pkg) size_t pos = new_pkg.size(); _base_name = std::string(new_pkg) + "/" + _base_name; - _pkg_name = std::string_view( _base_name.data(), pos++); - _msg_name = std::string_view( _base_name.data() + pos, _base_name.size() - pos); + _pkg_name = std::string_view(_base_name.data(), pos++); + _msg_name = std::string_view(_base_name.data() + pos, _base_name.size() - pos); - _hash = std::hash{}( _base_name ); + _hash = std::hash{}(_base_name); } - -} +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/ParserROS/rosx_introspection/src/stringtree_leaf.cpp b/plotjuggler_plugins/ParserROS/rosx_introspection/src/stringtree_leaf.cpp index 76ae93f05..73e8f5e25 100644 --- a/plotjuggler_plugins/ParserROS/rosx_introspection/src/stringtree_leaf.cpp +++ b/plotjuggler_plugins/ParserROS/rosx_introspection/src/stringtree_leaf.cpp @@ -1,25 +1,25 @@ /***** MIT License **** -* -* Copyright (c) 2016-2022 Davide Faconti -* -* 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. -*/ + * + * Copyright (c) 2016-2022 Davide Faconti + * + * 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. + */ #include "rosx_introspection/stringtree_leaf.hpp" @@ -29,9 +29,9 @@ namespace RosMsgParser FieldsVector::FieldsVector(const FieldLeaf& leaf) { auto node = leaf.node; - while(node && node->value()) + while (node && node->value()) { - fields.push_back( node->value() ); + fields.push_back(node->value()); node = node->parent(); } std::reverse(fields.begin(), fields.end()); @@ -41,7 +41,7 @@ FieldsVector::FieldsVector(const FieldLeaf& leaf) void FieldsVector::toStr(std::string& out) const { size_t total_size = 0; - for( const ROSField* field: fields) + for (const ROSField* field : fields) { total_size += field->name().size() + 1; if (field->isArray()) @@ -50,29 +50,29 @@ void FieldsVector::toStr(std::string& out) const } } - out.resize( total_size ); + out.resize(total_size); char* buffer = static_cast(&out[0]); size_t array_count = 0; size_t offset = 0; - for( const ROSField* field: fields) + for (const ROSField* field : fields) { const std::string& str = field->name(); - bool is_root = ( field == fields.front() ); - if( !is_root ) + bool is_root = (field == fields.front()); + if (!is_root) { buffer[offset++] = '/'; } - std::memcpy( &buffer[offset], str.data(), str.size() ); + std::memcpy(&buffer[offset], str.data(), str.size()); offset += str.size(); - if(!is_root && field->isArray()) + if (!is_root && field->isArray()) { buffer[offset++] = '['; - if( array_count < index_array.size() ) + if (array_count < index_array.size()) { - offset += print_number(&buffer[offset], index_array[ array_count++ ] ); + offset += print_number(&buffer[offset], index_array[array_count++]); } buffer[offset++] = ']'; } @@ -81,14 +81,14 @@ void FieldsVector::toStr(std::string& out) const out.resize(offset); } - -//void CreateStringFromTreeLeaf(const FieldTreeLeaf &leaf, bool skip_root, std::string& out) +// void CreateStringFromTreeLeaf(const FieldTreeLeaf &leaf, bool skip_root, std::string& +// out) //{ -// const FieldTreeNode* leaf_node = leaf.node_ptr; -// if( !leaf_node ){ -// out.clear(); -// return ; -// } +// const FieldTreeNode* leaf_node = leaf.node_ptr; +// if( !leaf_node ){ +// out.clear(); +// return ; +// } // SmallVector strings_chain; @@ -139,4 +139,4 @@ void FieldsVector::toStr(std::string& out) const // out.resize(offset); //} -} +} // namespace RosMsgParser diff --git a/plotjuggler_plugins/PluginsZcm/config_zcm.cpp b/plotjuggler_plugins/PluginsZcm/config_zcm.cpp index 908e43a84..f93b9169b 100644 --- a/plotjuggler_plugins/PluginsZcm/config_zcm.cpp +++ b/plotjuggler_plugins/PluginsZcm/config_zcm.cpp @@ -6,88 +6,96 @@ #include #include - -ConfigZCM::ConfigZCM(QString prefix, QWidget *parent) - : QWidget(parent) - , ui(new Ui::ConfigZCM) - , _prefix(prefix) +ConfigZCM::ConfigZCM(QString prefix, QWidget* parent) + : QWidget(parent), ui(new Ui::ConfigZCM), _prefix(prefix) { - ui->setupUi(this); + ui->setupUi(this); - QSettings settings; - auto libs = settings.value(_prefix + "::manual_libs", {}).toStringList(); - for (auto const &lib : libs) { - ui->listWidgetLibs->addItem(lib); - } + QSettings settings; + auto libs = settings.value(_prefix + "::manual_libs", {}).toStringList(); + for (auto const& lib : libs) + { + ui->listWidgetLibs->addItem(lib); + } - bool is_manual = settings.value(_prefix + "::is_manual", false).toBool(); - ui->radioManualLibrary->setChecked(is_manual); + bool is_manual = settings.value(_prefix + "::is_manual", false).toBool(); + ui->radioManualLibrary->setChecked(is_manual); } ConfigZCM::~ConfigZCM() { - QSettings settings; + QSettings settings; - QStringList libs; - for (int row = 0; row < ui->listWidgetLibs->count(); row++) { - libs << ui->listWidgetLibs->item(row)->text(); - } - settings.setValue(_prefix + "::manual_libs", libs); - settings.setValue(_prefix + "::is_manual", ui->radioManualLibrary->isChecked()); - delete ui; + QStringList libs; + for (int row = 0; row < ui->listWidgetLibs->count(); row++) + { + libs << ui->listWidgetLibs->item(row)->text(); + } + settings.setValue(_prefix + "::manual_libs", libs); + settings.setValue(_prefix + "::is_manual", ui->radioManualLibrary->isChecked()); + delete ui; } QString ConfigZCM::getLibraries() const { - if (ui->radioEnvironmentLibrary->isChecked()) { - return getenv("PJ_ZCMTYPES_LIB_PATH"); - } else { - QStringList libs; - for (int row = 0; row < ui->listWidgetLibs->count(); row++) { - libs << ui->listWidgetLibs->item(row)->text(); - } - return libs.join(":"); + if (ui->radioEnvironmentLibrary->isChecked()) + { + return getenv("PJ_ZCMTYPES_LIB_PATH"); + } + else + { + QStringList libs; + for (int row = 0; row < ui->listWidgetLibs->count(); row++) + { + libs << ui->listWidgetLibs->item(row)->text(); } + return libs.join(":"); + } } void ConfigZCM::on_radioEnvironmentLibrary_toggled(bool checked) { - if (checked) { - ui->radioManualLibrary->setChecked(false); - } + if (checked) + { + ui->radioManualLibrary->setChecked(false); + } } void ConfigZCM::on_radioManualLibrary_toggled(bool checked) { - if (checked) { - ui->radioEnvironmentLibrary->setChecked(false); - } - ui->manualWidget->setEnabled(checked); + if (checked) + { + ui->radioEnvironmentLibrary->setChecked(false); + } + ui->manualWidget->setEnabled(checked); } void ConfigZCM::on_pushButtonAdd_clicked() { - QSettings settings; - auto dir = settings.value(_prefix + "::load_dir", QDir::currentPath()).toString(); - auto files = QFileDialog::getOpenFileNames(this, "Zcm libraries", dir, "*.so *.dll"); - for (auto filename : files) { - if (ui->listWidgetLibs->findItems(filename, Qt::MatchExactly).empty()) { - ui->listWidgetLibs->addItem(filename); - } - } - ui->listWidgetLibs->sortItems(); - if(!files.empty()){ - settings.setValue(_prefix + "::load_dir", - QFileInfo(files.front()).dir().absolutePath()); + QSettings settings; + auto dir = settings.value(_prefix + "::load_dir", QDir::currentPath()).toString(); + auto files = QFileDialog::getOpenFileNames(this, "Zcm libraries", dir, "*.so *.dll"); + for (auto filename : files) + { + if (ui->listWidgetLibs->findItems(filename, Qt::MatchExactly).empty()) + { + ui->listWidgetLibs->addItem(filename); } + } + ui->listWidgetLibs->sortItems(); + if (!files.empty()) + { + settings.setValue(_prefix + "::load_dir", + QFileInfo(files.front()).dir().absolutePath()); + } } void ConfigZCM::on_pushButtonRemove_clicked() { - auto items = ui->listWidgetLibs->selectedItems(); - for(auto item: items) { - ui->listWidgetLibs->removeItemWidget(item); - delete item; - } + auto items = ui->listWidgetLibs->selectedItems(); + for (auto item : items) + { + ui->listWidgetLibs->removeItemWidget(item); + delete item; + } } - diff --git a/plotjuggler_plugins/PluginsZcm/config_zcm.h b/plotjuggler_plugins/PluginsZcm/config_zcm.h index f6f6d5344..442795730 100644 --- a/plotjuggler_plugins/PluginsZcm/config_zcm.h +++ b/plotjuggler_plugins/PluginsZcm/config_zcm.h @@ -2,31 +2,31 @@ #include -namespace Ui { +namespace Ui +{ class ConfigZCM; } class ConfigZCM : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit ConfigZCM(QString prefix, QWidget *parent = nullptr); - ~ConfigZCM(); + explicit ConfigZCM(QString prefix, QWidget* parent = nullptr); + ~ConfigZCM(); - QString getLibraries() const; + QString getLibraries() const; private slots: - void on_radioEnvironmentLibrary_toggled(bool checked); + void on_radioEnvironmentLibrary_toggled(bool checked); - void on_radioManualLibrary_toggled(bool checked); + void on_radioManualLibrary_toggled(bool checked); - void on_pushButtonAdd_clicked(); + void on_pushButtonAdd_clicked(); - void on_pushButtonRemove_clicked(); + void on_pushButtonRemove_clicked(); private: - Ui::ConfigZCM *ui; - QString _prefix; + Ui::ConfigZCM* ui; + QString _prefix; }; - diff --git a/plotjuggler_plugins/PluginsZcm/dataload_zcm.cpp b/plotjuggler_plugins/PluginsZcm/dataload_zcm.cpp index ab0a17417..8abaa9d63 100644 --- a/plotjuggler_plugins/PluginsZcm/dataload_zcm.cpp +++ b/plotjuggler_plugins/PluginsZcm/dataload_zcm.cpp @@ -35,7 +35,7 @@ DataLoadZcm::DataLoadZcm() _ui->listWidgetChannels->setSelectionMode(QAbstractItemView::ExtendedSelection); connect(_ui->listWidgetChannels, &QListWidget::itemSelectionChanged, this, [this]() { - auto selected = _ui->listWidgetChannels->selectionModel()->selectedIndexes(); + auto selected = _ui->listWidgetChannels->selectionModel()->selectedIndexes(); bool box_enabled = selected.size() > 0; _ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(box_enabled); }); @@ -60,67 +60,77 @@ const vector& DataLoadZcm::compatibleFileExtensions() const static int processInputLog(const string& logpath, function processEvent) { - zcm::LogFile inlog(logpath, "r"); - if (!inlog.good()) { - cerr << "Unable to open input zcm log: " << logpath << endl; - return 1; - } + zcm::LogFile inlog(logpath, "r"); + if (!inlog.good()) + { + cerr << "Unable to open input zcm log: " << logpath << endl; + return 1; + } - auto processLog = [&inlog](function processEvent) { - const zcm::LogEvent* evt; - off64_t offset; - static int lastPrintPercent = 0; - - fseeko(inlog.getFilePtr(), 0, SEEK_END); - off64_t logSize = ftello(inlog.getFilePtr()); - fseeko(inlog.getFilePtr(), 0, SEEK_SET); - - QProgressDialog progress_dialog; - progress_dialog.setLabelText("Loading... please wait"); - progress_dialog.setWindowModality(Qt::ApplicationModal); - progress_dialog.setRange(0, 100); - progress_dialog.setAutoClose(true); - progress_dialog.setAutoReset(true); - progress_dialog.show(); - - bool interrupted = false; - - while (1) { - offset = ftello(inlog.getFilePtr()); - - int percent = 100.0 * offset / (logSize == 0 ? 1 : logSize); - if (percent != lastPrintPercent) { - if (verbose) { - cout << "\r" << "Percent Complete: " << percent << flush; - } - lastPrintPercent = percent; - - progress_dialog.setValue(percent); - if (progress_dialog.wasCanceled()) { - interrupted = true; - break; - } - } - - evt = inlog.readNextEvent(); - if (evt == nullptr) break; - - processEvent(evt); + auto processLog = [&inlog](function processEvent) { + const zcm::LogEvent* evt; + off64_t offset; + static int lastPrintPercent = 0; + + fseeko(inlog.getFilePtr(), 0, SEEK_END); + off64_t logSize = ftello(inlog.getFilePtr()); + fseeko(inlog.getFilePtr(), 0, SEEK_SET); + + QProgressDialog progress_dialog; + progress_dialog.setLabelText("Loading... please wait"); + progress_dialog.setWindowModality(Qt::ApplicationModal); + progress_dialog.setRange(0, 100); + progress_dialog.setAutoClose(true); + progress_dialog.setAutoReset(true); + progress_dialog.show(); + + bool interrupted = false; + + while (1) + { + offset = ftello(inlog.getFilePtr()); + + int percent = 100.0 * offset / (logSize == 0 ? 1 : logSize); + if (percent != lastPrintPercent) + { + if (verbose) + { + cout << "\r" + << "Percent Complete: " << percent << flush; } - if (verbose) { - if (lastPrintPercent != 100 && !interrupted) - cout << "\r" << "Percent Complete: 100" << flush; - cout << endl; + lastPrintPercent = percent; + + progress_dialog.setValue(percent); + if (progress_dialog.wasCanceled()) + { + interrupted = true; + break; } + } + + evt = inlog.readNextEvent(); + if (evt == nullptr) + break; + + processEvent(evt); + } + if (verbose) + { + if (lastPrintPercent != 100 && !interrupted) + cout << "\r" + << "Percent Complete: 100" << flush; + cout << endl; + } - if (interrupted) progress_dialog.cancel(); - }; + if (interrupted) + progress_dialog.cancel(); + }; - processLog(processEvent); + processLog(processEvent); - inlog.close(); + inlog.close(); - return 0; + return 0; } bool DataLoadZcm::refreshChannels(const string& filepath) @@ -128,7 +138,7 @@ bool DataLoadZcm::refreshChannels(const string& filepath) _all_channels.clear(); _all_channels_filepath = filepath; - auto processEvent = [&](const zcm::LogEvent* evt){ + auto processEvent = [&](const zcm::LogEvent* evt) { _all_channels.insert(evt->channel); }; @@ -141,16 +151,19 @@ bool DataLoadZcm::launchDialog(const string& filepath) _dialog->restoreGeometry(settings.value("DataLoadZcm.geometry").toByteArray()); _ui->listWidgetChannels->clear(); - for (auto& c : _all_channels) { + for (auto& c : _all_channels) + { auto chan = QString::fromStdString(c); _ui->listWidgetChannels->addItem(chan); } _ui->listWidgetChannels->sortItems(); auto selected_channels = settings.value("DataLoadZcm.selected_channels").toStringList(); - for (int row = 0; row<_ui->listWidgetChannels->count(); row++) { + for (int row = 0; row < _ui->listWidgetChannels->count(); row++) + { auto item = _ui->listWidgetChannels->item(row); - if (selected_channels.contains(item->text())) { + if (selected_channels.contains(item->text())) + { item->setSelected(true); } } @@ -159,14 +172,16 @@ bool DataLoadZcm::launchDialog(const string& filepath) int res = _dialog->exec(); settings.setValue("DataLoadZcm.geometry", _dialog->saveGeometry()); - if (res == QDialog::Rejected) { + if (res == QDialog::Rejected) + { return false; } _selected_channels.clear(); QModelIndexList indexes = _ui->listWidgetChannels->selectionModel()->selectedRows(); - for (auto& i : indexes) { + for (auto& i : indexes) + { auto item = _ui->listWidgetChannels->item(i.row()); _selected_channels.insert(item->text().toStdString()); selected_channels.push_back(item->text()); @@ -178,7 +193,8 @@ bool DataLoadZcm::launchDialog(const string& filepath) } template -double toDouble(const void* data) { +double toDouble(const void* data) +{ return static_cast(*reinterpret_cast(data)); } @@ -187,21 +203,41 @@ struct ProcessUsr vector>& numerics; vector>& strings; }; -static void processData(const string& name, zcm_field_type_t type, - const void* data, void* usr) +static void processData(const string& name, zcm_field_type_t type, const void* data, + void* usr) { ProcessUsr* v = (ProcessUsr*)usr; - switch (type) { - case ZCM_FIELD_INT8_T: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT16_T: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT32_T: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT64_T: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_BYTE: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_FLOAT: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_DOUBLE: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_BOOLEAN: v->numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_STRING: v->strings.emplace_back(name, string((const char*)data)); break; - case ZCM_FIELD_USER_TYPE: assert(false && "Should not be possble"); + switch (type) + { + case ZCM_FIELD_INT8_T: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT16_T: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT32_T: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT64_T: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_BYTE: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_FLOAT: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_DOUBLE: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_BOOLEAN: + v->numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_STRING: + v->strings.emplace_back(name, string((const char*)data)); + break; + case ZCM_FIELD_USER_TYPE: + assert(false && "Should not be possble"); } }; @@ -209,18 +245,21 @@ bool DataLoadZcm::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data { string filepath = info->filename.toStdString(); - if (info->plugin_config.hasChildNodes()) { + if (info->plugin_config.hasChildNodes()) + { xmlLoadState(info->plugin_config.firstChildElement()); } - if (filepath != _all_channels_filepath) { + if (filepath != _all_channels_filepath) + { refreshChannels(filepath); } - if (!launchDialog(filepath)) { + if (!launchDialog(filepath)) + { return false; } zcm::TypeDb types(_config_widget->getLibraries().toStdString()); - if(!types.good()) + if (!types.good()) { QMessageBox::warning(nullptr, "Error", "Failed to load zcmtypes"); return false; @@ -230,23 +269,26 @@ bool DataLoadZcm::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data vector> strings; ProcessUsr usr = { numerics, strings }; - auto processEvent = [&](const zcm::LogEvent* evt){ - if (_selected_channels.find(evt->channel) == _selected_channels.end()){ + auto processEvent = [&](const zcm::LogEvent* evt) { + if (_selected_channels.find(evt->channel) == _selected_channels.end()) + { return; } - zcm::Introspection::processEncodedType(evt->channel, - evt->data, evt->datalen, - "/", + zcm::Introspection::processEncodedType(evt->channel, evt->data, evt->datalen, "/", types, processData, &usr); - for (auto& n : usr.numerics) { + for (auto& n : usr.numerics) + { auto itr = plot_data.numeric.find(n.first); - if (itr == plot_data.numeric.end()) itr = plot_data.addNumeric(n.first); + if (itr == plot_data.numeric.end()) + itr = plot_data.addNumeric(n.first); itr->second.pushBack({ (double)evt->timestamp / 1e6, n.second }); } - for (auto& s : usr.strings) { + for (auto& s : usr.strings) + { auto itr = plot_data.strings.find(s.first); - if (itr == plot_data.strings.end()) itr = plot_data.addStringSeries(s.first); + if (itr == plot_data.strings.end()) + itr = plot_data.addStringSeries(s.first); itr->second.pushBack({ (double)evt->timestamp / 1e6, s.second }); } @@ -260,12 +302,13 @@ bool DataLoadZcm::readDataFromFile(FileLoadInfo* info, PlotDataMapRef& plot_data return true; } -static QDomElement serialize(const unordered_set& input, - QDomDocument& doc, const string& name) +static QDomElement serialize(const unordered_set& input, QDomDocument& doc, + const string& name) { QDomElement ret = doc.createElement(QString::fromStdString(name)); - for (const auto& item : input) { + for (const auto& item : input) + { QDomElement stringElement = doc.createElement("String"); QDomText textNode = doc.createTextNode(QString::fromStdString(item)); stringElement.appendChild(textNode); @@ -277,24 +320,26 @@ static QDomElement serialize(const unordered_set& input, static unordered_set deserialize(const QDomElement& elt) { - unordered_set ret; - - QDomNodeList childNodes = elt.childNodes(); - for (int i = 0; i < childNodes.size(); ++i) { - QDomNode node = childNodes.item(i); - if (node.isElement()) { - QDomElement element = node.toElement(); - if (element.tagName() == "String") { - QString stringValue = element.text(); - ret.insert(stringValue.toStdString()); - } - } + unordered_set ret; + + QDomNodeList childNodes = elt.childNodes(); + for (int i = 0; i < childNodes.size(); ++i) + { + QDomNode node = childNodes.item(i); + if (node.isElement()) + { + QDomElement element = node.toElement(); + if (element.tagName() == "String") + { + QString stringValue = element.text(); + ret.insert(stringValue.toStdString()); + } } + } - return ret; + return ret; } - bool DataLoadZcm::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { parent_element.appendChild(serialize(_selected_channels, doc, "selected_channels")); @@ -307,15 +352,18 @@ bool DataLoadZcm::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) c bool DataLoadZcm::xmlLoadState(const QDomElement& parent_element) { QDomElement all_channels = parent_element.firstChildElement("all_channels"); - if (!all_channels.isNull()) { + if (!all_channels.isNull()) + { _all_channels = deserialize(all_channels); - if (all_channels.hasAttribute("filepath")) { + if (all_channels.hasAttribute("filepath")) + { _all_channels_filepath = all_channels.attribute("filepath").toStdString(); } } QDomElement selected_channels = parent_element.firstChildElement("selected_channels"); - if (!selected_channels.isNull()) { + if (!selected_channels.isNull()) + { _selected_channels = deserialize(selected_channels); QStringList selected_channels; diff --git a/plotjuggler_plugins/PluginsZcm/datastream_zcm.cpp b/plotjuggler_plugins/PluginsZcm/datastream_zcm.cpp index 40b525fdf..131e0c696 100644 --- a/plotjuggler_plugins/PluginsZcm/datastream_zcm.cpp +++ b/plotjuggler_plugins/PluginsZcm/datastream_zcm.cpp @@ -17,11 +17,12 @@ using namespace std; using namespace PJ; template -double toDouble(const void* data) { +double toDouble(const void* data) +{ return static_cast(*reinterpret_cast(data)); } -DataStreamZcm::DataStreamZcm(): _subs(nullptr), _running(false) +DataStreamZcm::DataStreamZcm() : _subs(nullptr), _running(false) { _dialog = new QDialog; _ui = new Ui::DialogZcm; @@ -44,7 +45,8 @@ const char* DataStreamZcm::name() const bool DataStreamZcm::start(QStringList*) { - if (_running) { + if (_running) + { return false; } @@ -67,7 +69,8 @@ bool DataStreamZcm::start(QStringList*) int res = _dialog->exec(); settings.setValue("DataStreamZcm::geometry", _dialog->saveGeometry()); - if (res == QDialog::Rejected) { + if (res == QDialog::Rejected) + { return false; } @@ -77,44 +80,52 @@ bool DataStreamZcm::start(QStringList*) _transport = _ui->lineEditTransport->text(); - if(!_zcm) { - try { - _zcm.reset(new zcm::ZCM(_transport.toStdString())); + if (!_zcm) + { + try + { + _zcm.reset(new zcm::ZCM(_transport.toStdString())); } - catch(std::exception& ex) { - QMessageBox::warning(nullptr, "Error", - tr("Exception from zcm::ZCM() :\n%1").arg(ex.what())); - return false; + catch (std::exception& ex) + { + QMessageBox::warning(nullptr, "Error", + tr("Exception from zcm::ZCM() :\n%1").arg(ex.what())); + return false; } - if (!_zcm->good()) { - QMessageBox::warning(nullptr, "Error", "Failed to create zcm::ZCM()"); - _zcm.reset(); - return false; + if (!_zcm->good()) + { + QMessageBox::warning(nullptr, "Error", "Failed to create zcm::ZCM()"); + _zcm.reset(); + return false; } } auto libraries = _config_widget->getLibraries(); // reset the types if it is the first time or folder changed - if(_types_library != libraries || !_types) + if (_types_library != libraries || !_types) { _types_library = libraries; _types.reset(new zcm::TypeDb(_types_library.toStdString())); - if(!_types->good()) { + if (!_types->good()) + { QMessageBox::warning(nullptr, "Error", "Failed to create zcm::TypeDb()"); _types.reset(); return false; } } - if(_subscribe_string != _ui->lineEditSubscribe->text() || !_subs) + if (_subscribe_string != _ui->lineEditSubscribe->text() || !_subs) { _subscribe_string = _ui->lineEditSubscribe->text(); - if (_subs) { + if (_subs) + { _zcm->unsubscribe(_subs); } - _subs =_zcm->subscribe(_subscribe_string.toStdString(), &DataStreamZcm::handler, this); - if (!_subs) { + _subs = + _zcm->subscribe(_subscribe_string.toStdString(), &DataStreamZcm::handler, this); + if (!_subs) + { QMessageBox::warning(nullptr, "Error", "Failed to subscribe"); return false; } @@ -127,10 +138,12 @@ bool DataStreamZcm::start(QStringList*) void DataStreamZcm::shutdown() { - if (!_running) { + if (!_running) + { return; } - if (_subs) { + if (_subs) + { _zcm->unsubscribe(_subs); _subs = nullptr; } @@ -172,48 +185,68 @@ bool DataStreamZcm::xmlLoadState(const QDomElement& parent_element) return true; } - void DataStreamZcm::processData(const string& name, zcm_field_type_t type, const void* data, void* usr) { - DataStreamZcm *me = (DataStreamZcm*)usr; - switch (type) { - case ZCM_FIELD_INT8_T: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT16_T: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT32_T: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_INT64_T: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_BYTE: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_FLOAT: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_DOUBLE: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_BOOLEAN: me->_numerics.emplace_back(name, toDouble(data)); break; - case ZCM_FIELD_STRING: me->_strings.emplace_back(name, string((const char*)data)); break; - case ZCM_FIELD_USER_TYPE: assert(false && "Should not be possble"); + DataStreamZcm* me = (DataStreamZcm*)usr; + switch (type) + { + case ZCM_FIELD_INT8_T: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT16_T: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT32_T: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_INT64_T: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_BYTE: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_FLOAT: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_DOUBLE: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_BOOLEAN: + me->_numerics.emplace_back(name, toDouble(data)); + break; + case ZCM_FIELD_STRING: + me->_strings.emplace_back(name, string((const char*)data)); + break; + case ZCM_FIELD_USER_TYPE: + assert(false && "Should not be possble"); } }; - void DataStreamZcm::handler(const zcm::ReceiveBuffer* rbuf, const string& channel) { - zcm::Introspection::processEncodedType(channel, - rbuf->data, rbuf->data_size, - "/", + zcm::Introspection::processEncodedType(channel, rbuf->data, rbuf->data_size, "/", *_types.get(), processData, this); { std::lock_guard lock(mutex()); - for (auto& n : _numerics) { - auto itr = dataMap().numeric.find(n.first); - if (itr == dataMap().numeric.end()) { - itr = dataMap().addNumeric(n.first); - } - itr->second.pushBack({ double(rbuf->recv_utime) / 1e6, n.second }); + for (auto& n : _numerics) + { + auto itr = dataMap().numeric.find(n.first); + if (itr == dataMap().numeric.end()) + { + itr = dataMap().addNumeric(n.first); + } + itr->second.pushBack({ double(rbuf->recv_utime) / 1e6, n.second }); } - for (auto& s : _strings) { - auto itr = dataMap().strings.find(s.first); - if (itr == dataMap().strings.end()) { - itr = dataMap().addStringSeries(s.first); - } - itr->second.pushBack({ double(rbuf->recv_utime) / 1e6, s.second }); + for (auto& s : _strings) + { + auto itr = dataMap().strings.find(s.first); + if (itr == dataMap().strings.end()) + { + itr = dataMap().addStringSeries(s.first); + } + itr->second.pushBack({ double(rbuf->recv_utime) / 1e6, s.second }); } } @@ -226,10 +259,13 @@ void DataStreamZcm::handler(const zcm::ReceiveBuffer* rbuf, const string& channe void DataStreamZcm::on_pushButtonUrl_clicked() { QString url = getenv("ZCM_DEFAULT_URL"); - if (url.isEmpty()) { - QMessageBox::warning(nullptr, "Error", "Environment variable ZCM_DEFAULT_URL not set"); - } else { + if (url.isEmpty()) + { + QMessageBox::warning(nullptr, "Error", + "Environment variable ZCM_DEFAULT_URL not set"); + } + else + { _ui->lineEditTransport->setText(url); } } - diff --git a/plotjuggler_plugins/PluginsZcm/datastream_zcm.h b/plotjuggler_plugins/PluginsZcm/datastream_zcm.h index a82333044..86233e729 100644 --- a/plotjuggler_plugins/PluginsZcm/datastream_zcm.h +++ b/plotjuggler_plugins/PluginsZcm/datastream_zcm.h @@ -36,7 +36,7 @@ class DataStreamZcm : public PJ::DataStreamer virtual bool xmlLoadState(const QDomElement& parent_element) override; - private slots: +private slots: void on_pushButtonUrl_clicked(); private: @@ -46,8 +46,7 @@ class DataStreamZcm : public PJ::DataStreamer zcm::Subscription* _subs = nullptr; - static void processData(const std::string& name, - zcm_field_type_t type, + static void processData(const std::string& name, zcm_field_type_t type, const void* data, void* usr); std::vector> _numerics; diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/_kiss_fft_guts.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/_kiss_fft_guts.h index 4bd8d1c10..39f8f2202 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/_kiss_fft_guts.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/_kiss_fft_guts.h @@ -24,11 +24,12 @@ 4*4*4*2 */ -struct kiss_fft_state{ - int nfft; - int inverse; - int factors[2*MAXFACTORS]; - kiss_fft_cpx twiddles[1]; +struct kiss_fft_state +{ + int nfft; + int inverse; + int factors[2 * MAXFACTORS]; + kiss_fft_cpx twiddles[1]; }; /* @@ -42,126 +43,148 @@ struct kiss_fft_state{ * */ #ifdef FIXED_POINT #include -#if (FIXED_POINT==32) -# define FRACBITS 31 -# define SAMPPROD int64_t +#if (FIXED_POINT == 32) +#define FRACBITS 31 +#define SAMPPROD int64_t #define SAMP_MAX INT32_MAX #define SAMP_MIN INT32_MIN #else -# define FRACBITS 15 -# define SAMPPROD int32_t +#define FRACBITS 15 +#define SAMPPROD int32_t #define SAMP_MAX INT16_MAX #define SAMP_MIN INT16_MIN #endif #if defined(CHECK_OVERFLOW) -# define CHECK_OVERFLOW_OP(a,op,b) \ - if ( (SAMPPROD)(a) op (SAMPPROD)(b) > SAMP_MAX || (SAMPPROD)(a) op (SAMPPROD)(b) < SAMP_MIN ) { \ - KISS_FFT_WARNING("overflow (%d " #op" %d) = %ld", (a),(b),(SAMPPROD)(a) op (SAMPPROD)(b)); } +#define CHECK_OVERFLOW_OP(a, op, b) \ + if ((SAMPPROD)(a)op(SAMPPROD)(b) > SAMP_MAX || \ + (SAMPPROD)(a)op(SAMPPROD)(b) < SAMP_MIN) \ + { \ + KISS_FFT_WARNING("overflow (%d " #op " %d) = %ld", (a), (b), \ + (SAMPPROD)(a)op(SAMPPROD)(b)); \ + } #endif - -# define smul(a,b) ( (SAMPPROD)(a)*(b) ) -# define sround( x ) (kiss_fft_scalar)( ( (x) + (1<<(FRACBITS-1)) ) >> FRACBITS ) - -# define S_MUL(a,b) sround( smul(a,b) ) - -# define C_MUL(m,a,b) \ - do{ (m).r = sround( smul((a).r,(b).r) - smul((a).i,(b).i) ); \ - (m).i = sround( smul((a).r,(b).i) + smul((a).i,(b).r) ); }while(0) - -# define DIVSCALAR(x,k) \ - (x) = sround( smul( x, SAMP_MAX/k ) ) - -# define C_FIXDIV(c,div) \ - do { DIVSCALAR( (c).r , div); \ - DIVSCALAR( (c).i , div); }while (0) - -# define C_MULBYSCALAR( c, s ) \ - do{ (c).r = sround( smul( (c).r , s ) ) ;\ - (c).i = sround( smul( (c).i , s ) ) ; }while(0) - -#else /* not FIXED_POINT*/ - -# define S_MUL(a,b) ( (a)*(b) ) -#define C_MUL(m,a,b) \ - do{ (m).r = (a).r*(b).r - (a).i*(b).i;\ - (m).i = (a).r*(b).i + (a).i*(b).r; }while(0) -# define C_FIXDIV(c,div) /* NOOP */ -# define C_MULBYSCALAR( c, s ) \ - do{ (c).r *= (s);\ - (c).i *= (s); }while(0) +#define smul(a, b) ((SAMPPROD)(a) * (b)) +#define sround(x) (kiss_fft_scalar)(((x) + (1 << (FRACBITS - 1))) >> FRACBITS) + +#define S_MUL(a, b) sround(smul(a, b)) + +#define C_MUL(m, a, b) \ + do \ + { \ + (m).r = sround(smul((a).r, (b).r) - smul((a).i, (b).i)); \ + (m).i = sround(smul((a).r, (b).i) + smul((a).i, (b).r)); \ + } while (0) + +#define DIVSCALAR(x, k) (x) = sround(smul(x, SAMP_MAX / k)) + +#define C_FIXDIV(c, div) \ + do \ + { \ + DIVSCALAR((c).r, div); \ + DIVSCALAR((c).i, div); \ + } while (0) + +#define C_MULBYSCALAR(c, s) \ + do \ + { \ + (c).r = sround(smul((c).r, s)); \ + (c).i = sround(smul((c).i, s)); \ + } while (0) + +#else /* not FIXED_POINT*/ + +#define S_MUL(a, b) ((a) * (b)) +#define C_MUL(m, a, b) \ + do \ + { \ + (m).r = (a).r * (b).r - (a).i * (b).i; \ + (m).i = (a).r * (b).i + (a).i * (b).r; \ + } while (0) +#define C_FIXDIV(c, div) /* NOOP */ +#define C_MULBYSCALAR(c, s) \ + do \ + { \ + (c).r *= (s); \ + (c).i *= (s); \ + } while (0) #endif #ifndef CHECK_OVERFLOW_OP -# define CHECK_OVERFLOW_OP(a,op,b) /* noop */ +#define CHECK_OVERFLOW_OP(a, op, b) /* noop */ #endif -#define C_ADD( res, a,b)\ - do { \ - CHECK_OVERFLOW_OP((a).r,+,(b).r)\ - CHECK_OVERFLOW_OP((a).i,+,(b).i)\ - (res).r=(a).r+(b).r; (res).i=(a).i+(b).i; \ - }while(0) -#define C_SUB( res, a,b)\ - do { \ - CHECK_OVERFLOW_OP((a).r,-,(b).r)\ - CHECK_OVERFLOW_OP((a).i,-,(b).i)\ - (res).r=(a).r-(b).r; (res).i=(a).i-(b).i; \ - }while(0) -#define C_ADDTO( res , a)\ - do { \ - CHECK_OVERFLOW_OP((res).r,+,(a).r)\ - CHECK_OVERFLOW_OP((res).i,+,(a).i)\ - (res).r += (a).r; (res).i += (a).i;\ - }while(0) - -#define C_SUBFROM( res , a)\ - do {\ - CHECK_OVERFLOW_OP((res).r,-,(a).r)\ - CHECK_OVERFLOW_OP((res).i,-,(a).i)\ - (res).r -= (a).r; (res).i -= (a).i; \ - }while(0) - +#define C_ADD(res, a, b) \ + do \ + { \ + CHECK_OVERFLOW_OP((a).r, +, (b).r) \ + CHECK_OVERFLOW_OP((a).i, +, (b).i) \ + (res).r = (a).r + (b).r; \ + (res).i = (a).i + (b).i; \ + } while (0) +#define C_SUB(res, a, b) \ + do \ + { \ + CHECK_OVERFLOW_OP((a).r, -, (b).r) \ + CHECK_OVERFLOW_OP((a).i, -, (b).i) \ + (res).r = (a).r - (b).r; \ + (res).i = (a).i - (b).i; \ + } while (0) +#define C_ADDTO(res, a) \ + do \ + { \ + CHECK_OVERFLOW_OP((res).r, +, (a).r) \ + CHECK_OVERFLOW_OP((res).i, +, (a).i) \ + (res).r += (a).r; \ + (res).i += (a).i; \ + } while (0) + +#define C_SUBFROM(res, a) \ + do \ + { \ + CHECK_OVERFLOW_OP((res).r, -, (a).r) \ + CHECK_OVERFLOW_OP((res).i, -, (a).i) \ + (res).r -= (a).r; \ + (res).i -= (a).i; \ + } while (0) #ifdef FIXED_POINT -# define KISS_FFT_COS(phase) floor(.5+SAMP_MAX * cos (phase)) -# define KISS_FFT_SIN(phase) floor(.5+SAMP_MAX * sin (phase)) -# define HALF_OF(x) ((x)>>1) +#define KISS_FFT_COS(phase) floor(.5 + SAMP_MAX * cos(phase)) +#define KISS_FFT_SIN(phase) floor(.5 + SAMP_MAX * sin(phase)) +#define HALF_OF(x) ((x) >> 1) #elif defined(USE_SIMD) -# define KISS_FFT_COS(phase) _mm_set1_ps( cos(phase) ) -# define KISS_FFT_SIN(phase) _mm_set1_ps( sin(phase) ) -# define HALF_OF(x) ((x)*_mm_set1_ps(.5)) +#define KISS_FFT_COS(phase) _mm_set1_ps(cos(phase)) +#define KISS_FFT_SIN(phase) _mm_set1_ps(sin(phase)) +#define HALF_OF(x) ((x)*_mm_set1_ps(.5)) #else -# define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) -# define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) -# define HALF_OF(x) ((x)*((kiss_fft_scalar).5)) +#define KISS_FFT_COS(phase) (kiss_fft_scalar) cos(phase) +#define KISS_FFT_SIN(phase) (kiss_fft_scalar) sin(phase) +#define HALF_OF(x) ((x) * ((kiss_fft_scalar).5)) #endif -#define kf_cexp(x,phase) \ - do{ \ - (x)->r = KISS_FFT_COS(phase);\ - (x)->i = KISS_FFT_SIN(phase);\ - }while(0) - +#define kf_cexp(x, phase) \ + do \ + { \ + (x)->r = KISS_FFT_COS(phase); \ + (x)->i = KISS_FFT_SIN(phase); \ + } while (0) /* a debugging function */ -#define pcpx(c)\ - KISS_FFT_DEBUG("%g + %gi\n",(double)((c)->r),(double)((c)->i)) - +#define pcpx(c) KISS_FFT_DEBUG("%g + %gi\n", (double)((c)->r), (double)((c)->i)) #ifdef KISS_FFT_USE_ALLOCA // define this to allow use of alloca instead of malloc for temporary buffers // Temporary buffers are used in two case: // 1. FFT sizes that have "bad" factors. i.e. not 2,3 and 5 -// 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place transform. +// 2. "in-place" FFTs. Notice the quotes, since kissfft does not really do an in-place +// transform. #include -#define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) -#define KISS_FFT_TMP_FREE(ptr) +#define KISS_FFT_TMP_ALLOC(nbytes) alloca(nbytes) +#define KISS_FFT_TMP_FREE(ptr) #else -#define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) -#define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) +#define KISS_FFT_TMP_ALLOC(nbytes) KISS_FFT_MALLOC(nbytes) +#define KISS_FFT_TMP_FREE(ptr) KISS_FFT_FREE(ptr) #endif #endif /* _kiss_fft_guts_h */ - diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kfc.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kfc.h index d7d8c1b4a..1f00ab41e 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kfc.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kfc.h @@ -17,32 +17,32 @@ extern "C" { /* KFC -- Kiss FFT Cache -Not needing to deal with kiss_fft_alloc and a config +Not needing to deal with kiss_fft_alloc and a config object may be handy for a lot of programs. -KFC uses the underlying KISS FFT functions, but caches the config object. -The first time kfc_fft or kfc_ifft for a given FFT size, the cfg -object is created for it. All subsequent calls use the cached +KFC uses the underlying KISS FFT functions, but caches the config object. +The first time kfc_fft or kfc_ifft for a given FFT size, the cfg +object is created for it. All subsequent calls use the cached configuration object. NOTE: -You should probably not use this if your program will be using a lot +You should probably not use this if your program will be using a lot of various sizes of FFTs. There is a linear search through the cached objects. If you are only using one or two FFT sizes, this -will be negligible. Otherwise, you may want to use another method +will be negligible. Otherwise, you may want to use another method of managing the cfg objects. - - There is no automated cleanup of the cached objects. This could lead -to large memory usage in a program that uses a lot of *DIFFERENT* + + There is no automated cleanup of the cached objects. This could lead +to large memory usage in a program that uses a lot of *DIFFERENT* sized FFTs. If you want to force all cached cfg objects to be freed, call kfc_cleanup. - + */ /*forward complex FFT */ -void KISS_FFT_API kfc_fft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); +void KISS_FFT_API kfc_fft(int nfft, const kiss_fft_cpx* fin, kiss_fft_cpx* fout); /*reverse complex FFT */ -void KISS_FFT_API kfc_ifft(int nfft, const kiss_fft_cpx * fin,kiss_fft_cpx * fout); +void KISS_FFT_API kfc_ifft(int nfft, const kiss_fft_cpx* fin, kiss_fft_cpx* fout); /*free all cached objects*/ void KISS_FFT_API kfc_cleanup(void); diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft.h index dce1034a7..90e3bfbc8 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft.h @@ -16,17 +16,17 @@ // Define KISS_FFT_SHARED macro to properly export symbols #ifdef KISS_FFT_SHARED -# ifdef _WIN32 -# ifdef KISS_FFT_BUILD -# define KISS_FFT_API __declspec(dllexport) -# else -# define KISS_FFT_API __declspec(dllimport) -# endif -# else -# define KISS_FFT_API __attribute__ ((visibility ("default"))) -# endif +#ifdef _WIN32 +#ifdef KISS_FFT_BUILD +#define KISS_FFT_API __declspec(dllexport) #else -# define KISS_FFT_API +#define KISS_FFT_API __declspec(dllimport) +#endif +#else +#define KISS_FFT_API __attribute__((visibility("default"))) +#endif +#else +#define KISS_FFT_API #endif #ifdef __cplusplus @@ -48,52 +48,52 @@ extern "C" { /* User may override KISS_FFT_MALLOC and/or KISS_FFT_FREE. */ #ifdef USE_SIMD -# include -# define kiss_fft_scalar __m128 -# ifndef KISS_FFT_MALLOC -# define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes,16) -# define KISS_FFT_ALIGN_CHECK(ptr) -# define KISS_FFT_ALIGN_SIZE_UP(size) ((size + 15UL) & ~0xFUL) -# endif -# ifndef KISS_FFT_FREE -# define KISS_FFT_FREE _mm_free -# endif +#include +#define kiss_fft_scalar __m128 +#ifndef KISS_FFT_MALLOC +#define KISS_FFT_MALLOC(nbytes) _mm_malloc(nbytes, 16) +#define KISS_FFT_ALIGN_CHECK(ptr) +#define KISS_FFT_ALIGN_SIZE_UP(size) ((size + 15UL) & ~0xFUL) +#endif +#ifndef KISS_FFT_FREE +#define KISS_FFT_FREE _mm_free +#endif #else -# define KISS_FFT_ALIGN_CHECK(ptr) -# define KISS_FFT_ALIGN_SIZE_UP(size) (size) -# ifndef KISS_FFT_MALLOC -# define KISS_FFT_MALLOC malloc -# endif -# ifndef KISS_FFT_FREE -# define KISS_FFT_FREE free -# endif +#define KISS_FFT_ALIGN_CHECK(ptr) +#define KISS_FFT_ALIGN_SIZE_UP(size) (size) +#ifndef KISS_FFT_MALLOC +#define KISS_FFT_MALLOC malloc +#endif +#ifndef KISS_FFT_FREE +#define KISS_FFT_FREE free +#endif #endif - #ifdef FIXED_POINT #include -# if (FIXED_POINT == 32) -# define kiss_fft_scalar int32_t -# else -# define kiss_fft_scalar int16_t -# endif +#if (FIXED_POINT == 32) +#define kiss_fft_scalar int32_t +#else +#define kiss_fft_scalar int16_t +#endif #else -# ifndef kiss_fft_scalar +#ifndef kiss_fft_scalar /* default is float */ -# define kiss_fft_scalar float -# endif +#define kiss_fft_scalar float +#endif #endif -typedef struct { - kiss_fft_scalar r; - kiss_fft_scalar i; -}kiss_fft_cpx; +typedef struct +{ + kiss_fft_scalar r; + kiss_fft_scalar i; +} kiss_fft_cpx; typedef struct kiss_fft_state* kiss_fft_cfg; -/* +/* * kiss_fft_alloc - * + * * Initialize a FFT (or IFFT) algorithm's cfg/state buffer. * * typical usage: kiss_fft_cfg mycfg=kiss_fft_alloc(1024,0,NULL,NULL); @@ -103,18 +103,19 @@ typedef struct kiss_fft_state* kiss_fft_cfg; * * If lenmem is NULL, then kiss_fft_alloc will allocate a cfg buffer using malloc. * The returned value should be free()d when done to avoid memory leaks. - * + * * The state can be placed in a user supplied buffer 'mem': * If lenmem is not NULL and mem is not NULL and *lenmem is large enough, * then the function places the cfg in mem and the size used in *lenmem * and returns mem. - * + * * If lenmem is not NULL and ( mem is NULL or *lenmem is not large enough), - * then the function returns NULL and places the minimum cfg + * then the function returns NULL and places the minimum cfg * buffer size in *lenmem. * */ -kiss_fft_cfg KISS_FFT_API kiss_fft_alloc(int nfft,int inverse_fft,void * mem,size_t * lenmem); +kiss_fft_cfg KISS_FFT_API kiss_fft_alloc(int nfft, int inverse_fft, void* mem, + size_t* lenmem); /* * kiss_fft(cfg,in_out_buf) @@ -126,23 +127,23 @@ kiss_fft_cfg KISS_FFT_API kiss_fft_alloc(int nfft,int inverse_fft,void * mem,siz * Note that each element is complex and can be accessed like f[k].r and f[k].i * */ -void KISS_FFT_API kiss_fft(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); +void KISS_FFT_API kiss_fft(kiss_fft_cfg cfg, const kiss_fft_cpx* fin, kiss_fft_cpx* fout); /* A more generic version of the above function. It reads its input from every Nth sample. * */ -void KISS_FFT_API kiss_fft_stride(kiss_fft_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout,int fin_stride); +void KISS_FFT_API kiss_fft_stride(kiss_fft_cfg cfg, const kiss_fft_cpx* fin, + kiss_fft_cpx* fout, int fin_stride); -/* If kiss_fft_alloc allocated a buffer, it is one contiguous +/* If kiss_fft_alloc allocated a buffer, it is one contiguous buffer and can be simply free()d when no longer needed*/ #define kiss_fft_free KISS_FFT_FREE /* - Cleans up some memory that gets managed internally. Not necessary to call, but it might clean up - your compiler output to call this before you exit. + Cleans up some memory that gets managed internally. Not necessary to call, but it might + clean up your compiler output to call this before you exit. */ void KISS_FFT_API kiss_fft_cleanup(void); - /* * Returns the smallest integer k, such that k>=n and k has only "fast" factors (2,3,5) @@ -150,11 +151,10 @@ void KISS_FFT_API kiss_fft_cleanup(void); int KISS_FFT_API kiss_fft_next_fast_size(int n); /* for real ffts, we need an even size */ -#define kiss_fftr_next_fast_size_real(n) \ - (kiss_fft_next_fast_size( ((n)+1)>>1)<<1) +#define kiss_fftr_next_fast_size_real(n) (kiss_fft_next_fast_size(((n) + 1) >> 1) << 1) #ifdef __cplusplus -} +} #endif #endif diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft_log.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft_log.h index b5b631a08..447342b8a 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft_log.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fft_log.h @@ -18,12 +18,12 @@ #define TOSTRING(x) STRINGIFY(x) #if defined(NDEBUG) -# define KISS_FFT_LOG_MSG(severity, ...) ((void)0) +#define KISS_FFT_LOG_MSG(severity, ...) ((void)0) #else -# define KISS_FFT_LOG_MSG(severity, ...) \ - fprintf(stderr, "[" #severity "] " __FILE__ ":" TOSTRING(__LINE__) " "); \ - fprintf(stderr, __VA_ARGS__); \ - fprintf(stderr, "\n") +#define KISS_FFT_LOG_MSG(severity, ...) \ + fprintf(stderr, "[" #severity "] " __FILE__ ":" TOSTRING(__LINE__) " "); \ + fprintf(stderr, __VA_ARGS__); \ + fprintf(stderr, "\n") #endif #define KISS_FFT_ERROR(...) KISS_FFT_LOG_MSG(ERROR, __VA_ARGS__) @@ -31,6 +31,4 @@ #define KISS_FFT_INFO(...) KISS_FFT_LOG_MSG(INFO, __VA_ARGS__) #define KISS_FFT_DEBUG(...) KISS_FFT_LOG_MSG(DEBUG, __VA_ARGS__) - - #endif /* kiss_fft_log_h */ \ No newline at end of file diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftnd.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftnd.h index 956ba94da..d9fb73adb 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftnd.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftnd.h @@ -15,10 +15,12 @@ extern "C" { #endif -typedef struct kiss_fftnd_state * kiss_fftnd_cfg; - -kiss_fftnd_cfg KISS_FFT_API kiss_fftnd_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); -void KISS_FFT_API kiss_fftnd(kiss_fftnd_cfg cfg,const kiss_fft_cpx *fin,kiss_fft_cpx *fout); +typedef struct kiss_fftnd_state* kiss_fftnd_cfg; + +kiss_fftnd_cfg KISS_FFT_API kiss_fftnd_alloc(const int* dims, int ndims, int inverse_fft, + void* mem, size_t* lenmem); +void KISS_FFT_API kiss_fftnd(kiss_fftnd_cfg cfg, const kiss_fft_cpx* fin, + kiss_fft_cpx* fout); #ifdef __cplusplus } diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftndr.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftndr.h index 0d56a1fad..dbc91cb55 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftndr.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftndr.h @@ -16,36 +16,31 @@ #ifdef __cplusplus extern "C" { #endif - -typedef struct kiss_fftndr_state *kiss_fftndr_cfg; +typedef struct kiss_fftndr_state* kiss_fftndr_cfg; -kiss_fftndr_cfg KISS_FFT_API kiss_fftndr_alloc(const int *dims,int ndims,int inverse_fft,void*mem,size_t*lenmem); +kiss_fftndr_cfg KISS_FFT_API kiss_fftndr_alloc(const int* dims, int ndims, + int inverse_fft, void* mem, + size_t* lenmem); /* dims[0] must be even - If you don't care to allocate space, use mem = lenmem = NULL + If you don't care to allocate space, use mem = lenmem = NULL */ - -void KISS_FFT_API kiss_fftndr( - kiss_fftndr_cfg cfg, - const kiss_fft_scalar *timedata, - kiss_fft_cpx *freqdata); +void KISS_FFT_API kiss_fftndr(kiss_fftndr_cfg cfg, const kiss_fft_scalar* timedata, + kiss_fft_cpx* freqdata); /* input timedata has dims[0] X dims[1] X ... X dims[ndims-1] scalar points output freqdata has dims[0] X dims[1] X ... X dims[ndims-1]/2+1 complex points */ -void KISS_FFT_API kiss_fftndri( - kiss_fftndr_cfg cfg, - const kiss_fft_cpx *freqdata, - kiss_fft_scalar *timedata); +void KISS_FFT_API kiss_fftndri(kiss_fftndr_cfg cfg, const kiss_fft_cpx* freqdata, + kiss_fft_scalar* timedata); /* input and output dimensions are the exact opposite of kiss_fftndr */ - #define kiss_fftndr_free free #ifdef __cplusplus diff --git a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftr.h b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftr.h index 7fd73d2d0..52eb55e20 100644 --- a/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftr.h +++ b/plotjuggler_plugins/ToolboxFFT/KissFFT/kiss_fftr.h @@ -14,33 +14,33 @@ extern "C" { #endif - -/* - +/* + Real optimized version can save about 45% cpu time vs. complex fft of a real seq. - - - */ -typedef struct kiss_fftr_state *kiss_fftr_cfg; + */ + +typedef struct kiss_fftr_state* kiss_fftr_cfg; -kiss_fftr_cfg KISS_FFT_API kiss_fftr_alloc(int nfft,int inverse_fft,void * mem, size_t * lenmem); +kiss_fftr_cfg KISS_FFT_API kiss_fftr_alloc(int nfft, int inverse_fft, void* mem, + size_t* lenmem); /* nfft must be even - If you don't care to allocate space, use mem = lenmem = NULL + If you don't care to allocate space, use mem = lenmem = NULL */ - -void KISS_FFT_API kiss_fftr(kiss_fftr_cfg cfg,const kiss_fft_scalar *timedata,kiss_fft_cpx *freqdata); +void KISS_FFT_API kiss_fftr(kiss_fftr_cfg cfg, const kiss_fft_scalar* timedata, + kiss_fft_cpx* freqdata); /* input timedata has nfft scalar points output freqdata has nfft/2+1 complex points */ -void KISS_FFT_API kiss_fftri(kiss_fftr_cfg cfg,const kiss_fft_cpx *freqdata,kiss_fft_scalar *timedata); +void KISS_FFT_API kiss_fftri(kiss_fftr_cfg cfg, const kiss_fft_cpx* freqdata, + kiss_fft_scalar* timedata); /* input freqdata has nfft/2+1 complex points output timedata has nfft scalar points diff --git a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp index 892e0d218..ba3b33e31 100644 --- a/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp +++ b/plotjuggler_plugins/ToolboxFFT/toolbox_FFT.cpp @@ -87,7 +87,7 @@ void ToolboxFFT::calculateCurveFFT() } PlotData& curve_data = it->second; - if( curve_data.size() == 0) + if (curve_data.size() == 0) { return; } @@ -120,7 +120,7 @@ void ToolboxFFT::calculateCurveFFT() input.reserve(curve_data.size()); double sum = 0; - if(ui->checkAverage->isChecked()) + if (ui->checkAverage->isChecked()) { for (size_t i = 0; i < N; i++) { diff --git a/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.cpp b/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.cpp index 2bece11d8..b696327bd 100644 --- a/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.cpp +++ b/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.cpp @@ -34,60 +34,56 @@ ToolboxLuaEditor::ToolboxLuaEditor() connect(ui->pushButtonDelete, &QPushButton::clicked, this, &ToolboxLuaEditor::onDelete); - connect(ui->lineEditFunctionName, &QLineEdit::textChanged, this, [this]() - { - bool has_name = ui->lineEditFunctionName->text().isEmpty() == false; - ui->pushButtonSave->setEnabled( has_name ); - } ); + connect(ui->lineEditFunctionName, &QLineEdit::textChanged, this, [this]() { + bool has_name = ui->lineEditFunctionName->text().isEmpty() == false; + ui->pushButtonSave->setEnabled(has_name); + }); connect(ui->buttonBox, &QDialogButtonBox::rejected, this, &ToolboxPlugin::closed); - connect(ui->listWidgetRecent, &QListWidget::doubleClicked, this, &ToolboxLuaEditor::restoreRecent); + connect(ui->listWidgetRecent, &QListWidget::doubleClicked, this, + &ToolboxLuaEditor::restoreRecent); - connect(ui->listWidgetFunctions, &QListWidget::doubleClicked, this, &ToolboxLuaEditor::restoreFunction); + connect(ui->listWidgetFunctions, &QListWidget::doubleClicked, this, + &ToolboxLuaEditor::restoreFunction); - connect(ui->listWidgetFunctions, &QListWidget::itemSelectionChanged, this, - [this]() { - auto selected = ui->listWidgetFunctions->selectedItems(); - ui->pushButtonDelete->setEnabled(selected.size()>0); - }); + connect(ui->listWidgetFunctions, &QListWidget::itemSelectionChanged, this, [this]() { + auto selected = ui->listWidgetFunctions->selectedItems(); + ui->pushButtonDelete->setEnabled(selected.size() > 0); + }); - _delay_library_check.connectCallback([this]() { - onLibraryUpdated(); - } ); + _delay_library_check.connectCallback([this]() { onLibraryUpdated(); }); connect(ui->textLibrary, &QTextEdit::textChanged, - [this]() { - _delay_library_check.triggerSignal(250); } - ); + [this]() { _delay_library_check.triggerSignal(250); }); connect(ui->pushButtonDefaultLibrary, &QPushButton::clicked, - [=]() { ui->textLibrary->setPlainText( library_default_code ); } ); + [=]() { ui->textLibrary->setPlainText(library_default_code); }); - connect(ui->pushButtonApplyLibrary, &QPushButton::clicked, - this, &ToolboxLuaEditor::onReloadLibrary); + connect(ui->pushButtonApplyLibrary, &QPushButton::clicked, this, + &ToolboxLuaEditor::onReloadLibrary); - - ui->textGlobal->setHighlighter( new QLuaHighlighter ); - ui->textFunction->setHighlighter( new QLuaHighlighter ); - ui->textLibrary->setHighlighter( new QLuaHighlighter ); + ui->textGlobal->setHighlighter(new QLuaHighlighter); + ui->textFunction->setHighlighter(new QLuaHighlighter); + ui->textLibrary->setHighlighter(new QLuaHighlighter); _completer = new QLuaCompleter(this); - ui->textGlobal->setCompleter( _completer ); - ui->textFunction->setCompleter( _completer ); - ui->textLibrary->setCompleter( _completer ); + ui->textGlobal->setCompleter(_completer); + ui->textFunction->setCompleter(_completer); + ui->textLibrary->setCompleter(_completer); // restore recent functions QSettings settings; - auto previous_functions = settings.value("ToolboxLuaEditor/recent_functions", "").toString(); - if( previous_functions.isEmpty() == false) + auto previous_functions = + settings.value("ToolboxLuaEditor/recent_functions", "").toString(); + if (previous_functions.isEmpty() == false) { QDomDocument xml_doc; - if(xml_doc.setContent(previous_functions)) + if (xml_doc.setContent(previous_functions)) { auto root = xml_doc.firstChild(); - for(auto elem = root.firstChildElement("function"); !elem.isNull(); - elem = elem.nextSiblingElement("function") ) + for (auto elem = root.firstChildElement("function"); !elem.isNull(); + elem = elem.nextSiblingElement("function")) { auto name = elem.attribute("name"); auto item = new QListWidgetItem(name); @@ -97,7 +93,7 @@ ToolboxLuaEditor::ToolboxLuaEditor() } } - if( settings.contains("ToolboxLuaEditor/library")) + if (settings.contains("ToolboxLuaEditor/library")) { QString code = settings.value("ToolboxLuaEditor/library").toString(); ui->textLibrary->setPlainText(code); @@ -113,39 +109,36 @@ ToolboxLuaEditor::~ToolboxLuaEditor() delete ui; } -const char *ToolboxLuaEditor::name() const +const char* ToolboxLuaEditor::name() const { return "Reactive Script Editor"; } -void ToolboxLuaEditor::init(PlotDataMapRef &src_data, - TransformsMap &transform_map) +void ToolboxLuaEditor::init(PlotDataMapRef& src_data, TransformsMap& transform_map) { _plot_data = &src_data; _transforms = &transform_map; - } -std::pair -ToolboxLuaEditor::providedWidget() const +std::pair ToolboxLuaEditor::providedWidget() const { return { _widget, PJ::ToolboxPlugin::FIXED }; } -bool ToolboxLuaEditor::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool ToolboxLuaEditor::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { - if( ui->listWidgetFunctions->count() > 0 ) + if (ui->listWidgetFunctions->count() > 0) { QString msg = "Do you want to save the current active scripts?\n\n"; - for(int row = 0; row < ui->listWidgetFunctions->count(); row++) + for (int row = 0; row < ui->listWidgetFunctions->count(); row++) { auto item = ui->listWidgetFunctions->item(row); msg += QString(" - %1\n").arg(item->text()); } auto ret = QMessageBox::question(nullptr, this->name(), msg); - if( ret == QMessageBox::No ) + if (ret == QMessageBox::No) { return false; } @@ -157,7 +150,7 @@ bool ToolboxLuaEditor::xmlSaveState(QDomDocument &doc, QDomElement &parent_eleme auto scripts_elem = doc.createElement("scripts"); - for(int row = 0; row < ui->listWidgetFunctions->count(); row++) + for (int row = 0; row < ui->listWidgetFunctions->count(); row++) { auto item = ui->listWidgetFunctions->item(row); auto fields = getItemData(item); @@ -172,19 +165,19 @@ bool ToolboxLuaEditor::xmlSaveState(QDomDocument &doc, QDomElement &parent_eleme return true; } -bool ToolboxLuaEditor::xmlLoadState(const QDomElement &parent_element) +bool ToolboxLuaEditor::xmlLoadState(const QDomElement& parent_element) { auto library_elem = parent_element.firstChildElement("library"); - if(!library_elem.isNull()) + if (!library_elem.isNull()) { - ui->textLibrary->setPlainText( library_elem.attribute("code") ); + ui->textLibrary->setPlainText(library_elem.attribute("code")); } auto scripts_elem = parent_element.firstChildElement("scripts"); - if(!scripts_elem.isNull()) + if (!scripts_elem.isNull()) { - for (auto elem = scripts_elem.firstChildElement("script"); - elem.isNull() == false; elem = elem.nextSiblingElement("script")) + for (auto elem = scripts_elem.firstChildElement("script"); elem.isNull() == false; + elem = elem.nextSiblingElement("script")) { ui->listWidgetFunctions->clear(); QString name = elem.attribute("name"); @@ -195,7 +188,7 @@ bool ToolboxLuaEditor::xmlLoadState(const QDomElement &parent_element) ui->listWidgetFunctions->addItem(item); auto lua_function = std::make_shared( - _plot_data, global, function, ui->textLibrary->toPlainText() ); + _plot_data, global, function, ui->textLibrary->toPlainText()); (*_transforms)[name.toStdString()] = lua_function; } @@ -210,13 +203,14 @@ bool ToolboxLuaEditor::onShowWidget() ui->listWidgetFunctions->clear(); // check the already existing functions. - for(auto it : *_transforms) + for (auto it : *_transforms) { - if( auto lua_function = std::dynamic_pointer_cast( it.second )) + if (auto lua_function = std::dynamic_pointer_cast(it.second)) { QString name = QString::fromStdString(it.first); auto item = new QListWidgetItem(name); - setItemData(item, name, lua_function->getGlobalCode(), lua_function->getFunctionCode()); + setItemData(item, name, lua_function->getGlobalCode(), + lua_function->getFunctionCode()); ui->listWidgetFunctions->addItem(item); } ui->listWidgetFunctions->sortItems(); @@ -232,12 +226,12 @@ bool ToolboxLuaEditor::onShowWidget() QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); fixedFont.setPointSize(_font_size); - ui->textGlobal->setFont( fixedFont ); - ui->textFunction->setFont( fixedFont ); - ui->textLibrary->setFont( fixedFont ); + ui->textGlobal->setFont(fixedFont); + ui->textFunction->setFont(fixedFont); + ui->textLibrary->setFont(fixedFont); - auto style_path = (theme == "light" ) ? ":/resources/lua_style_light.xml" : - ":/resources/lua_style_dark.xml"; + auto style_path = (theme == "light") ? ":/resources/lua_style_light.xml" : + ":/resources/lua_style_dark.xml"; QFile fl(style_path); if (fl.open(QIODevice::ReadOnly)) @@ -245,9 +239,9 @@ bool ToolboxLuaEditor::onShowWidget() auto style = new QSyntaxStyle(this); if (style->load(fl.readAll())) { - ui->textGlobal->setSyntaxStyle( style ); - ui->textFunction->setSyntaxStyle( style ); - ui->textLibrary->setSyntaxStyle( style ); + ui->textGlobal->setSyntaxStyle(style); + ui->textFunction->setSyntaxStyle(style); + ui->textLibrary->setSyntaxStyle(style); } } @@ -257,7 +251,7 @@ bool ToolboxLuaEditor::onShowWidget() void ToolboxLuaEditor::onSave() { auto name = ui->lineEditFunctionName->text(); - if(ui->listWidgetFunctions->findItems(name, Qt::MatchExactly).size()>0) + if (ui->listWidgetFunctions->findItems(name, Qt::MatchExactly).size() > 0) { QMessageBox msgBox(_widget); msgBox.setWindowTitle("Warning"); @@ -274,58 +268,61 @@ void ToolboxLuaEditor::onSave() } } - try { + try + { auto lua_function = std::make_shared( - _plot_data, - ui->textGlobal->toPlainText(), - ui->textFunction->toPlainText(), - ui->textLibrary->toPlainText() ); + _plot_data, ui->textGlobal->toPlainText(), ui->textFunction->toPlainText(), + ui->textLibrary->toPlainText()); (*_transforms)[name.toStdString()] = lua_function; - if( ui->listWidgetFunctions->findItems(name, Qt::MatchExactly).empty() ) + if (ui->listWidgetFunctions->findItems(name, Qt::MatchExactly).empty()) { ui->listWidgetFunctions->addItem(name); ui->listWidgetFunctions->sortItems(); } auto item = ui->listWidgetFunctions->findItems(name, Qt::MatchExactly).first(); - setItemData(item, name, ui->textGlobal->toPlainText(), ui->textFunction->toPlainText()); + setItemData(item, name, ui->textGlobal->toPlainText(), + ui->textFunction->toPlainText()); - for( auto& new_name: lua_function->createdCurves() ) + for (auto& new_name : lua_function->createdCurves()) { emit plotCreated(new_name); } } - catch(std::runtime_error& err) + catch (std::runtime_error& err) { - QMessageBox::warning(nullptr, "Error in Lua code", QString(err.what()), QMessageBox::Cancel); + QMessageBox::warning(nullptr, "Error in Lua code", QString(err.what()), + QMessageBox::Cancel); } auto prev_items = ui->listWidgetRecent->findItems(name, Qt::MatchExactly); // new name, delete oldest and append - if( prev_items.empty() ) + if (prev_items.empty()) { - while( ui->listWidgetRecent->count() >= 10 ) + while (ui->listWidgetRecent->count() >= 10) { delete ui->listWidgetRecent->takeItem(0); } } - else{ + else + { // overwrite item with same name - auto row = ui->listWidgetRecent->row( prev_items.first() ); + auto row = ui->listWidgetRecent->row(prev_items.first()); delete ui->listWidgetRecent->takeItem(row); } // save recent functions auto new_item = new QListWidgetItem(name); - setItemData(new_item, name, ui->textGlobal->toPlainText(), ui->textFunction->toPlainText()); + setItemData(new_item, name, ui->textGlobal->toPlainText(), + ui->textFunction->toPlainText()); ui->listWidgetRecent->addItem(new_item); QDomDocument xml_doc; auto root = xml_doc.createElement("functions"); - for(int row = 0; row < ui->listWidgetRecent->count(); row++) + for (int row = 0; row < ui->listWidgetRecent->count(); row++) { auto item = ui->listWidgetRecent->item(row); auto fields = getItemData(item); @@ -344,7 +341,7 @@ void ToolboxLuaEditor::onSave() void ToolboxLuaEditor::onDelete() { - for(auto item: ui->listWidgetFunctions->selectedItems()) + for (auto item : ui->listWidgetFunctions->selectedItems()) { _transforms->erase(item->text().toStdString()); @@ -353,7 +350,7 @@ void ToolboxLuaEditor::onDelete() } } -void ToolboxLuaEditor::restoreRecent(const QModelIndex &index) +void ToolboxLuaEditor::restoreRecent(const QModelIndex& index) { auto item = ui->listWidgetRecent->item(index.row()); auto fields = getItemData(item); @@ -362,7 +359,7 @@ void ToolboxLuaEditor::restoreRecent(const QModelIndex &index) ui->textFunction->setPlainText(fields.function_code); } -void ToolboxLuaEditor::restoreFunction(const QModelIndex &index) +void ToolboxLuaEditor::restoreFunction(const QModelIndex& index) { auto item = ui->listWidgetFunctions->item(index.row()); auto fields = getItemData(item); @@ -373,24 +370,25 @@ void ToolboxLuaEditor::restoreFunction(const QModelIndex &index) void ToolboxLuaEditor::onLibraryUpdated() { - if( ui->textLibrary->toPlainText() == _previous_library ) + if (ui->textLibrary->toPlainText() == _previous_library) { ui->pushButtonApplyLibrary->setEnabled(false); return; } QString svg_name = ":/resources/svg/green_circle.svg"; - try { + try + { ReactiveLuaFunction tmp(_plot_data, "", "", ui->textLibrary->toPlainText()); ui->labelSemaphore->setToolTip("Everything is fine :)"); int active_series = ui->listWidgetFunctions->count(); - ui->pushButtonApplyLibrary->setEnabled( active_series > 0 ); + ui->pushButtonApplyLibrary->setEnabled(active_series > 0); _previous_library = ui->textLibrary->toPlainText(); QSettings settings; settings.setValue("ToolboxLuaEditor/library", ui->textLibrary->toPlainText()); } - catch(std::runtime_error& ex) + catch (std::runtime_error& ex) { QString error_msg = ex.what(); ui->labelSemaphore->setToolTip(error_msg); @@ -402,37 +400,41 @@ void ToolboxLuaEditor::onLibraryUpdated() file.open(QFile::ReadOnly | QFile::Text); QByteArray content(file.readAll()); QSvgRenderer rr(content); - QImage image(ui->labelSemaphore->width(), ui->labelSemaphore->height(), QImage::Format_ARGB32); + QImage image(ui->labelSemaphore->width(), ui->labelSemaphore->height(), + QImage::Format_ARGB32); QPainter painter(&image); image.fill(Qt::transparent); rr.render(&painter); - ui->labelSemaphore->setPixmap( QPixmap::fromImage(image) ); + ui->labelSemaphore->setPixmap(QPixmap::fromImage(image)); } void ToolboxLuaEditor::onReloadLibrary() { - for(int row = 0; row < ui->listWidgetFunctions->count(); row++) + for (int row = 0; row < ui->listWidgetFunctions->count(); row++) { auto item = ui->listWidgetFunctions->item(row); auto name = item->text(); auto fields = getItemData(item); - try{ + try + { auto lua_function = std::make_shared( - _plot_data, fields.global_code, fields.function_code, ui->textLibrary->toPlainText() ); + _plot_data, fields.global_code, fields.function_code, + ui->textLibrary->toPlainText()); (*_transforms)[fields.name.toStdString()] = lua_function; } - catch(std::runtime_error& err) + catch (std::runtime_error& err) { - QMessageBox::warning(nullptr, "Error in Lua code", QString(err.what()), QMessageBox::Cancel); + QMessageBox::warning(nullptr, "Error in Lua code", QString(err.what()), + QMessageBox::Cancel); } } ui->pushButtonApplyLibrary->setEnabled(false); } -bool ToolboxLuaEditor::eventFilter(QObject *obj, QEvent *ev) +bool ToolboxLuaEditor::eventFilter(QObject* obj, QEvent* ev) { - if(obj != ui->textGlobal && obj != ui->textFunction && obj != ui->textLibrary ) + if (obj != ui->textGlobal && obj != ui->textFunction && obj != ui->textLibrary) { return false; } @@ -462,7 +464,7 @@ bool ToolboxLuaEditor::eventFilter(QObject *obj, QEvent *ev) _dragging_curves.push_back(curve_name); } } - if( !_dragging_curves.empty() ) + if (!_dragging_curves.empty()) { event->acceptProposedAction(); } @@ -472,7 +474,7 @@ bool ToolboxLuaEditor::eventFilter(QObject *obj, QEvent *ev) else if (ev->type() == QEvent::Drop) { auto text_edit = qobject_cast(obj); - for(const auto& name: _dragging_curves) + for (const auto& name : _dragging_curves) { text_edit->insertPlainText(QString("\"%1\"\n").arg(name)); } @@ -500,9 +502,9 @@ bool ToolboxLuaEditor::eventFilter(QObject *obj, QEvent *ev) { auto font = ui->textGlobal->font(); font.setPointSize(_font_size); - ui->textGlobal->setFont( font ); - ui->textFunction->setFont( font ); - ui->textLibrary->setFont( font ); + ui->textGlobal->setFont(font); + ui->textFunction->setFont(font); + ui->textLibrary->setFont(font); QSettings settings; settings.setValue("ToolboxLuaEditor/fonts_size", _font_size); @@ -513,7 +515,8 @@ bool ToolboxLuaEditor::eventFilter(QObject *obj, QEvent *ev) return false; } -ToolboxLuaEditor::SavedData ToolboxLuaEditor::getItemData(const QListWidgetItem *item) const +ToolboxLuaEditor::SavedData +ToolboxLuaEditor::getItemData(const QListWidgetItem* item) const { auto fields = item->data(Qt::UserRole).toStringList(); SavedData data; @@ -523,10 +526,8 @@ ToolboxLuaEditor::SavedData ToolboxLuaEditor::getItemData(const QListWidgetItem return data; } -void ToolboxLuaEditor::setItemData(QListWidgetItem *item, - QString name, - QString global_code, - QString function_code) +void ToolboxLuaEditor::setItemData(QListWidgetItem* item, QString name, + QString global_code, QString function_code) { QStringList save_fields; save_fields.push_back(name); diff --git a/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.h b/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.h index 8ac8baffd..15bc75570 100644 --- a/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.h +++ b/plotjuggler_plugins/ToolboxLuaEditor/lua_editor.h @@ -31,8 +31,7 @@ class ToolboxLuaEditor : public PJ::ToolboxPlugin const char* name() const override; - void init(PJ::PlotDataMapRef& src_data, - PJ::TransformsMap& transform_map) override; + void init(PJ::PlotDataMapRef& src_data, PJ::TransformsMap& transform_map) override; std::pair providedWidget() const override; @@ -48,9 +47,9 @@ public slots: void onDelete(); - void restoreRecent(const QModelIndex &index); + void restoreRecent(const QModelIndex& index); - void restoreFunction(const QModelIndex &index); + void restoreFunction(const QModelIndex& index); void onLibraryUpdated(); @@ -63,8 +62,7 @@ public slots: PJ::PlotDataMapRef* _plot_data = nullptr; PJ::TransformsMap* _transforms = nullptr; - - bool eventFilter(QObject *obj, QEvent *event) override; + bool eventFilter(QObject* obj, QEvent* event) override; QStringList _dragging_curves; QLuaCompleter* _completer; @@ -83,7 +81,8 @@ public slots: SavedData getItemData(const QListWidgetItem* item) const; - void setItemData(QListWidgetItem* item, QString name, QString global_code, QString function_code); + void setItemData(QListWidgetItem* item, QString name, QString global_code, + QString function_code); }; -#endif // LUA_EDITOR_H +#endif // LUA_EDITOR_H diff --git a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp index ee4672c72..c0d173810 100644 --- a/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp +++ b/plotjuggler_plugins/ToolboxQuaternion/toolbox_quaternion.cpp @@ -165,10 +165,10 @@ bool ToolboxQuaternion::generateRPY(GenerateType type) std::vector src_data; { - for(QLineEdit* line: {ui->lineEditX, ui->lineEditY, ui->lineEditZ, ui->lineEditW }) + for (QLineEdit* line : { ui->lineEditX, ui->lineEditY, ui->lineEditZ, ui->lineEditW }) { - auto it = _plot_data->numeric.find( line->text().toStdString() ); - if( it == _plot_data->numeric.end() ) + auto it = _plot_data->numeric.find(line->text().toStdString()); + if (it == _plot_data->numeric.end()) { return false; } @@ -181,9 +181,9 @@ bool ToolboxQuaternion::generateRPY(GenerateType type) // remove previous cruves bvefore creating new one _plot_widget->removeAllCurves(); - _preview_data_roll.reset( new PlotData(prefix + "roll", {}) ); - _preview_data_pitch.reset( new PlotData(prefix + "pitch", {}) ); - _preview_data_yaw.reset( new PlotData(prefix + "yaw", {}) ); + _preview_data_roll.reset(new PlotData(prefix + "roll", {})); + _preview_data_pitch.reset(new PlotData(prefix + "pitch", {})); + _preview_data_yaw.reset(new PlotData(prefix + "yaw", {})); std::vector dst_vector = { _preview_data_roll.get(), _preview_data_pitch.get(), diff --git a/plotjuggler_plugins/VideoViewer/qoi.h b/plotjuggler_plugins/VideoViewer/qoi.h index f2c519f43..5cd189633 100644 --- a/plotjuggler_plugins/VideoViewer/qoi.h +++ b/plotjuggler_plugins/VideoViewer/qoi.h @@ -227,7 +227,6 @@ The alpha value remains unchanged from the previous pixel. */ - /* ----------------------------------------------------------------------------- Header - Public functions */ @@ -250,10 +249,11 @@ You may use the constants QOI_SRGB or QOI_LINEAR. The colorspace is purely informative. It will be saved to the file header, but does not affect en-/decoding in any way. */ -#define QOI_SRGB 0 +#define QOI_SRGB 0 #define QOI_LINEAR 1 -typedef struct { +typedef struct +{ unsigned int width; unsigned int height; unsigned char channels; @@ -269,8 +269,7 @@ number of channels (3 = RGB, 4 = RGBA) and the colorspace. The function returns 0 on failure (invalid parameters, or fopen or malloc failed) or the number of bytes written on success. */ -int qoi_write(const char *filename, const void *data, const qoi_desc *desc); - +int qoi_write(const char* filename, const void* data, const qoi_desc* desc); /* Read and decode a QOI image from the file system. If channels is 0, the number of channels from the file header is used. If channels is 3 or 4 the @@ -282,11 +281,10 @@ will be filled with the description from the file header. The returned pixel data should be free()d after use. */ -void *qoi_read(const char *filename, qoi_desc *desc, int channels); +void* qoi_read(const char* filename, qoi_desc* desc, int channels); #endif /* QOI_NO_STDIO */ - /* Encode raw RGB or RGBA pixels into a QOI image in memory. The function either returns NULL on failure (invalid parameters or malloc @@ -295,8 +293,7 @@ is set to the size in bytes of the encoded data. The returned qoi data should be free()d after use. */ -void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len); - +void* qoi_encode(const void* data, const qoi_desc* desc, int* out_len); /* Decode a QOI image from memory. @@ -306,15 +303,13 @@ is filled with the description from the file header. The returned pixel data should be free()d after use. */ -void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels); - +void* qoi_decode(const void* data, int size, qoi_desc* desc, int channels); #ifdef __cplusplus } #endif #endif /* QOI_H */ - /* ----------------------------------------------------------------------------- Implementation */ @@ -323,26 +318,26 @@ Implementation */ #include #ifndef QOI_MALLOC - #define QOI_MALLOC(sz) malloc(sz) - #define QOI_FREE(p) free(p) +#define QOI_MALLOC(sz) malloc(sz) +#define QOI_FREE(p) free(p) #endif #ifndef QOI_ZEROARR - #define QOI_ZEROARR(a) memset((a),0,sizeof(a)) +#define QOI_ZEROARR(a) memset((a), 0, sizeof(a)) #endif -#define QOI_OP_INDEX 0x00 /* 00xxxxxx */ -#define QOI_OP_DIFF 0x40 /* 01xxxxxx */ -#define QOI_OP_LUMA 0x80 /* 10xxxxxx */ -#define QOI_OP_RUN 0xc0 /* 11xxxxxx */ -#define QOI_OP_RGB 0xfe /* 11111110 */ -#define QOI_OP_RGBA 0xff /* 11111111 */ +#define QOI_OP_INDEX 0x00 /* 00xxxxxx */ +#define QOI_OP_DIFF 0x40 /* 01xxxxxx */ +#define QOI_OP_LUMA 0x80 /* 10xxxxxx */ +#define QOI_OP_RUN 0xc0 /* 11xxxxxx */ +#define QOI_OP_RGB 0xfe /* 11111110 */ +#define QOI_OP_RGBA 0xff /* 11111111 */ -#define QOI_MASK_2 0xc0 /* 11000000 */ +#define QOI_MASK_2 0xc0 /* 11000000 */ -#define QOI_COLOR_HASH(C) (C.rgba.r*3 + C.rgba.g*5 + C.rgba.b*7 + C.rgba.a*11) -#define QOI_MAGIC \ - (((unsigned int)'q') << 24 | ((unsigned int)'o') << 16 | \ - ((unsigned int)'i') << 8 | ((unsigned int)'f')) +#define QOI_COLOR_HASH(C) (C.rgba.r * 3 + C.rgba.g * 5 + C.rgba.b * 7 + C.rgba.a * 11) +#define QOI_MAGIC \ + (((unsigned int)'q') << 24 | ((unsigned int)'o') << 16 | ((unsigned int)'i') << 8 | \ + ((unsigned int)'f')) #define QOI_HEADER_SIZE 14 /* 2GB is the max file size that this implementation can safely handle. We guard @@ -351,21 +346,27 @@ pixel, rounded down to a nice clean value. 400 million pixels ought to be enough for anybody. */ #define QOI_PIXELS_MAX ((unsigned int)400000000) -typedef union { - struct { unsigned char r, g, b, a; } rgba; +typedef union +{ + struct + { + unsigned char r, g, b, a; + } rgba; unsigned int v; } qoi_rgba_t; -static const unsigned char qoi_padding[8] = {0,0,0,0,0,0,0,1}; +static const unsigned char qoi_padding[8] = { 0, 0, 0, 0, 0, 0, 0, 1 }; -void qoi_write_32(unsigned char *bytes, int *p, unsigned int v) { +void qoi_write_32(unsigned char* bytes, int* p, unsigned int v) +{ bytes[(*p)++] = (0xff000000 & v) >> 24; bytes[(*p)++] = (0x00ff0000 & v) >> 16; bytes[(*p)++] = (0x0000ff00 & v) >> 8; bytes[(*p)++] = (0x000000ff & v); } -unsigned int qoi_read_32(const unsigned char *bytes, int *p) { +unsigned int qoi_read_32(const unsigned char* bytes, int* p) +{ unsigned int a = bytes[(*p)++]; unsigned int b = bytes[(*p)++]; unsigned int c = bytes[(*p)++]; @@ -373,31 +374,29 @@ unsigned int qoi_read_32(const unsigned char *bytes, int *p) { return a << 24 | b << 16 | c << 8 | d; } -void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { +void* qoi_encode(const void* data, const qoi_desc* desc, int* out_len) +{ int i, max_size, p, run; int px_len, px_end, px_pos, channels; - unsigned char *bytes; - const unsigned char *pixels; + unsigned char* bytes; + const unsigned char* pixels; qoi_rgba_t index[64]; qoi_rgba_t px, px_prev; - if ( - data == NULL || out_len == NULL || desc == NULL || - desc->width == 0 || desc->height == 0 || - desc->channels < 3 || desc->channels > 4 || - desc->colorspace > 1 || - desc->height >= QOI_PIXELS_MAX / desc->width - ) { + if (data == NULL || out_len == NULL || desc == NULL || desc->width == 0 || + desc->height == 0 || desc->channels < 3 || desc->channels > 4 || + desc->colorspace > 1 || desc->height >= QOI_PIXELS_MAX / desc->width) + { return NULL; } - max_size = - desc->width * desc->height * (desc->channels + 1) + - QOI_HEADER_SIZE + sizeof(qoi_padding); + max_size = desc->width * desc->height * (desc->channels + 1) + QOI_HEADER_SIZE + + sizeof(qoi_padding); p = 0; - bytes = (unsigned char *) QOI_MALLOC(max_size); - if (!bytes) { + bytes = (unsigned char*)QOI_MALLOC(max_size); + if (!bytes) + { return NULL; } @@ -407,8 +406,7 @@ void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { bytes[p++] = desc->channels; bytes[p++] = desc->colorspace; - - pixels = (const unsigned char *)data; + pixels = (const unsigned char*)data; QOI_ZEROARR(index); @@ -423,40 +421,50 @@ void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { px_end = px_len - desc->channels; channels = desc->channels; - for (px_pos = 0; px_pos < px_len; px_pos += channels) { - if (channels == 4) { - px = *(qoi_rgba_t *)(pixels + px_pos); + for (px_pos = 0; px_pos < px_len; px_pos += channels) + { + if (channels == 4) + { + px = *(qoi_rgba_t*)(pixels + px_pos); } - else { + else + { px.rgba.r = pixels[px_pos + 0]; px.rgba.g = pixels[px_pos + 1]; px.rgba.b = pixels[px_pos + 2]; } - if (px.v == px_prev.v) { + if (px.v == px_prev.v) + { run++; - if (run == 62 || px_pos == px_end) { + if (run == 62 || px_pos == px_end) + { bytes[p++] = QOI_OP_RUN | (run - 1); run = 0; } } - else { + else + { int index_pos; - if (run > 0) { + if (run > 0) + { bytes[p++] = QOI_OP_RUN | (run - 1); run = 0; } index_pos = QOI_COLOR_HASH(px) % 64; - if (index[index_pos].v == px.v) { + if (index[index_pos].v == px.v) + { bytes[p++] = QOI_OP_INDEX | index_pos; } - else { + else + { index[index_pos] = px; - if (px.rgba.a == px_prev.rgba.a) { + if (px.rgba.a == px_prev.rgba.a) + { signed char vr = px.rgba.r - px_prev.rgba.r; signed char vg = px.rgba.g - px_prev.rgba.g; signed char vb = px.rgba.b - px_prev.rgba.b; @@ -464,29 +472,25 @@ void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { signed char vg_r = vr - vg; signed char vg_b = vb - vg; - if ( - vr > -3 && vr < 2 && - vg > -3 && vg < 2 && - vb > -3 && vb < 2 - ) { + if (vr > -3 && vr < 2 && vg > -3 && vg < 2 && vb > -3 && vb < 2) + { bytes[p++] = QOI_OP_DIFF | (vr + 2) << 4 | (vg + 2) << 2 | (vb + 2); } - else if ( - vg_r > -9 && vg_r < 8 && - vg > -33 && vg < 32 && - vg_b > -9 && vg_b < 8 - ) { - bytes[p++] = QOI_OP_LUMA | (vg + 32); - bytes[p++] = (vg_r + 8) << 4 | (vg_b + 8); + else if (vg_r > -9 && vg_r < 8 && vg > -33 && vg < 32 && vg_b > -9 && vg_b < 8) + { + bytes[p++] = QOI_OP_LUMA | (vg + 32); + bytes[p++] = (vg_r + 8) << 4 | (vg_b + 8); } - else { + else + { bytes[p++] = QOI_OP_RGB; bytes[p++] = px.rgba.r; bytes[p++] = px.rgba.g; bytes[p++] = px.rgba.b; } } - else { + else + { bytes[p++] = QOI_OP_RGBA; bytes[p++] = px.rgba.r; bytes[p++] = px.rgba.g; @@ -498,7 +502,8 @@ void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { px_prev = px; } - for (i = 0; i < (int)sizeof(qoi_padding); i++) { + for (i = 0; i < (int)sizeof(qoi_padding); i++) + { bytes[p++] = qoi_padding[i]; } @@ -506,24 +511,23 @@ void *qoi_encode(const void *data, const qoi_desc *desc, int *out_len) { return bytes; } -void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) { - const unsigned char *bytes; +void* qoi_decode(const void* data, int size, qoi_desc* desc, int channels) +{ + const unsigned char* bytes; unsigned int header_magic; - unsigned char *pixels; + unsigned char* pixels; qoi_rgba_t index[64]; qoi_rgba_t px; int px_len, chunks_len, px_pos; int p = 0, run = 0; - if ( - data == NULL || desc == NULL || - (channels != 0 && channels != 3 && channels != 4) || - size < QOI_HEADER_SIZE + (int)sizeof(qoi_padding) - ) { + if (data == NULL || desc == NULL || (channels != 0 && channels != 3 && channels != 4) || + size < QOI_HEADER_SIZE + (int)sizeof(qoi_padding)) + { return NULL; } - bytes = (const unsigned char *)data; + bytes = (const unsigned char*)data; header_magic = qoi_read_32(bytes, &p); desc->width = qoi_read_32(bytes, &p); @@ -531,23 +535,22 @@ void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) { desc->channels = bytes[p++]; desc->colorspace = bytes[p++]; - if ( - desc->width == 0 || desc->height == 0 || - desc->channels < 3 || desc->channels > 4 || - desc->colorspace > 1 || - header_magic != QOI_MAGIC || - desc->height >= QOI_PIXELS_MAX / desc->width - ) { + if (desc->width == 0 || desc->height == 0 || desc->channels < 3 || desc->channels > 4 || + desc->colorspace > 1 || header_magic != QOI_MAGIC || + desc->height >= QOI_PIXELS_MAX / desc->width) + { return NULL; } - if (channels == 0) { + if (channels == 0) + { channels = desc->channels; } px_len = desc->width * desc->height * channels; - pixels = (unsigned char *) QOI_MALLOC(px_len); - if (!pixels) { + pixels = (unsigned char*)QOI_MALLOC(px_len); + if (!pixels) + { return NULL; } @@ -558,50 +561,61 @@ void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) { px.rgba.a = 255; chunks_len = size - (int)sizeof(qoi_padding); - for (px_pos = 0; px_pos < px_len; px_pos += channels) { - if (run > 0) { + for (px_pos = 0; px_pos < px_len; px_pos += channels) + { + if (run > 0) + { run--; } - else if (p < chunks_len) { + else if (p < chunks_len) + { int b1 = bytes[p++]; - if (b1 == QOI_OP_RGB) { + if (b1 == QOI_OP_RGB) + { px.rgba.r = bytes[p++]; px.rgba.g = bytes[p++]; px.rgba.b = bytes[p++]; } - else if (b1 == QOI_OP_RGBA) { + else if (b1 == QOI_OP_RGBA) + { px.rgba.r = bytes[p++]; px.rgba.g = bytes[p++]; px.rgba.b = bytes[p++]; px.rgba.a = bytes[p++]; } - else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) { + else if ((b1 & QOI_MASK_2) == QOI_OP_INDEX) + { px = index[b1]; } - else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) { + else if ((b1 & QOI_MASK_2) == QOI_OP_DIFF) + { px.rgba.r += ((b1 >> 4) & 0x03) - 2; px.rgba.g += ((b1 >> 2) & 0x03) - 2; - px.rgba.b += ( b1 & 0x03) - 2; + px.rgba.b += (b1 & 0x03) - 2; } - else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) { + else if ((b1 & QOI_MASK_2) == QOI_OP_LUMA) + { int b2 = bytes[p++]; int vg = (b1 & 0x3f) - 32; px.rgba.r += vg - 8 + ((b2 >> 4) & 0x0f); px.rgba.g += vg; - px.rgba.b += vg - 8 + (b2 & 0x0f); + px.rgba.b += vg - 8 + (b2 & 0x0f); } - else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) { + else if ((b1 & QOI_MASK_2) == QOI_OP_RUN) + { run = (b1 & 0x3f); } index[QOI_COLOR_HASH(px) % 64] = px; } - if (channels == 4) { + if (channels == 4) + { *(qoi_rgba_t*)(pixels + px_pos) = px; } - else { + else + { pixels[px_pos + 0] = px.rgba.r; pixels[px_pos + 1] = px.rgba.g; pixels[px_pos + 2] = px.rgba.b; @@ -614,17 +628,20 @@ void *qoi_decode(const void *data, int size, qoi_desc *desc, int channels) { #ifndef QOI_NO_STDIO #include -int qoi_write(const char *filename, const void *data, const qoi_desc *desc) { - FILE *f = fopen(filename, "wb"); +int qoi_write(const char* filename, const void* data, const qoi_desc* desc) +{ + FILE* f = fopen(filename, "wb"); int size; - void *encoded; + void* encoded; - if (!f) { + if (!f) + { return 0; } encoded = qoi_encode(data, desc, &size); - if (!encoded) { + if (!encoded) + { fclose(f); return 0; } @@ -636,25 +653,29 @@ int qoi_write(const char *filename, const void *data, const qoi_desc *desc) { return size; } -void *qoi_read(const char *filename, qoi_desc *desc, int channels) { - FILE *f = fopen(filename, "rb"); +void* qoi_read(const char* filename, qoi_desc* desc, int channels) +{ + FILE* f = fopen(filename, "rb"); int size, bytes_read; void *pixels, *data; - if (!f) { + if (!f) + { return NULL; } fseek(f, 0, SEEK_END); size = ftell(f); - if (size <= 0) { + if (size <= 0) + { fclose(f); return NULL; } fseek(f, 0, SEEK_SET); data = QOI_MALLOC(size); - if (!data) { + if (!data) + { fclose(f); return NULL; } diff --git a/plotjuggler_plugins/VideoViewer/video_dialog.cpp b/plotjuggler_plugins/VideoViewer/video_dialog.cpp index e3b202b01..8f30c2334 100644 --- a/plotjuggler_plugins/VideoViewer/video_dialog.cpp +++ b/plotjuggler_plugins/VideoViewer/video_dialog.cpp @@ -18,20 +18,21 @@ #define QOI_IMPLEMENTATION #include "qoi.h" -ImageLabel::ImageLabel(QWidget *parent) : - QWidget(parent) +ImageLabel::ImageLabel(QWidget* parent) : QWidget(parent) { } -const QPixmap* ImageLabel::pixmap() const { +const QPixmap* ImageLabel::pixmap() const +{ return &pix; } -void ImageLabel::setPixmap (const QPixmap &pixmap){ +void ImageLabel::setPixmap(const QPixmap& pixmap) +{ pix = pixmap; } -void ImageLabel::paintEvent(QPaintEvent *event) +void ImageLabel::paintEvent(QPaintEvent* event) { QWidget::paintEvent(event); @@ -50,15 +51,12 @@ void ImageLabel::paintEvent(QPaintEvent *event) QPoint corner((rect_size.width() - pix_size.width()) / 2, (rect_size.height() - pix_size.height()) / 2); - QPixmap scaled_pix = pix.scaled(pix_size, - Qt::KeepAspectRatio, - Qt::SmoothTransformation); + QPixmap scaled_pix = + pix.scaled(pix_size, Qt::KeepAspectRatio, Qt::SmoothTransformation); painter.drawPixmap(corner, scaled_pix); } -VideoDialog::VideoDialog(QWidget *parent) : - QDialog(parent), - ui(new Ui::VideoDialog) +VideoDialog::VideoDialog(QWidget* parent) : QDialog(parent), ui(new Ui::VideoDialog) { using namespace QtAV; @@ -76,8 +74,7 @@ VideoDialog::VideoDialog(QWidget *parent) : _media_player->setRenderer(_video_output); ui->verticalLayoutMain->addWidget(_video_output->widget(), 1.0); - connect(_media_player, &AVPlayer::started, - this, &VideoDialog::updateSlider); + connect(_media_player, &AVPlayer::started, this, &VideoDialog::updateSlider); ui->lineEditReference->installEventFilter(this); @@ -97,7 +94,7 @@ VideoDialog::~VideoDialog() bool VideoDialog::loadFile(QString filename) { - if(!filename.isEmpty() && QFileInfo::exists(filename)) + if (!filename.isEmpty() && QFileInfo::exists(filename)) { _media_player->play(filename); _media_player->pause(true); @@ -117,7 +114,6 @@ bool VideoDialog::loadFile(QString filename) return false; } - QString VideoDialog::referenceCurve() const { return ui->lineEditReference->text(); @@ -140,8 +136,8 @@ void VideoDialog::on_loadButton_clicked() QString directory_path = settings.value("VideoDialog.loadDirectory", QDir::currentPath()).toString(); - QString filename = QFileDialog::getOpenFileName(this, tr("Load Video"), - directory_path, tr("(*.*)")); + QString filename = + QFileDialog::getOpenFileName(this, tr("Load Video"), directory_path, tr("(*.*)")); if (!loadFile(filename)) { return; @@ -156,16 +152,17 @@ void VideoDialog::updateSlider() qint64 duration_ms = _media_player->duration(); int num_frames = static_cast(qreal(duration_ms) * fps / 1000.0); ui->timeSlider->setRange(0, num_frames); - _media_player->setNotifyInterval( static_cast(1000 / fps) ); + _media_player->setNotifyInterval(static_cast(1000 / fps)); _media_player->pause(true); ui->timeSlider->setEnabled(true); - if(_media_player->isSeekable() == false || duration_ms == 0) + if (_media_player->isSeekable() == false || duration_ms == 0) { QMessageBox msgBox(this); msgBox.setWindowTitle("Video is not seekable"); - msgBox.setText(tr("Video is not seekable. You will need to decode the video into individual frames.\n")); + msgBox.setText(tr("Video is not seekable. You will need to decode the video into " + "individual frames.\n")); msgBox.addButton(QMessageBox::Cancel); QPushButton* button = msgBox.addButton(tr("Decode!"), QMessageBox::YesRole); msgBox.setDefaultButton(button); @@ -176,7 +173,8 @@ void VideoDialog::updateSlider() { ui->timeSlider->setEnabled(false); } - else{ + else + { on_decodeButton_clicked(); } } @@ -186,20 +184,22 @@ void VideoDialog::on_timeSlider_valueChanged(int num) { double fps = _media_player->statistics().video.frame_rate; double period = 1000 / fps; - qint64 frame_pos = static_cast(qreal(num) * period ); + qint64 frame_pos = static_cast(qreal(num) * period); - if( _decoded ) + if (_decoded) { num = std::max(0, num); - num = std::min(int(_compressed_frames.size()-1), num); + num = std::min(int(_compressed_frames.size() - 1), num); auto& frame = _compressed_frames[num]; - void* data = qoi_decode( frame.data, frame.length, &frame.info, 3); - QImage image(static_cast(data), frame.info.width, frame.info.height, QImage::Format_RGB888); + void* data = qoi_decode(frame.data, frame.length, &frame.info, 3); + QImage image(static_cast(data), frame.info.width, frame.info.height, + QImage::Format_RGB888); - //qDebug() << "ratio: " << double(3*frame.info.width*frame.info.height) / double(frame.length); + // qDebug() << "ratio: " << double(3*frame.info.width*frame.info.height) / + // double(frame.length); - _label->setPixmap( QPixmap::fromImage( image ) ); + _label->setPixmap(QPixmap::fromImage(image)); _label->repaint(); free(data); } @@ -212,20 +212,20 @@ void VideoDialog::on_timeSlider_valueChanged(int num) void VideoDialog::seekByValue(double value) { - if( ui->radioButtonFrame->isChecked() ) + if (ui->radioButtonFrame->isChecked()) { ui->timeSlider->setValue(static_cast(value)); } - else if( ui->radioButtonTime->isChecked() ) + else if (ui->radioButtonTime->isChecked()) { const auto& fps = _media_player->statistics().video.frame_rate; - ui->timeSlider->setValue( static_cast( value * 1000 / fps )); + ui->timeSlider->setValue(static_cast(value * 1000 / fps)); } } bool VideoDialog::eventFilter(QObject* obj, QEvent* ev) { - if( obj != ui->lineEditReference ) + if (obj != ui->lineEditReference) { return false; } @@ -287,10 +287,9 @@ void VideoDialog::on_clearButton_clicked() _compressed_frames.clear(); } - void VideoDialog::on_decodeButton_clicked() { - if( _decoded ) + if (_decoded) { return; } @@ -323,12 +322,13 @@ void VideoDialog::on_decodeButton_clicked() compressed_frame.info.height = frame.height(); compressed_frame.info.channels = 3; compressed_frame.info.colorspace = QOI_LINEAR; - compressed_frame.data = qoi_encode(image.bits(), &compressed_frame.info, &compressed_frame.length); + compressed_frame.data = + qoi_encode(image.bits(), &compressed_frame.info, &compressed_frame.length); -// _frames.push_back( std::move(image) ); - _compressed_frames.push_back( std::move(compressed_frame) ); + // _frames.push_back( std::move(image) ); + _compressed_frames.push_back(std::move(compressed_frame)); - if( ++count % 10 == 0 ) + if (++count % 10 == 0) { progress_dialog.setValue(count); QApplication::processEvents(); @@ -345,6 +345,6 @@ void VideoDialog::on_decodeButton_clicked() _label->setHidden(false); ui->decodeButton->setEnabled(false); - ui->timeSlider->setRange(0, _compressed_frames.size()-1); - on_timeSlider_valueChanged( ui->timeSlider->value() ); + ui->timeSlider->setRange(0, _compressed_frames.size() - 1); + on_timeSlider_valueChanged(ui->timeSlider->value()); } diff --git a/plotjuggler_plugins/VideoViewer/video_dialog.h b/plotjuggler_plugins/VideoViewer/video_dialog.h index 605362725..ca53cb59b 100644 --- a/plotjuggler_plugins/VideoViewer/video_dialog.h +++ b/plotjuggler_plugins/VideoViewer/video_dialog.h @@ -17,26 +17,25 @@ class ImageLabel : public QWidget Q_OBJECT public: - explicit ImageLabel(QWidget *parent = nullptr); + explicit ImageLabel(QWidget* parent = nullptr); const QPixmap* pixmap() const; public slots: void setPixmap(const QPixmap&); protected: - void paintEvent(QPaintEvent *); + void paintEvent(QPaintEvent*); private: QPixmap pix; }; - class VideoDialog : public QDialog { Q_OBJECT public: - explicit VideoDialog(QWidget *parent = nullptr); + explicit VideoDialog(QWidget* parent = nullptr); ~VideoDialog(); QString referenceCurve() const; @@ -45,7 +44,7 @@ class VideoDialog : public QDialog bool isPaused() const; - Ui::VideoDialog *ui; + Ui::VideoDialog* ui; bool loadFile(QString filename); @@ -54,7 +53,7 @@ private slots: void on_timeSlider_valueChanged(int value); - void closeEvent (QCloseEvent *event) + void closeEvent(QCloseEvent* event) { emit closed(); } @@ -77,15 +76,17 @@ private Q_SLOTS: void closed(); private: - QtAV::VideoOutput *_video_output; - QtAV::AVPlayer *_media_player; + QtAV::VideoOutput* _video_output; + QtAV::AVPlayer* _media_player; std::unique_ptr _frame_reader; - //std::vector _frames; + // std::vector _frames; struct CompressedFrame { - CompressedFrame(): length(0), data(nullptr) {} + CompressedFrame() : length(0), data(nullptr) + { + } CompressedFrame(const CompressedFrame&) = delete; - CompressedFrame(CompressedFrame&& other): length(0), data(nullptr) + CompressedFrame(CompressedFrame&& other) : length(0), data(nullptr) { std::swap(other.data, data); std::swap(other.length, length); @@ -93,7 +94,8 @@ private Q_SLOTS: ~CompressedFrame() { - if(data) free(data); + if (data) + free(data); } int length; @@ -105,9 +107,9 @@ private Q_SLOTS: bool eventFilter(QObject* obj, QEvent* ev); QString _dragging_curve; - ImageLabel *_label; + ImageLabel* _label; bool _decoded = false; }; -#endif // VIDEO_DIALOG_H +#endif // VIDEO_DIALOG_H diff --git a/plotjuggler_plugins/VideoViewer/video_viewer.cpp b/plotjuggler_plugins/VideoViewer/video_viewer.cpp index 23da1f262..343277c38 100644 --- a/plotjuggler_plugins/VideoViewer/video_viewer.cpp +++ b/plotjuggler_plugins/VideoViewer/video_viewer.cpp @@ -7,11 +7,10 @@ PublisherVideo::PublisherVideo() { _dialog = new VideoDialog(nullptr); - connect(_dialog, &VideoDialog::closed, this, [this]() - { - setEnabled(false); - emit closed(); - }); + connect(_dialog, &VideoDialog::closed, this, [this]() { + setEnabled(false); + emit closed(); + }); } PublisherVideo::~PublisherVideo() @@ -21,25 +20,25 @@ PublisherVideo::~PublisherVideo() void PublisherVideo::updateState(double current_time) { - if(_dialog->isHidden()) + if (_dialog->isHidden()) { return; } QString ref_curve = _dialog->referenceCurve(); - if(ref_curve.isEmpty()) + if (ref_curve.isEmpty()) { return; } auto it = _datamap->numeric.find(ref_curve.toStdString()); - if( it == _datamap->numeric.end() ) + if (it == _datamap->numeric.end()) { return; } const auto& data = it->second; auto position = data.getYfromX(current_time); - if( position ) + if (position) { - if( !_dialog->isPaused() ) + if (!_dialog->isPaused()) { _dialog->pause(true); } @@ -52,31 +51,33 @@ void PublisherVideo::play(double current_time) updateState(current_time); } -bool PublisherVideo::xmlSaveState(QDomDocument &doc, QDomElement &parent_element) const +bool PublisherVideo::xmlSaveState(QDomDocument& doc, QDomElement& parent_element) const { QDomElement config = doc.createElement("config"); config.setAttribute("video_file", _dialog->ui->lineFilename->text()); config.setAttribute("curve_name", _dialog->ui->lineEditReference->text()); - config.setAttribute("use_frame", _dialog->ui->radioButtonFrame->isChecked() ? "true" : "false"); + config.setAttribute("use_frame", + _dialog->ui->radioButtonFrame->isChecked() ? "true" : "false"); parent_element.appendChild(config); return true; } -bool PublisherVideo::xmlLoadState(const QDomElement &parent_element) +bool PublisherVideo::xmlLoadState(const QDomElement& parent_element) { QDomElement config = parent_element.firstChildElement("config"); - if( config.isNull() ) + if (config.isNull()) { return false; } - _dialog->loadFile( config.attribute("video_file") ); - _dialog->ui->lineEditReference->setText( config.attribute("curve_name") ); - if( config.attribute("use_frame") == "true" ) + _dialog->loadFile(config.attribute("video_file")); + _dialog->ui->lineEditReference->setText(config.attribute("curve_name")); + if (config.attribute("use_frame") == "true") { _dialog->ui->radioButtonFrame->setChecked(true); } - else{ + else + { _dialog->ui->radioButtonTime->setChecked(true); } _xml_loaded = true; @@ -87,12 +88,12 @@ void PublisherVideo::setEnabled(bool enabled) { QSettings settings; auto ui = _dialog->ui; - if(enabled) + if (enabled) { - if( !_xml_loaded ) + if (!_xml_loaded) { QString filename = settings.value("VideoDialog::video_file", "").toString(); - if(filename != ui->lineFilename->text()) + if (filename != ui->lineFilename->text()) { _dialog->loadFile(filename); } diff --git a/plotjuggler_plugins/VideoViewer/video_viewer.h b/plotjuggler_plugins/VideoViewer/video_viewer.h index ca35c07c5..2d7060f68 100644 --- a/plotjuggler_plugins/VideoViewer/video_viewer.h +++ b/plotjuggler_plugins/VideoViewer/video_viewer.h @@ -42,7 +42,6 @@ public slots: virtual void setEnabled(bool enabled) override; private: - bool _enabled = false; bool _xml_loaded = false;