commit
stringlengths
40
40
old_file
stringlengths
2
205
new_file
stringlengths
2
205
old_contents
stringlengths
0
32.9k
new_contents
stringlengths
1
38.9k
subject
stringlengths
3
9.4k
message
stringlengths
6
9.84k
lang
stringlengths
3
13
license
stringclasses
13 values
repos
stringlengths
6
115k
f55215eadc99cb9d56fb82701abe53a546571d30
statusview.cpp
statusview.cpp
/* LICENSE AND COPYRIGHT INFORMATION - Please read carefully. Copyright (c) 2010-2013, davyjones <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "statusview.h" StatusView::StatusView(Database *database) { menuBar()->setVisible(false); setWindowTitle(tr("Status - ").append(database->getName())); setObjectName("Status"); setContextMenuPolicy(Qt::NoContextMenu); this->database = database; createActions(); QSettings settings("pgXplorer", "pgXplorer"); ti = static_cast<StatusView::TimerInterval> (settings.value("interval", StatusView::NoInterval).toInt()); if(timerInterval() == StatusView::TimerInterval1) setTimerInterval1(); else if(timerInterval() == StatusView::TimerInterval2) setTimerInterval2(); else setNoInterval(); toolbar = new ToolBar; toolbar->setIconSize(QSize(36,36)); toolbar->setObjectName("statusview"); toolbar->setMovable(false); toolbar->addAction(refresh_action); toolbar->addAction(stop_action); toolbar->addAction(terminate_action); toolbar->addSeparator(); toolbar->addWidget(timer_button); toolbar->addSeparator(); toolbar->addAction(copy_action); addToolBar(toolbar); status_query_model = new QSqlQueryModel; status_view = new QTableView(this); status_view->setSelectionBehavior(QAbstractItemView::SelectRows); status_view->setSelectionMode(QAbstractItemView::SingleSelection); status_view->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); status_view->setModel(status_query_model); QString sql; if(database->settings("server_version_num").compare("90200") < 0) { sql = ("SELECT procpid AS \"PID\", usename AS \"User\", client_addr AS \"Client\", query_start AS \"Started\", current_query AS \"Query\" FROM pg_stat_activity where current_query not like '%pg_stat_activity%' and datname='"); } else { sql = ("SELECT pid AS \"PID\", usename AS \"User\", client_addr AS \"Client\", query_start AS \"Started\", query AS \"Query\" FROM pg_stat_activity where query not like '%pg_stat_activity%' and state<>'idle' and datname='"); } sql.append(database->getName() + "'"); status_query_thread = new SimpleQueryThread(0, status_query_model, sql); status_query_thread->setConnectionParameters(database->getHost(), database->getPort(), database->getName(), database->getUser(), database->getPassword()); status_query_thread->setExecOnStart(true); connect(this, &StatusView::requestStatus, status_query_thread, &SimpleQueryThread::executeDefaultQuery); connect(status_query_thread, &SimpleQueryThread::workerIsDone, this, &StatusView::updateStatus); status_query_thread->start(); connect(status_view->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(toggleActions())); setCentralWidget(status_view); statusBar()->showMessage(""); if(timer_interval>0) timer.start(timer_interval, this); } void StatusView::setNoInterval() { timer_interval = 0; no_refresh->setIconVisibleInMenu(true); refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2->setIconVisibleInMenu(false); setTimerInterval(StatusView::NoInterval); } void StatusView::setTimerInterval1() { timer_interval = 10000; no_refresh->setIconVisibleInMenu(false); refresh_freq_1->setIconVisibleInMenu(true); refresh_freq_2->setIconVisibleInMenu(false); setTimerInterval(StatusView::TimerInterval1); } void StatusView::setTimerInterval2() { timer_interval = 20000; no_refresh->setIconVisibleInMenu(false); refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2->setIconVisibleInMenu(true); setTimerInterval(StatusView::TimerInterval2); } void StatusView::updateStatus() { if(!timer.isActive() && timer_interval>0) timer.start(timer_interval, this); status_view->setModel(status_query_model); status_view->resizeColumnsToContents(); toggleActions(); } void StatusView::createActions() { refresh_action = new QAction(QIcon(":/icons/refresh.svg"), tr("Refresh"), this); refresh_action->setShortcut(QKeySequence::Refresh); refresh_action->setStatusTip(tr("Refresh status now")); connect(refresh_action, SIGNAL(triggered()), SIGNAL(requestStatus())); stop_action = new QAction(QIcon(":/icons/stop.svg"), tr("Stop"), this); stop_action->setEnabled(false); stop_action->setStatusTip(tr("Cancel selected query")); connect(stop_action, SIGNAL(triggered()), SLOT(stopQuery())); terminate_action = new QAction(QIcon(":/icons/terminate.svg"), tr("Terminate"), this); terminate_action->setEnabled(false); terminate_action->setStatusTip(tr("Terminate selected query")); connect(terminate_action, SIGNAL(triggered()), SLOT(terminateQuery())); copy_action = new QAction(QIcon(":/icons/copy.svg"), tr("Copy"), this); copy_action->setEnabled(false); copy_action->setStatusTip(tr("Copy selected contents to clipboard")); connect(copy_action, SIGNAL(triggered()), SLOT(copyQuery())); no_refresh = new QAction(QIcon(":/icons/ok.png"), tr("Don't refresh"), this); connect(no_refresh, SIGNAL(triggered()), SLOT(dontRefresh())); if(timerInterval() != StatusView::NoInterval) no_refresh->setIconVisibleInMenu(false); refresh_freq_1 = new QAction(QIcon(":/icons/ok.png"), tr("Refresh every 10s"), this); connect(refresh_freq_1, SIGNAL(triggered()), SLOT(refreshFrequency1())); if(timerInterval() != StatusView::TimerInterval1) refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2 = new QAction(QIcon(":/icons/ok.png"), tr("Refresh every 20s"), this); connect(refresh_freq_2, SIGNAL(triggered()), SLOT(refreshFrequency2())); if(timerInterval() != StatusView::TimerInterval2) refresh_freq_2->setIconVisibleInMenu(false); timer_menu = new QMenu; timer_menu->addAction(no_refresh); timer_menu->addAction(refresh_freq_1); timer_menu->addAction(refresh_freq_2); timer_action = new QAction(QIcon(":/icons/timer.svg"), tr("Set interval"), this); //timer_action->setMenu(timer_menu); timer_action->setStatusTip(tr("Set refresh interval (in seconds)")); timer_button = new QToolButton; timer_button->setAutoRaise(false); timer_button->setPopupMode(QToolButton::InstantPopup); timer_button->setDefaultAction(timer_action); timer_button->setMenu(timer_menu); } void StatusView::toggleActions() { stop_action->setEnabled(false); terminate_action->setEnabled(false); copy_action->setEnabled(false); QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { if(status_view->model()->data(indices.last()).toString().compare("<IDLE>") != 0) { stop_action->setEnabled(true); } terminate_action->setEnabled(true); copy_action->setEnabled(true); } } void StatusView::stopQuery() { int ret = QMessageBox::question(this, "pgXplorer", tr("Do you want to cancel this query?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(ret == QMessageBox::No) return; QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { { QSqlDatabase database_connection; database_connection = QSqlDatabase::addDatabase("QPSQL", QLatin1String("cancel")); database_connection.setHostName(database->getHost()); database_connection.setPort(database->getPort().toInt()); database_connection.setDatabaseName(database->getName()); database_connection.setUserName(database->getUser()); database_connection.setPassword(database->getPassword()); if (!database_connection.open()) { qDebug() << tr("Couldn't connect to database.\n" "Check connection parameters.\n"); return; } QString sql("SELECT pg_cancel_backend(" + status_view->model()->data(indices.first()).toString() + ")"); QSqlQueryModel query_model; query_model.setQuery(sql, database_connection); if (query_model.lastError().isValid()) { qDebug() << query_model.lastError(); } if(query_model.data(query_model.index(0, 0)).toBool()) statusBar()->showMessage(tr("Query was successfully cancelled."), 5000); else statusBar()->showMessage(tr("Could not cancel the selected query. Try terminating it."), 5000); } QSqlDatabase::removeDatabase(QLatin1String("cancel")); } emit requestStatus(); } void StatusView::terminateQuery() { int ret = QMessageBox::question(this, "pgXplorer", tr("Do you want to terminate this query?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(ret == QMessageBox::No) return; QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { { QSqlDatabase database_connection; database_connection = QSqlDatabase::addDatabase("QPSQL", QLatin1String("terminate")); database_connection.setHostName(database->getHost()); database_connection.setPort(database->getPort().toInt()); database_connection.setDatabaseName(database->getName()); database_connection.setUserName(database->getUser()); database_connection.setPassword(database->getPassword()); if (!database_connection.open()) { qDebug() << tr("Couldn't connect to database.\n" "Check connection parameters.\n"); return; } QString sql("SELECT pg_terminate_backend(" + status_view->model()->data(indices.first()).toString() + ")"); QSqlQueryModel query_model; query_model.setQuery(sql, database_connection); if (query_model.lastError().isValid()) { qDebug() << query_model.lastError(); } if(query_model.data(query_model.index(0, 0)).toBool()) statusBar()->showMessage(tr("Query was successfully terminated."), 5000); else statusBar()->showMessage(tr("Could not terminate the selected query. Contact database administrator."), 5000); } QSqlDatabase::removeDatabase(QLatin1String("terminate")); } emit requestStatus(); } void StatusView::copyQuery() { QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; qSort(indices); QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); QModelIndex current; QString selectedText; foreach(current, indices) { QVariant data = status_view->model()->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(status_view->model()->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(selectedText); } void StatusView::dontRefresh() { setNoInterval(); if(timer.isActive()) timer.stop(); } void StatusView::refreshFrequency1() { setTimerInterval1(); if(timer.isActive()) timer.stop(); timer.start(timer_interval, this); } void StatusView::refreshFrequency2() { setTimerInterval2(); if(timer.isActive()) timer.stop(); timer.start(timer_interval, this); } void StatusView::bringOnTop() { activateWindow(); raise(); } void StatusView::timerEvent(QTimerEvent *event) { if(timer.timerId() == event->timerId()) { if(isVisible()) { emit requestStatus(); statusBar()->showMessage(tr("Refreshed just now"), 1000); } else timer.stop(); } } void StatusView::closeEvent(QCloseEvent *event) { event->accept(); QSettings settings("pgXplorer", "pgXplorer"); if(isMaximized()) { settings.setValue("statusview_maximized", true); showNormal(); } else settings.setValue("statusview_maximized", false); settings.setValue("statusview_pos", pos()); settings.setValue("statusview_size", size()); settings.setValue("icon_size", toolbar->iconSize()); settings.setValue("interval", (int) ti); } StatusView::TimerInterval StatusView::timerInterval() const { return ti; } void StatusView::setTimerInterval(TimerInterval timer_interval) { ti = timer_interval; } void StatusView::languageChanged(QEvent *event) { if (event->type() == QEvent::LanguageChange) { setWindowTitle(tr("Status - ").append(database->getName())); refresh_action->setText(tr("Refresh")); stop_action->setText(tr("Stop")); terminate_action->setText(tr("Terminate")); copy_action->setText(tr("Copy")); timer_action->setText(tr("Set interval")); no_refresh->setText(tr("Don't refresh")); refresh_freq_1->setText(tr("Refresh every 10s")); refresh_freq_2->setText(tr("Refresh every 20s")); refresh_action->setStatusTip(tr("Refresh status now")); stop_action->setStatusTip(tr("Cancel selected query")); terminate_action->setStatusTip(tr("Terminate selected query")); copy_action->setStatusTip(tr("Copy selected contents to clipboard")); timer_action->setStatusTip(tr("Set refresh interval (in seconds)")); no_refresh->setStatusTip(tr("Don't refresh")); refresh_freq_1->setStatusTip(tr("Refresh every 10s")); refresh_freq_2->setStatusTip(tr("Refresh every 20s")); } }
/* LICENSE AND COPYRIGHT INFORMATION - Please read carefully. Copyright (c) 2010-2013, davyjones <[email protected]> Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "statusview.h" StatusView::StatusView(Database *database) { menuBar()->setVisible(false); setWindowTitle(tr("Status - ").append(database->getName())); setObjectName("Status"); setContextMenuPolicy(Qt::NoContextMenu); this->database = database; createActions(); QSettings settings("pgXplorer", "pgXplorer"); ti = static_cast<StatusView::TimerInterval> (settings.value("interval", StatusView::NoInterval).toInt()); if(timerInterval() == StatusView::TimerInterval1) setTimerInterval1(); else if(timerInterval() == StatusView::TimerInterval2) setTimerInterval2(); else setNoInterval(); toolbar = new ToolBar; toolbar->setIconSize(QSize(36,36)); toolbar->setObjectName("statusview"); toolbar->setMovable(false); toolbar->addAction(refresh_action); toolbar->addAction(stop_action); toolbar->addAction(terminate_action); toolbar->addSeparator(); toolbar->addWidget(timer_button); toolbar->addSeparator(); toolbar->addAction(copy_action); addToolBar(toolbar); status_query_model = new QSqlQueryModel; status_view = new QTableView(this); status_view->setSelectionBehavior(QAbstractItemView::SelectRows); status_view->setSelectionMode(QAbstractItemView::SingleSelection); status_view->setHorizontalScrollMode(QAbstractItemView::ScrollPerPixel); status_view->setModel(status_query_model); QString sql; if(database->settings("server_version_num").compare("90200") < 0) { sql = ("SELECT procpid AS \"PID\", usename AS \"User\", client_addr AS \"Client\", query_start AS \"Started\", current_query AS \"Query\" FROM pg_stat_activity where current_query not like '%pg_stat_activity%' and datname='"); } else { sql = ("SELECT pid AS \"PID\", usename AS \"User\", client_addr AS \"Client\", query_start AS \"Started\", query AS \"Query\" FROM pg_stat_activity where query not like '%pg_stat_activity%' and state<>'idle' and datname='"); } sql.append(database->getName() + "'"); status_query_thread = new SimpleQueryThread(0, status_query_model, sql); status_query_thread->setConnectionParameters(database->getHost(), database->getPort(), database->getName(), database->getUser(), database->getPassword()); status_query_thread->setExecOnStart(true); connect(this, &StatusView::requestStatus, status_query_thread, &SimpleQueryThread::executeDefaultQuery); connect(status_query_thread, &SimpleQueryThread::workerIsDone, this, &StatusView::updateStatus); status_query_thread->start(); connect(status_view->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), SLOT(toggleActions())); setCentralWidget(status_view); statusBar()->showMessage(""); if(timer_interval>0) timer.start(timer_interval, this); } void StatusView::setNoInterval() { timer_interval = 0; no_refresh->setIconVisibleInMenu(true); refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2->setIconVisibleInMenu(false); setTimerInterval(StatusView::NoInterval); } void StatusView::setTimerInterval1() { timer_interval = 10000; no_refresh->setIconVisibleInMenu(false); refresh_freq_1->setIconVisibleInMenu(true); refresh_freq_2->setIconVisibleInMenu(false); setTimerInterval(StatusView::TimerInterval1); } void StatusView::setTimerInterval2() { timer_interval = 20000; no_refresh->setIconVisibleInMenu(false); refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2->setIconVisibleInMenu(true); setTimerInterval(StatusView::TimerInterval2); } void StatusView::updateStatus() { if(!timer.isActive() && timer_interval>0) timer.start(timer_interval, this); status_view->setModel(status_query_model); status_view->resizeColumnsToContents(); toggleActions(); } void StatusView::createActions() { refresh_action = new QAction(QIcon(":/icons/refresh.svg"), tr("Refresh"), this); refresh_action->setShortcut(QKeySequence::Refresh); refresh_action->setStatusTip(tr("Refresh status now")); connect(refresh_action, SIGNAL(triggered()), SIGNAL(requestStatus())); stop_action = new QAction(QIcon(":/icons/stop.svg"), tr("Stop"), this); stop_action->setEnabled(false); stop_action->setStatusTip(tr("Cancel selected query")); connect(stop_action, SIGNAL(triggered()), SLOT(stopQuery())); terminate_action = new QAction(QIcon(":/icons/terminate.svg"), tr("Terminate"), this); terminate_action->setEnabled(false); terminate_action->setStatusTip(tr("Terminate selected query")); connect(terminate_action, SIGNAL(triggered()), SLOT(terminateQuery())); copy_action = new QAction(QIcon(":/icons/copy.svg"), tr("Copy"), this); copy_action->setEnabled(false); copy_action->setStatusTip(tr("Copy selected contents to clipboard")); connect(copy_action, SIGNAL(triggered()), SLOT(copyQuery())); no_refresh = new QAction(QIcon(":/icons/ok.svg"), tr("Don't refresh"), this); connect(no_refresh, SIGNAL(triggered()), SLOT(dontRefresh())); if(timerInterval() != StatusView::NoInterval) no_refresh->setIconVisibleInMenu(false); refresh_freq_1 = new QAction(QIcon(":/icons/ok.svg"), tr("Refresh every 10s"), this); connect(refresh_freq_1, SIGNAL(triggered()), SLOT(refreshFrequency1())); if(timerInterval() != StatusView::TimerInterval1) refresh_freq_1->setIconVisibleInMenu(false); refresh_freq_2 = new QAction(QIcon(":/icons/ok.svg"), tr("Refresh every 20s"), this); connect(refresh_freq_2, SIGNAL(triggered()), SLOT(refreshFrequency2())); if(timerInterval() != StatusView::TimerInterval2) refresh_freq_2->setIconVisibleInMenu(false); timer_menu = new QMenu; timer_menu->addAction(no_refresh); timer_menu->addAction(refresh_freq_1); timer_menu->addAction(refresh_freq_2); timer_action = new QAction(QIcon(":/icons/timer.svg"), tr("Set interval"), this); //timer_action->setMenu(timer_menu); timer_action->setStatusTip(tr("Set refresh interval (in seconds)")); timer_button = new QToolButton; timer_button->setAutoRaise(false); timer_button->setPopupMode(QToolButton::InstantPopup); timer_button->setDefaultAction(timer_action); timer_button->setMenu(timer_menu); } void StatusView::toggleActions() { stop_action->setEnabled(false); terminate_action->setEnabled(false); copy_action->setEnabled(false); QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { if(status_view->model()->data(indices.last()).toString().compare("<IDLE>") != 0) { stop_action->setEnabled(true); } terminate_action->setEnabled(true); copy_action->setEnabled(true); } } void StatusView::stopQuery() { int ret = QMessageBox::question(this, "pgXplorer", tr("Do you want to cancel this query?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(ret == QMessageBox::No) return; QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { { QSqlDatabase database_connection; database_connection = QSqlDatabase::addDatabase("QPSQL", QLatin1String("cancel")); database_connection.setHostName(database->getHost()); database_connection.setPort(database->getPort().toInt()); database_connection.setDatabaseName(database->getName()); database_connection.setUserName(database->getUser()); database_connection.setPassword(database->getPassword()); if (!database_connection.open()) { qDebug() << tr("Couldn't connect to database.\n" "Check connection parameters.\n"); return; } QString sql("SELECT pg_cancel_backend(" + status_view->model()->data(indices.first()).toString() + ")"); QSqlQueryModel query_model; query_model.setQuery(sql, database_connection); if (query_model.lastError().isValid()) { qDebug() << query_model.lastError(); } if(query_model.data(query_model.index(0, 0)).toBool()) statusBar()->showMessage(tr("Query was successfully cancelled."), 5000); else statusBar()->showMessage(tr("Could not cancel the selected query. Try terminating it."), 5000); } QSqlDatabase::removeDatabase(QLatin1String("cancel")); } emit requestStatus(); } void StatusView::terminateQuery() { int ret = QMessageBox::question(this, "pgXplorer", tr("Do you want to terminate this query?"), QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes); if(ret == QMessageBox::No) return; QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; if(indices.first().row() == indices.last().row()) { { QSqlDatabase database_connection; database_connection = QSqlDatabase::addDatabase("QPSQL", QLatin1String("terminate")); database_connection.setHostName(database->getHost()); database_connection.setPort(database->getPort().toInt()); database_connection.setDatabaseName(database->getName()); database_connection.setUserName(database->getUser()); database_connection.setPassword(database->getPassword()); if (!database_connection.open()) { qDebug() << tr("Couldn't connect to database.\n" "Check connection parameters.\n"); return; } QString sql("SELECT pg_terminate_backend(" + status_view->model()->data(indices.first()).toString() + ")"); QSqlQueryModel query_model; query_model.setQuery(sql, database_connection); if (query_model.lastError().isValid()) { qDebug() << query_model.lastError(); } if(query_model.data(query_model.index(0, 0)).toBool()) statusBar()->showMessage(tr("Query was successfully terminated."), 5000); else statusBar()->showMessage(tr("Could not terminate the selected query. Contact database administrator."), 5000); } QSqlDatabase::removeDatabase(QLatin1String("terminate")); } emit requestStatus(); } void StatusView::copyQuery() { QItemSelectionModel *selection_model = status_view->selectionModel(); QModelIndexList indices = selection_model->selectedIndexes(); if(indices.isEmpty()) return; qSort(indices); QModelIndex prev = indices.first(); QModelIndex last = indices.last(); indices.removeFirst(); QModelIndex current; QString selectedText; foreach(current, indices) { QVariant data = status_view->model()->data(prev); selectedText.append(data.toString()); if(current.row() != prev.row()) selectedText.append(QLatin1Char('\n')); else selectedText.append(QLatin1Char('\t')); prev = current; } selectedText.append(status_view->model()->data(last).toString()); selectedText.append(QLatin1Char('\n')); qApp->clipboard()->setText(selectedText); } void StatusView::dontRefresh() { setNoInterval(); if(timer.isActive()) timer.stop(); } void StatusView::refreshFrequency1() { setTimerInterval1(); if(timer.isActive()) timer.stop(); timer.start(timer_interval, this); } void StatusView::refreshFrequency2() { setTimerInterval2(); if(timer.isActive()) timer.stop(); timer.start(timer_interval, this); } void StatusView::bringOnTop() { activateWindow(); raise(); } void StatusView::timerEvent(QTimerEvent *event) { if(timer.timerId() == event->timerId()) { if(isVisible()) { emit requestStatus(); statusBar()->showMessage(tr("Refreshed just now"), 1000); } else timer.stop(); } } void StatusView::closeEvent(QCloseEvent *event) { event->accept(); QSettings settings("pgXplorer", "pgXplorer"); if(isMaximized()) { settings.setValue("statusview_maximized", true); showNormal(); } else settings.setValue("statusview_maximized", false); settings.setValue("statusview_pos", pos()); settings.setValue("statusview_size", size()); settings.setValue("icon_size", toolbar->iconSize()); settings.setValue("interval", (int) ti); } StatusView::TimerInterval StatusView::timerInterval() const { return ti; } void StatusView::setTimerInterval(TimerInterval timer_interval) { ti = timer_interval; } void StatusView::languageChanged(QEvent *event) { if (event->type() == QEvent::LanguageChange) { setWindowTitle(tr("Status - ").append(database->getName())); refresh_action->setText(tr("Refresh")); stop_action->setText(tr("Stop")); terminate_action->setText(tr("Terminate")); copy_action->setText(tr("Copy")); timer_action->setText(tr("Set interval")); no_refresh->setText(tr("Don't refresh")); refresh_freq_1->setText(tr("Refresh every 10s")); refresh_freq_2->setText(tr("Refresh every 20s")); refresh_action->setStatusTip(tr("Refresh status now")); stop_action->setStatusTip(tr("Cancel selected query")); terminate_action->setStatusTip(tr("Terminate selected query")); copy_action->setStatusTip(tr("Copy selected contents to clipboard")); timer_action->setStatusTip(tr("Set refresh interval (in seconds)")); no_refresh->setStatusTip(tr("Don't refresh")); refresh_freq_1->setStatusTip(tr("Refresh every 10s")); refresh_freq_2->setStatusTip(tr("Refresh every 20s")); } }
Update to svg files.
Update to svg files.
C++
isc
pgXplorer/pgXplorer,pgXplorer/pgXplorer
d8c4ade54871b25c69a9e556a79cf6d79bd47eb2
include/bitcoin/bitcoin/utility/async_strand.hpp
include/bitcoin/bitcoin/utility/async_strand.hpp
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_ASYNC_STRAND_HPP #define LIBBITCOIN_ASYNC_STRAND_HPP #include <functional> #include <thread> #include <boost/asio.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> namespace libbitcoin { template <typename Handler> struct wrapped_handler_impl { Handler handler; boost::asio::io_service::strand& strand; template <typename... Args> void operator()(Args&&... args) { strand.dispatch(std::bind(handler, std::forward<Args>(args)...)); } }; /** * Convenience class for objects wishing to synchronize operations around * shared data. * * queue() guarantees that any handlers passed to it will never * execute at the same time, and they will be called in sequential order. * * randomly_queue() guarantees that any handlers passed to it will never * execute at the same time. */ class BC_API async_strand { public: async_strand(threadpool& pool); /** * wrap() returns a new handler that guarantees that the handler it * encapsulates will never execute at the same time as another handler * passing through this class. */ template <typename Handler, typename... Args> auto wrap(Handler&& handler, Args&&... args) -> wrapped_handler_impl<decltype( std::bind(std::forward<Handler>(handler), std::forward<Args>(args)...))> { const auto forward = std::forward<Handler>(handler); const auto bound = std::bind(forward, std::forward<Args>(args)...); return { bound, strand_ }; } /** * queue() guarantees that any handlers passed to it will * never execute at the same time in sequential order. * * Guarantees sequential calling order. * * @code * strand.queue(handler); * @endcode */ template <typename... Args> void queue(Args&&... args) { strand_.post(std::bind(std::forward<Args>(args)...)); } /** * randomly_queue() guarantees that any handlers passed to it will * never execute at the same time. * * Does not guarantee sequential calling order. * * @code * strand.randomly_queue(handler); * @endcode */ template <typename... Args> void randomly_queue(Args&&... args) { ios_.post(strand_.wrap(std::bind(std::forward<Args>(args)...))); } private: boost::asio::io_service& ios_; boost::asio::io_service::strand strand_; }; } // namespace libbitcoin #endif
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_ASYNC_STRAND_HPP #define LIBBITCOIN_ASYNC_STRAND_HPP #include <functional> #include <thread> #include <boost/asio.hpp> #include <bitcoin/bitcoin/define.hpp> #include <bitcoin/bitcoin/utility/threadpool.hpp> namespace libbitcoin { template <typename Handler> struct wrapped_handler_impl { Handler handler; boost::asio::io_service::strand& strand; template <typename... Args> void operator()(Args&&... args) { strand.dispatch(std::bind(handler, std::forward<Args>(args)...)); } }; /** * Convenience class for objects wishing to synchronize operations around * shared data. * * queue() guarantees that any handlers passed to it will never * execute at the same time, and they will be called in sequential order. * * randomly_queue() guarantees that any handlers passed to it will never * execute at the same time. */ class BC_API async_strand { public: async_strand(threadpool& pool); /** * wrap() returns a new handler that guarantees that the handler it * encapsulates will never execute at the same time as another handler * passing through this class. */ template <typename Handler, typename... Args> auto wrap(Handler&& handler, Args&&... args) -> wrapped_handler_impl<decltype( std::bind( std::forward<Handler>(handler), std::forward<Args>(args)...))> { auto bound = std::bind( std::forward<Handler>(handler), std::forward<Args>(args)...); return { bound, strand_ }; } /** * queue() guarantees that any handlers passed to it will * never execute at the same time in sequential order. * * Guarantees sequential calling order. * * @code * strand.queue(handler); * @endcode */ template <typename... Args> void queue(Args&&... args) { strand_.post(std::bind(std::forward<Args>(args)...)); } /** * randomly_queue() guarantees that any handlers passed to it will * never execute at the same time. * * Does not guarantee sequential calling order. * * @code * strand.randomly_queue(handler); * @endcode */ template <typename... Args> void randomly_queue(Args&&... args) { ios_.post(strand_.wrap(std::bind(std::forward<Args>(args)...))); } private: boost::asio::io_service& ios_; boost::asio::io_service::strand strand_; }; } // namespace libbitcoin #endif
Remove const qualifier (clang).
Remove const qualifier (clang).
C++
agpl-3.0
swansontec/libbitcoin,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,swansontec/libbitcoin,GroestlCoin/libgroestlcoin,GroestlCoin/libgroestlcoin
4c3be8a5957c8c9b2e12b46ab1829f6855852b7e
lib/sanitizer_common/sanitizer_symbolizer_mac.cc
lib/sanitizer_common/sanitizer_symbolizer_mac.cc
//===-- sanitizer_symbolizer_mac.cc ---------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between various sanitizers' runtime libraries. // // Implementation of Mac-specific "atos" symbolizer. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_allocator_internal.h" #include "sanitizer_mac.h" #include "sanitizer_symbolizer_mac.h" namespace __sanitizer { #include <dlfcn.h> #include <errno.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <util.h> bool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleSwiftAndCXX(info.dli_sname); if (!demangled) return false; stack->info.function = internal_strdup(demangled); return true; } bool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleSwiftAndCXX(info.dli_sname); datainfo->name = internal_strdup(demangled); datainfo->start = (uptr)info.dli_saddr; return true; } class AtosSymbolizerProcess : public SymbolizerProcess { public: explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid) : SymbolizerProcess(path, /*use_forkpty*/ true) { // Put the string command line argument in the object so that it outlives // the call to GetArgV. internal_snprintf(pid_str_, sizeof(pid_str_), "%d", parent_pid); } private: bool ReachedEndOfOutput(const char *buffer, uptr length) const override { return (length >= 1 && buffer[length - 1] == '\n'); } void GetArgV(const char *path_to_binary, const char *(&argv)[kArgVMax]) const override { int i = 0; argv[i++] = path_to_binary; argv[i++] = "-p"; argv[i++] = &pid_str_[0]; if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) { // On Mavericks atos prints a deprecation warning which we suppress by // passing -d. The warning isn't present on other OSX versions, even the // newer ones. argv[i++] = "-d"; } argv[i++] = nullptr; } char pid_str_[16]; }; static bool ParseCommandOutput(const char *str, uptr addr, char **out_name, char **out_module, char **out_file, uptr *line, uptr *start_address) { // Trim ending newlines. char *trim; ExtractTokenUpToDelimiter(str, "\n", &trim); // The line from `atos` is in one of these formats: // myfunction (in library.dylib) (sourcefile.c:17) // myfunction (in library.dylib) + 0x1fe // myfunction (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) + 0x1fe // 0xdeadbeef (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) // 0xdeadbeef const char *rest = trim; char *symbol_name; rest = ExtractTokenUpToDelimiter(rest, " (in ", &symbol_name); if (rest[0] == '\0') { InternalFree(symbol_name); InternalFree(trim); return false; } if (internal_strncmp(symbol_name, "0x", 2) != 0) *out_name = symbol_name; else InternalFree(symbol_name); rest = ExtractTokenUpToDelimiter(rest, ") ", out_module); if (rest[0] == '(') { if (out_file) { rest++; rest = ExtractTokenUpToDelimiter(rest, ":", out_file); char *extracted_line_number; rest = ExtractTokenUpToDelimiter(rest, ")", &extracted_line_number); if (line) *line = (uptr)internal_atoll(extracted_line_number); InternalFree(extracted_line_number); } } else if (rest[0] == '+') { rest += 2; uptr offset = internal_atoll(rest); if (start_address) *start_address = addr - offset; } InternalFree(trim); return true; } AtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator) : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {} bool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { if (!process_) return false; if (addr == 0) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; uptr line; if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module, &stack->info.file, &line, nullptr)) { process_ = nullptr; return false; } stack->info.line = (int)line; return true; } bool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) { if (!process_) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr, nullptr, &info->start)) { process_ = nullptr; return false; } return true; } } // namespace __sanitizer #endif // SANITIZER_MAC
//===-- sanitizer_symbolizer_mac.cc ---------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file is shared between various sanitizers' runtime libraries. // // Implementation of Mac-specific "atos" symbolizer. //===----------------------------------------------------------------------===// #include "sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_allocator_internal.h" #include "sanitizer_mac.h" #include "sanitizer_symbolizer_mac.h" #include <dlfcn.h> #include <errno.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <util.h> namespace __sanitizer { bool DlAddrSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleSwiftAndCXX(info.dli_sname); if (!demangled) return false; stack->info.function = internal_strdup(demangled); return true; } bool DlAddrSymbolizer::SymbolizeData(uptr addr, DataInfo *datainfo) { Dl_info info; int result = dladdr((const void *)addr, &info); if (!result) return false; const char *demangled = DemangleSwiftAndCXX(info.dli_sname); datainfo->name = internal_strdup(demangled); datainfo->start = (uptr)info.dli_saddr; return true; } class AtosSymbolizerProcess : public SymbolizerProcess { public: explicit AtosSymbolizerProcess(const char *path, pid_t parent_pid) : SymbolizerProcess(path, /*use_forkpty*/ true) { // Put the string command line argument in the object so that it outlives // the call to GetArgV. internal_snprintf(pid_str_, sizeof(pid_str_), "%d", parent_pid); } private: bool ReachedEndOfOutput(const char *buffer, uptr length) const override { return (length >= 1 && buffer[length - 1] == '\n'); } void GetArgV(const char *path_to_binary, const char *(&argv)[kArgVMax]) const override { int i = 0; argv[i++] = path_to_binary; argv[i++] = "-p"; argv[i++] = &pid_str_[0]; if (GetMacosVersion() == MACOS_VERSION_MAVERICKS) { // On Mavericks atos prints a deprecation warning which we suppress by // passing -d. The warning isn't present on other OSX versions, even the // newer ones. argv[i++] = "-d"; } argv[i++] = nullptr; } char pid_str_[16]; }; static bool ParseCommandOutput(const char *str, uptr addr, char **out_name, char **out_module, char **out_file, uptr *line, uptr *start_address) { // Trim ending newlines. char *trim; ExtractTokenUpToDelimiter(str, "\n", &trim); // The line from `atos` is in one of these formats: // myfunction (in library.dylib) (sourcefile.c:17) // myfunction (in library.dylib) + 0x1fe // myfunction (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) + 0x1fe // 0xdeadbeef (in library.dylib) + 15 // 0xdeadbeef (in library.dylib) // 0xdeadbeef const char *rest = trim; char *symbol_name; rest = ExtractTokenUpToDelimiter(rest, " (in ", &symbol_name); if (rest[0] == '\0') { InternalFree(symbol_name); InternalFree(trim); return false; } if (internal_strncmp(symbol_name, "0x", 2) != 0) *out_name = symbol_name; else InternalFree(symbol_name); rest = ExtractTokenUpToDelimiter(rest, ") ", out_module); if (rest[0] == '(') { if (out_file) { rest++; rest = ExtractTokenUpToDelimiter(rest, ":", out_file); char *extracted_line_number; rest = ExtractTokenUpToDelimiter(rest, ")", &extracted_line_number); if (line) *line = (uptr)internal_atoll(extracted_line_number); InternalFree(extracted_line_number); } } else if (rest[0] == '+') { rest += 2; uptr offset = internal_atoll(rest); if (start_address) *start_address = addr - offset; } InternalFree(trim); return true; } AtosSymbolizer::AtosSymbolizer(const char *path, LowLevelAllocator *allocator) : process_(new(*allocator) AtosSymbolizerProcess(path, getpid())) {} bool AtosSymbolizer::SymbolizePC(uptr addr, SymbolizedStack *stack) { if (!process_) return false; if (addr == 0) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; uptr line; if (!ParseCommandOutput(buf, addr, &stack->info.function, &stack->info.module, &stack->info.file, &line, nullptr)) { process_ = nullptr; return false; } stack->info.line = (int)line; return true; } bool AtosSymbolizer::SymbolizeData(uptr addr, DataInfo *info) { if (!process_) return false; char command[32]; internal_snprintf(command, sizeof(command), "0x%zx\n", addr); const char *buf = process_->SendCommand(command); if (!buf) return false; if (!ParseCommandOutput(buf, addr, &info->name, &info->module, nullptr, nullptr, &info->start)) { process_ = nullptr; return false; } return true; } } // namespace __sanitizer #endif // SANITIZER_MAC
Remove the system includes from __sanitizer namespace
[compiler-rt] Remove the system includes from __sanitizer namespace git-svn-id: c199f293c43da69278bea8e88f92242bf3aa95f7@281658 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt,llvm-mirror/compiler-rt
be97b099cbb5d8c74bd5068925753f715f1ec4f0
libspaghetti/source/elements/values/scale_int.cc
libspaghetti/source/elements/values/scale_int.cc
// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 <algorithm> #include "elements/values/scale_int.h" #include "spaghetti/logger.h" #include "spaghetti/utils.h" namespace spaghetti::elements::values { ScaleInt::ScaleInt() { setMinInputs(1); setMaxInputs(1); setMinOutputs(1); setMaxOutputs(1); addInput(ValueType::eInt, "Value", IOSocket::eCanHoldInt | IOSocket::eCanChangeName); addOutput(ValueType::eInt, "Scaled", IOSocket::eCanHoldInt | IOSocket::eCanChangeName); } void ScaleInt::serialize(Json &a_json) { Element::serialize(a_json); auto &properties = a_json["properties"]; properties["x_min"] = m_xMin; properties["x_max"] = m_xMax; properties["y_min"] = m_yMin; properties["y_max"] = m_yMax; } void ScaleInt::deserialize(const Json &a_json) { Element::deserialize(a_json); auto const &PROPERTIES = a_json["properties"]; m_xMin = PROPERTIES["x_min"].get<int32_t>(); m_xMax = PROPERTIES["x_max"].get<int32_t>(); m_yMin = PROPERTIES["y_min"].get<int32_t>(); m_yMax = PROPERTIES["y_max"].get<int32_t>(); } void ScaleInt::calculate() { int32_t const INPUT_VALUE{ std::get<int32_t>(m_inputs[0].value) }; int32_t const VALUE{ std::clamp(INPUT_VALUE, m_xMin, m_xMax) }; if (VALUE == m_lastValue) return; log::info(" input value: {}", INPUT_VALUE); log::info(" last value: {}", m_lastValue); log::info(" value: {}", VALUE); m_lastValue = VALUE; vec2 *previousPtr{ &m_series[0] }; vec2 *currentPtr{}; size_t const SIZE = m_series.size(); log::info(" series count: {}", SIZE); for (size_t i = 0; i < SIZE; ++i) { currentPtr = &m_series[i]; if (currentPtr->x < VALUE) previousPtr = currentPtr; else break; } assert(previousPtr); assert(currentPtr); vec2 const PREVIOUS{ *previousPtr }; vec2 const CURRENT{ *currentPtr }; log::info(" previous: {}, {}", PREVIOUS.x, PREVIOUS.y); log::info(" current: {}, {}", CURRENT.x, CURRENT.y); float value{}; float percent{}; if (VALUE == PREVIOUS.x) value = static_cast<float>(PREVIOUS.y); else if (VALUE == CURRENT.x) value = static_cast<float>(CURRENT.y); else { percent = static_cast<float>(VALUE - PREVIOUS.x) / static_cast<float>(CURRENT.x - PREVIOUS.x); value = lerp(static_cast<float>(PREVIOUS.y), static_cast<float>(CURRENT.y), percent); } log::info(" value: {}, percent: {}", value, percent); m_outputs[0].value = static_cast<int32_t>(value); } void ScaleInt::setSeriesCount(size_t const a_seriesCount) { if (a_seriesCount < 2) return; m_series.resize(a_seriesCount); } } // namespace spaghetti::elements::values
// MIT License // // Copyright (c) 2017-2018 Artur Wyszyński, aljen at hitomi dot pl // // 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 <algorithm> #include "elements/values/scale_int.h" #include "spaghetti/logger.h" #include "spaghetti/utils.h" namespace spaghetti::elements::values { ScaleInt::ScaleInt() { setMinInputs(1); setMaxInputs(1); setMinOutputs(1); setMaxOutputs(1); addInput(ValueType::eInt, "Value", IOSocket::eCanHoldInt | IOSocket::eCanChangeName); addOutput(ValueType::eInt, "Scaled", IOSocket::eCanHoldInt | IOSocket::eCanChangeName); setIconifyingHidesCentralWidget(true); } void ScaleInt::serialize(Json &a_json) { Element::serialize(a_json); auto &properties = a_json["properties"]; properties["x_min"] = m_xMin; properties["x_max"] = m_xMax; properties["y_min"] = m_yMin; properties["y_max"] = m_yMax; } void ScaleInt::deserialize(const Json &a_json) { Element::deserialize(a_json); auto const &PROPERTIES = a_json["properties"]; m_xMin = PROPERTIES["x_min"].get<int32_t>(); m_xMax = PROPERTIES["x_max"].get<int32_t>(); m_yMin = PROPERTIES["y_min"].get<int32_t>(); m_yMax = PROPERTIES["y_max"].get<int32_t>(); } void ScaleInt::calculate() { int32_t const INPUT_VALUE{ std::get<int32_t>(m_inputs[0].value) }; int32_t const VALUE{ std::clamp(INPUT_VALUE, m_xMin, m_xMax) }; if (VALUE == m_lastValue) return; log::info(" input value: {}", INPUT_VALUE); log::info(" last value: {}", m_lastValue); log::info(" value: {}", VALUE); m_lastValue = VALUE; vec2 *previousPtr{ &m_series[0] }; vec2 *currentPtr{}; size_t const SIZE = m_series.size(); log::info(" series count: {}", SIZE); for (size_t i = 0; i < SIZE; ++i) { currentPtr = &m_series[i]; if (currentPtr->x < VALUE) previousPtr = currentPtr; else break; } assert(previousPtr); assert(currentPtr); vec2 const PREVIOUS{ *previousPtr }; vec2 const CURRENT{ *currentPtr }; log::info(" previous: {}, {}", PREVIOUS.x, PREVIOUS.y); log::info(" current: {}, {}", CURRENT.x, CURRENT.y); float value{}; float percent{}; if (VALUE == PREVIOUS.x) value = static_cast<float>(PREVIOUS.y); else if (VALUE == CURRENT.x) value = static_cast<float>(CURRENT.y); else { percent = static_cast<float>(VALUE - PREVIOUS.x) / static_cast<float>(CURRENT.x - PREVIOUS.x); value = lerp(static_cast<float>(PREVIOUS.y), static_cast<float>(CURRENT.y), percent); } log::info(" value: {}, percent: {}", value, percent); m_outputs[0].value = static_cast<int32_t>(value); } void ScaleInt::setSeriesCount(size_t const a_seriesCount) { if (a_seriesCount < 2) return; m_series.resize(a_seriesCount); } } // namespace spaghetti::elements::values
Hide central widget for ScaleInt
Hide central widget for ScaleInt
C++
mit
aljen/spaghetti,aljen/spaghetti
fbb950137e90d179f2e9ba5b224fb292d4743573
source/signals/ThisThread-Signals.cpp
source/signals/ThisThread-Signals.cpp
/** * \file * \brief ThisThread::Signals namespace implementation * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-21 */ #include "distortos/ThisThread-Signals.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" namespace distortos { namespace ThisThread { namespace Signals { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// SignalsWaitUnblockFunctor is a functor executed when unblocking a thread that is waiting for signal class SignalsWaitUnblockFunctor : public scheduler::ThreadControlBlock::UnblockFunctor { public: /** * \brief SignalsWaitUnblockFunctor's constructor * * \param [in] pendingSignalSet is a reference to SignalSet that will be used to return saved pending signal set */ constexpr explicit SignalsWaitUnblockFunctor(SignalSet& pendingSignalSet) : pendingSignalSet_(pendingSignalSet) { } /** * \brief SignalsWaitUnblockFunctor's function call operator * * Saves pending signal set of unblocked thread and clears pointer to set of signals that were "waited for". * * \param [in] threadControlBlock is a reference to ThreadControlBlock that is being unblocked */ void operator()(scheduler::ThreadControlBlock& threadControlBlock) const override { pendingSignalSet_ = threadControlBlock.getPendingSignalSet(); threadControlBlock.setWaitingSignalSet(nullptr); } private: /// reference to SignalSet that will be used to return saved pending signal set SignalSet& pendingSignalSet_; }; } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ std::pair<int, uint8_t> wait(const SignalSet& signalSet) { architecture::InterruptMaskingLock interruptMaskingLock; auto& scheduler = scheduler::getScheduler(); auto& currentThreadControlBlock = scheduler.getCurrentThreadControlBlock(); const auto bitset = signalSet.getBitset(); auto pendingSignalSet = currentThreadControlBlock.getPendingSignalSet(); auto pendingBitset = pendingSignalSet.getBitset(); auto intersection = bitset & pendingBitset; if (intersection.none() == true) // none of desired signals is pending, so current thread must be blocked { scheduler::ThreadControlBlockList waitingList {scheduler.getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::WaitingForSignal}; currentThreadControlBlock.setWaitingSignalSet(&signalSet); const SignalsWaitUnblockFunctor signalsWaitUnblockFunctor {pendingSignalSet}; const auto ret = scheduler.block(waitingList, &signalsWaitUnblockFunctor); if (ret != 0) return {ret, {}}; pendingBitset = pendingSignalSet.getBitset(); intersection = bitset & pendingBitset; } const auto intersectionValue = intersection.to_ulong(); // GCC builtin - "find first set" - https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html const auto signalNumber = __builtin_ffsl(intersectionValue) - 1; const auto ret = currentThreadControlBlock.acceptPendingSignal(signalNumber); return {ret, signalNumber}; } } // namespace Signals } // namespace ThisThread } // namespace distortos
/** * \file * \brief ThisThread::Signals namespace implementation * * \author Copyright (C) 2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-02-21 */ #include "distortos/ThisThread-Signals.hpp" #include "distortos/scheduler/getScheduler.hpp" #include "distortos/scheduler/Scheduler.hpp" #include "distortos/architecture/InterruptMaskingLock.hpp" namespace distortos { namespace ThisThread { namespace Signals { namespace { /*---------------------------------------------------------------------------------------------------------------------+ | local types +---------------------------------------------------------------------------------------------------------------------*/ /// SignalsWaitUnblockFunctor is a functor executed when unblocking a thread that is waiting for signal class SignalsWaitUnblockFunctor : public scheduler::ThreadControlBlock::UnblockFunctor { public: /** * \brief SignalsWaitUnblockFunctor's constructor * * \param [in] pendingSignalSet is a reference to SignalSet that will be used to return saved pending signal set */ constexpr explicit SignalsWaitUnblockFunctor(SignalSet& pendingSignalSet) : pendingSignalSet_(pendingSignalSet) { } /** * \brief SignalsWaitUnblockFunctor's function call operator * * Saves pending signal set of unblocked thread and clears pointer to set of signals that were "waited for". * * \param [in] threadControlBlock is a reference to ThreadControlBlock that is being unblocked */ void operator()(scheduler::ThreadControlBlock& threadControlBlock) const override { pendingSignalSet_ = threadControlBlock.getPendingSignalSet(); threadControlBlock.setWaitingSignalSet(nullptr); } private: /// reference to SignalSet that will be used to return saved pending signal set SignalSet& pendingSignalSet_; }; /*---------------------------------------------------------------------------------------------------------------------+ | local functions +---------------------------------------------------------------------------------------------------------------------*/ /** * \brief Implementation of distortos::ThisThread::Signals::wait(). * * \param [in] signalSet is a reference to set of signals that will be waited for * * \return pair with return code (0 on success, error code otherwise) and signal number of signal that was accepted */ std::pair<int, uint8_t> waitImplementation(const SignalSet& signalSet) { architecture::InterruptMaskingLock interruptMaskingLock; auto& scheduler = scheduler::getScheduler(); auto& currentThreadControlBlock = scheduler.getCurrentThreadControlBlock(); const auto bitset = signalSet.getBitset(); auto pendingSignalSet = currentThreadControlBlock.getPendingSignalSet(); auto pendingBitset = pendingSignalSet.getBitset(); auto intersection = bitset & pendingBitset; if (intersection.none() == true) // none of desired signals is pending, so current thread must be blocked { scheduler::ThreadControlBlockList waitingList {scheduler.getThreadControlBlockListAllocator(), scheduler::ThreadControlBlock::State::WaitingForSignal}; currentThreadControlBlock.setWaitingSignalSet(&signalSet); const SignalsWaitUnblockFunctor signalsWaitUnblockFunctor {pendingSignalSet}; const auto ret = scheduler.block(waitingList, &signalsWaitUnblockFunctor); if (ret != 0) return {ret, {}}; pendingBitset = pendingSignalSet.getBitset(); intersection = bitset & pendingBitset; } const auto intersectionValue = intersection.to_ulong(); // GCC builtin - "find first set" - https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html const auto signalNumber = __builtin_ffsl(intersectionValue) - 1; const auto ret = currentThreadControlBlock.acceptPendingSignal(signalNumber); return {ret, signalNumber}; } } // namespace /*---------------------------------------------------------------------------------------------------------------------+ | global functions +---------------------------------------------------------------------------------------------------------------------*/ std::pair<int, uint8_t> wait(const SignalSet& signalSet) { return waitImplementation(signalSet); } } // namespace Signals } // namespace ThisThread } // namespace distortos
move implementation to local waitImplementation()
ThisThread::Signals::wait(): move implementation to local waitImplementation()
C++
mpl-2.0
jasmin-j/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,jasmin-j/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,DISTORTEC/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,CezaryGapinski/distortos
5ab04e1391665651572dd68ab9adc5b9b8f00086
linbox-old/tests/Gauss/rank_sparse_reord_gauss.C
linbox-old/tests/Gauss/rank_sparse_reord_gauss.C
// ======================================================================= // // Givaro / Athapascan-1 // Algorithme de Coppersmith : n=m=1 --> Wiedemann ameliore, Creux // With diagonal Scaling and Transpose Computation // Multiply computations are stopped when the polynomials remains the same // for more than DIFF_BOUND // Time-stamp: <08 Mar 00 16:21:40 [email protected]> // ======================================================================= // #include <stdio.h> #include <stdlib.h> #include <iostream.h> // --------------------------------------------- #include <givinit.h> #include "givgfq.h" #include "lin_spv_bb.h" // BB Wrapper for sparse vectors #include "lin_density.h" #include "lin_dom_gauss.C" // --------------------------------------------- // MAIN int main(int argc, char* argv[]) { Givaro::Init(&argc, &argv); Timer init; init.clear();init.start(); typedef GFqDom<long> GFqDomain; typedef GFqDomain::Residu_t Residu; // Must have a matrix name char* Matrix_File_Name = argv[1]; Residu MOD=65521,expo=1,cardinal; short transp = -1; if (argc > 2) MOD = atoi( argv[2] ); if (argc > 3) expo = atoi( argv[3] ); if (argc > 4) transp = atoi( argv[4] ); // Premire tape : le corps de base GFqDomain F(MOD,expo); cardinal = F.size(); GaussDom< GFqDomain > GF( F, Commentator(PRINT_EVERYTHING,PRINT_EVERYTHING) ); typedef SparseBlackBoxDom< GFqDomain > SPBB ; SPBB TheMat(F); unsigned long ni, nj; TheMat.read(ni,nj,Matrix_File_Name); if (transp < 0) if (ni > nj) TheMat.read_transpose(Matrix_File_Name); else TheMat.read(Matrix_File_Name); else if (transp == 1) TheMat.read_transpose(Matrix_File_Name); else TheMat.read(Matrix_File_Name); unsigned long rank; init.stop(); cerr << "Init, " << TheMat.n_elem() << " elts : " << init.usertime() << " (" << init.realtime() << ")" << endl; { GF.gauss_rankin(rank,TheMat,Density()); } Givaro::End(); return 0; };
// ======================================================================= // // Givaro / Athapascan-1 // Algorithme de Coppersmith : n=m=1 --> Wiedemann ameliore, Creux // With diagonal Scaling and Transpose Computation // Multiply computations are stopped when the polynomials remains the same // for more than DIFF_BOUND // Time-stamp: <08 Mar 00 16:21:40 [email protected]> // ======================================================================= // #define _REENTRANT #include <stdio.h> #include <stdlib.h> #include <iostream.h> // --------------------------------------------- #include "LinBox/integer.h" using namespace LinBox; #include "LinBox/field_archetype.h" #include "LinBox/gmp-rational-field.C" #include "LinBox/gmp-rational-random.h" #include "lin_spv_bb.h" // BB Wrapper for sparse vectors #include "lin_density.h" #include "lin_dom_gauss.C" // --------------------------------------------- // MAIN int main(int argc, char* argv[]) { Timer init; init.clear();init.start(); // Must have a matrix name char* Matrix_File_Name = argv[1]; short transp = -1; if (argc > 4) transp = atoi( argv[4] ); // Premire tape : le corps de base typedef GMP_Rational_Field MyField; MyField F; #ifdef __ARCH__ Field_archetype Af( & F ); // works also ... // Field_archetype Af( new Field_envelope<MyField>(F) ); GaussDom< Field_archetype > elimination_routines_with_field_stored( Af, Commentator(PRINT_EVERYTHING,PRINT_EVERYTHING) ); SparseBlackBoxDom< Field_archetype > TheMat( Af ); #else GaussDom< MyField > elimination_routines_with_field_stored( F, Commentator(PRINT_EVERYTHING,PRINT_EVERYTHING) ); SparseBlackBoxDom< MyField > TheMat(F); #endif unsigned long ni, nj; TheMat.read(ni,nj,Matrix_File_Name); if (transp < 0) if (ni > nj) TheMat.read_transpose(Matrix_File_Name); else TheMat.read(Matrix_File_Name); else if (transp == 1) TheMat.read_transpose(Matrix_File_Name); else TheMat.read(Matrix_File_Name); unsigned long rank; init.stop(); cerr << "Init, " << TheMat.n_elem() << " elts : " << init.usertime() << " (" << init.realtime() << ")" << endl; { elimination_routines_with_field_stored.gauss_rankin(rank,TheMat,Density()); } return 0; };
Use now gmp-rational field
Use now gmp-rational field
C++
lgpl-2.1
linbox-team/linbox,linbox-team/linbox,linbox-team/linbox,linbox-team/linbox,linbox-team/linbox
5c1912351000431f4a59bfcc836ed0b4c3bf9114
common/system/routine_tracer_funcstats.cc
common/system/routine_tracer_funcstats.cc
#include "routine_tracer_funcstats.h" #include "simulator.h" #include "core_manager.h" #include "thread.h" #include "core.h" #include "performance_model.h" #include "log.h" #include "stats.h" #include "cache_efficiency_tracker.h" #include "utils.h" #include <sstream> RoutineTracerFunctionStats::RtnThread::RtnThread(RoutineTracerFunctionStats::RtnMaster *master, Thread *thread) : RoutineTracerThread(thread) , m_master(master) , m_current_eip(0) { } void RoutineTracerFunctionStats::RtnThread::functionEnter(IntPtr eip) { functionBegin(eip); } void RoutineTracerFunctionStats::RtnThread::functionExit(IntPtr eip) { functionEnd(eip, true); } void RoutineTracerFunctionStats::RtnThread::functionChildEnter(IntPtr eip, IntPtr eip_child) { functionEnd(eip, false); } void RoutineTracerFunctionStats::RtnThread::functionChildExit(IntPtr eip, IntPtr eip_child) { functionBegin(eip); } void RoutineTracerFunctionStats::RtnThread::functionBeginHelper(IntPtr eip, RtnValues& values_start) { m_current_eip = eip; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) { values_start[*it] = getThreadStat(*it); } } void RoutineTracerFunctionStats::RtnThread::functionEndHelper(IntPtr eip, UInt64 count) { RtnValues values; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) { values[*it] = getThreadStat(*it) - m_values_start[*it]; } m_master->updateRoutine(eip, count, values); } void RoutineTracerFunctionStats::RtnThread::functionEndFullHelper(const std::deque<IntPtr> &stack, UInt64 count) { RtnValues values; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(auto it = types.begin(); it != types.end(); ++it) { values[*it] = getThreadStat(*it) - m_values_start_full[stack][*it]; } m_master->updateRoutineFull(stack, count, values); } void RoutineTracerFunctionStats::RtnThread::functionBegin(IntPtr eip) { Sim()->getThreadStatsManager()->update(m_thread->getId()); functionBeginHelper(eip, m_values_start); functionBeginHelper(eip, m_values_start_full[m_stack]); } void RoutineTracerFunctionStats::RtnThread::functionEnd(IntPtr eip, bool is_function_start) { Sim()->getThreadStatsManager()->update(m_thread->getId()); functionEndHelper(eip, is_function_start ? 1 : 0); functionEndFullHelper(m_stack, is_function_start ? 1 : 0); } UInt64 RoutineTracerFunctionStats::RtnThread::getThreadStat(ThreadStatsManager::ThreadStatType type) { return Sim()->getThreadStatsManager()->getThreadStatistic(m_thread->getId(), type); } UInt64 RoutineTracerFunctionStats::RtnThread::getCurrentRoutineId() { return m_current_eip; } RoutineTracerFunctionStats::RtnMaster::RtnMaster() { ThreadStatNamedStat::registerStat("fp_addsub", "interval_timer", "uop_fp_addsub"); ThreadStatNamedStat::registerStat("fp_muldiv", "interval_timer", "uop_fp_muldiv"); ThreadStatNamedStat::registerStat("l3miss", "L3", "load-misses"); ThreadStatAggregates::registerStats(); ThreadStatNamedStat::registerStat("cpiBase", "interval_timer", "cpiBase"); ThreadStatNamedStat::registerStat("cpiBranchPredictor", "interval_timer", "cpiBranchPredictor"); ThreadStatCpiMem::registerStat(); Sim()->getConfig()->setCacheEfficiencyCallbacks(__ce_get_owner, __ce_notify, (UInt64)this); } RoutineTracerFunctionStats::RtnMaster::~RtnMaster() { writeResults(Sim()->getConfig()->formatOutputFileName("sim.rtntrace").c_str()); writeResultsFull(Sim()->getConfig()->formatOutputFileName("sim.rtntracefull").c_str()); } UInt64 RoutineTracerFunctionStats::RtnMaster::ce_get_owner(core_id_t core_id) { Thread *thread = Sim()->getCoreManager()->getCoreFromID(core_id)->getThread(); if (thread && m_threads.count(thread->getId())) return m_threads[thread->getId()]->getCurrentRoutineId(); else return 0; } void RoutineTracerFunctionStats::RtnMaster::ce_notify(bool on_roi_end, UInt64 owner, CacheBlockInfo::BitsUsedType bits_used, UInt32 bits_total) { ScopedLock sl(m_lock); IntPtr eip = owner; if (m_routines.count(eip)) { m_routines[eip]->m_bits_used += countBits(bits_used); m_routines[eip]->m_bits_total += bits_total; } } RoutineTracerThread* RoutineTracerFunctionStats::RtnMaster::getThreadHandler(Thread *thread) { RtnThread* thread_handler = new RtnThread(this, thread); m_threads[thread->getId()] = thread_handler; return thread_handler; } void RoutineTracerFunctionStats::RtnMaster::addRoutine(IntPtr eip, const char *name, const char *imgname, int column, int line, const char *filename) { ScopedLock sl(m_lock); if (m_routines.count(eip) == 0) { m_routines[eip] = new RoutineTracerFunctionStats::Routine(eip, name, imgname, column, line, filename); } } bool RoutineTracerFunctionStats::RtnMaster::hasRoutine(IntPtr eip) { ScopedLock sl(m_lock); return m_routines.count(eip) > 0; } void RoutineTracerFunctionStats::RtnMaster::updateRoutine(IntPtr eip, UInt64 calls, RtnValues values) { ScopedLock sl(m_lock); LOG_ASSERT_ERROR(m_routines.count(eip), "Routine %lx not found", eip); m_routines[eip]->m_calls += calls; for(RtnValues::iterator it = values.begin(); it != values.end(); ++it) { m_routines[eip]->m_values[it->first] += it->second; } } void RoutineTracerFunctionStats::RtnMaster::updateRoutineFull(const std::deque<UInt64>& stack, UInt64 calls, RtnValues values) { ScopedLock sl(m_lock); LOG_ASSERT_ERROR(m_routines.count(stack.back()), "Routine %lx not found", stack.back()); if (m_callstack_routines.count(stack) == 0) { m_callstack_routines[stack] = new RoutineTracerFunctionStats::Routine(*m_routines[stack.back()]); } m_callstack_routines[stack]->m_calls += calls; for(auto it = values.begin(); it != values.end(); ++it) { m_callstack_routines[stack]->m_values[it->first] += it->second; } } void RoutineTracerFunctionStats::RtnMaster::writeResults(const char *filename) { FILE *fp = fopen(filename, "w"); const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); fprintf(fp, "eip\tname\tsource\tcalls\tbits_used\tbits_total"); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) fprintf(fp, "\t%s", Sim()->getThreadStatsManager()->getThreadStatName(*it)); fprintf(fp, "\n"); for(RoutineMap::iterator it = m_routines.begin(); it != m_routines.end(); ++it) { fprintf(fp, "%" PRIxPTR "\t%s\t%s\t%" PRId64 "\t%" PRId64 "\t%" PRId64, it->second->m_eip, it->second->m_name, it->second->m_location, it->second->m_calls, it->second->m_bits_used, it->second->m_bits_total); for(ThreadStatsManager::ThreadStatTypeList::const_iterator jt = types.begin(); jt != types.end(); ++jt) fprintf(fp, "\t%" PRId64, it->second->m_values[*jt]); fprintf(fp, "\n"); } fclose(fp); } void RoutineTracerFunctionStats::RtnMaster::writeResultsFull(const char *filename) { FILE *fp = fopen(filename, "w"); const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); fprintf(fp, "eip\tname\tsource\tcalls\tbits_used\tbits_total"); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) fprintf(fp, "\t%s", Sim()->getThreadStatsManager()->getThreadStatName(*it)); fprintf(fp, "\n"); for(auto it = m_callstack_routines.begin(); it != m_callstack_routines.end(); ++it) { std::ostringstream s; s << it->first.front(); for (auto kt = ++it->first.begin(); kt != it->first.end(); ++kt) { s << ":" << std::hex << *kt << std::dec; } fprintf(fp, "%s\t%s\t%s\t%" PRId64 "\t%" PRId64 "\t%" PRId64, s.str().c_str(), it->second->m_name, it->second->m_location, it->second->m_calls, it->second->m_bits_used, it->second->m_bits_total); for(ThreadStatsManager::ThreadStatTypeList::const_iterator jt = types.begin(); jt != types.end(); ++jt) fprintf(fp, "\t%" PRId64, it->second->m_values[*jt]); fprintf(fp, "\n"); } fclose(fp); } // Helper class to provide global icount/time statistics class ThreadStatAggregates { public: static void registerStats(); private: static UInt64 callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user); }; void RoutineTracerFunctionStats::ThreadStatAggregates::registerStats() { Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "global_instructions", callback, (UInt64)GLOBAL_INSTRUCTIONS); Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "global_nonidle_elapsed_time", callback, (UInt64)GLOBAL_NONIDLE_ELAPSED_TIME); } UInt64 RoutineTracerFunctionStats::ThreadStatAggregates::callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user) { UInt64 result = 0; switch(user) { case GLOBAL_INSTRUCTIONS: for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) result += Sim()->getCoreManager()->getCoreFromID(core_id)->getPerformanceModel()->getInstructionCount(); return result; case GLOBAL_NONIDLE_ELAPSED_TIME: for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) result += Sim()->getCoreManager()->getCoreFromID(core_id)->getPerformanceModel()->getNonIdleElapsedTime().getFS(); return result; default: LOG_PRINT_ERROR("Unexpected user value %d", user); } } // Helper class to provide simplified cpiMem component ThreadStatsManager::ThreadStatType RoutineTracerFunctionStats::ThreadStatCpiMem::registerStat() { ThreadStatCpiMem *tsns = new ThreadStatCpiMem(); return Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "cpiMem", callback, (UInt64)tsns); } RoutineTracerFunctionStats::ThreadStatCpiMem::ThreadStatCpiMem() : m_stats(Sim()->getConfig()->getApplicationCores()) { for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) { for (int h = HitWhere::WHERE_FIRST ; h < HitWhere::NUM_HITWHERES ; h++) { String metricName = "cpiDataCache" + String(HitWhereString((HitWhere::where_t)h)); StatsMetricBase *m = Sim()->getStatsManager()->getMetricObject("interval_timer", core_id, metricName); LOG_ASSERT_ERROR(m != NULL, "Invalid statistic %s.%d.%s", "interval_timer", core_id, metricName.c_str()); m_stats[core_id].push_back(m); } } } UInt64 RoutineTracerFunctionStats::ThreadStatCpiMem::callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user) { ThreadStatCpiMem* tsns = (ThreadStatCpiMem*)user; std::vector<StatsMetricBase*>& stats = tsns->m_stats[core->getId()]; UInt64 result = 0; for(std::vector<StatsMetricBase*>::iterator it = stats.begin(); it != stats.end(); ++it) result += (*it)->recordMetric(); return result; }
#include "routine_tracer_funcstats.h" #include "simulator.h" #include "core_manager.h" #include "thread.h" #include "core.h" #include "performance_model.h" #include "log.h" #include "stats.h" #include "cache_efficiency_tracker.h" #include "utils.h" #include <sstream> RoutineTracerFunctionStats::RtnThread::RtnThread(RoutineTracerFunctionStats::RtnMaster *master, Thread *thread) : RoutineTracerThread(thread) , m_master(master) , m_current_eip(0) { } void RoutineTracerFunctionStats::RtnThread::functionEnter(IntPtr eip) { functionBegin(eip); } void RoutineTracerFunctionStats::RtnThread::functionExit(IntPtr eip) { functionEnd(eip, true); } void RoutineTracerFunctionStats::RtnThread::functionChildEnter(IntPtr eip, IntPtr eip_child) { functionEnd(eip, false); } void RoutineTracerFunctionStats::RtnThread::functionChildExit(IntPtr eip, IntPtr eip_child) { functionBegin(eip); } void RoutineTracerFunctionStats::RtnThread::functionBeginHelper(IntPtr eip, RtnValues& values_start) { m_current_eip = eip; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) { values_start[*it] = getThreadStat(*it); } } void RoutineTracerFunctionStats::RtnThread::functionEndHelper(IntPtr eip, UInt64 count) { RtnValues values; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) { values[*it] = getThreadStat(*it) - m_values_start[*it]; } m_master->updateRoutine(eip, count, values); } void RoutineTracerFunctionStats::RtnThread::functionEndFullHelper(const std::deque<IntPtr> &stack, UInt64 count) { RtnValues values; const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); for(auto it = types.begin(); it != types.end(); ++it) { values[*it] = getThreadStat(*it) - m_values_start_full[stack][*it]; } m_master->updateRoutineFull(stack, count, values); } void RoutineTracerFunctionStats::RtnThread::functionBegin(IntPtr eip) { Sim()->getThreadStatsManager()->update(m_thread->getId()); functionBeginHelper(eip, m_values_start); functionBeginHelper(eip, m_values_start_full[m_stack]); } void RoutineTracerFunctionStats::RtnThread::functionEnd(IntPtr eip, bool is_function_start) { Sim()->getThreadStatsManager()->update(m_thread->getId()); functionEndHelper(eip, is_function_start ? 1 : 0); functionEndFullHelper(m_stack, is_function_start ? 1 : 0); } UInt64 RoutineTracerFunctionStats::RtnThread::getThreadStat(ThreadStatsManager::ThreadStatType type) { return Sim()->getThreadStatsManager()->getThreadStatistic(m_thread->getId(), type); } UInt64 RoutineTracerFunctionStats::RtnThread::getCurrentRoutineId() { return m_current_eip; } RoutineTracerFunctionStats::RtnMaster::RtnMaster() { ThreadStatNamedStat::registerStat("fp_addsub", "interval_timer", "uop_fp_addsub"); ThreadStatNamedStat::registerStat("fp_muldiv", "interval_timer", "uop_fp_muldiv"); ThreadStatNamedStat::registerStat("l3miss", "L3", "load-misses"); ThreadStatAggregates::registerStats(); ThreadStatNamedStat::registerStat("cpiBase", "interval_timer", "cpiBase"); ThreadStatNamedStat::registerStat("cpiBranchPredictor", "interval_timer", "cpiBranchPredictor"); ThreadStatCpiMem::registerStat(); Sim()->getConfig()->setCacheEfficiencyCallbacks(__ce_get_owner, __ce_notify, (UInt64)this); } RoutineTracerFunctionStats::RtnMaster::~RtnMaster() { writeResults(Sim()->getConfig()->formatOutputFileName("sim.rtntrace").c_str()); writeResultsFull(Sim()->getConfig()->formatOutputFileName("sim.rtntracefull").c_str()); } UInt64 RoutineTracerFunctionStats::RtnMaster::ce_get_owner(core_id_t core_id) { Thread *thread = Sim()->getCoreManager()->getCoreFromID(core_id)->getThread(); if (thread && m_threads.count(thread->getId())) return m_threads[thread->getId()]->getCurrentRoutineId(); else return 0; } void RoutineTracerFunctionStats::RtnMaster::ce_notify(bool on_roi_end, UInt64 owner, CacheBlockInfo::BitsUsedType bits_used, UInt32 bits_total) { ScopedLock sl(m_lock); IntPtr eip = owner; if (m_routines.count(eip)) { m_routines[eip]->m_bits_used += countBits(bits_used); m_routines[eip]->m_bits_total += bits_total; } } RoutineTracerThread* RoutineTracerFunctionStats::RtnMaster::getThreadHandler(Thread *thread) { RtnThread* thread_handler = new RtnThread(this, thread); m_threads[thread->getId()] = thread_handler; return thread_handler; } void RoutineTracerFunctionStats::RtnMaster::addRoutine(IntPtr eip, const char *name, const char *imgname, int column, int line, const char *filename) { ScopedLock sl(m_lock); if (m_routines.count(eip) == 0) { m_routines[eip] = new RoutineTracerFunctionStats::Routine(eip, name, imgname, column, line, filename); } } bool RoutineTracerFunctionStats::RtnMaster::hasRoutine(IntPtr eip) { ScopedLock sl(m_lock); return m_routines.count(eip) > 0; } void RoutineTracerFunctionStats::RtnMaster::updateRoutine(IntPtr eip, UInt64 calls, RtnValues values) { ScopedLock sl(m_lock); LOG_ASSERT_ERROR(m_routines.count(eip), "Routine %lx not found", eip); m_routines[eip]->m_calls += calls; for(RtnValues::iterator it = values.begin(); it != values.end(); ++it) { m_routines[eip]->m_values[it->first] += it->second; } } void RoutineTracerFunctionStats::RtnMaster::updateRoutineFull(const std::deque<UInt64>& stack, UInt64 calls, RtnValues values) { ScopedLock sl(m_lock); LOG_ASSERT_ERROR(m_routines.count(stack.back()), "Routine %lx not found", stack.back()); if (m_callstack_routines.count(stack) == 0) { m_callstack_routines[stack] = new RoutineTracerFunctionStats::Routine(*m_routines[stack.back()]); } m_callstack_routines[stack]->m_calls += calls; for(auto it = values.begin(); it != values.end(); ++it) { m_callstack_routines[stack]->m_values[it->first] += it->second; } } void RoutineTracerFunctionStats::RtnMaster::writeResults(const char *filename) { FILE *fp = fopen(filename, "w"); const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); fprintf(fp, "eip\tname\tsource\tcalls\tbits_used\tbits_total"); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) fprintf(fp, "\t%s", Sim()->getThreadStatsManager()->getThreadStatName(*it)); fprintf(fp, "\n"); for(RoutineMap::iterator it = m_routines.begin(); it != m_routines.end(); ++it) { fprintf(fp, "%" PRIxPTR "\t%s\t%s\t%" PRId64 "\t%" PRId64 "\t%" PRId64, it->second->m_eip, it->second->m_name, it->second->m_location, it->second->m_calls, it->second->m_bits_used, it->second->m_bits_total); for(ThreadStatsManager::ThreadStatTypeList::const_iterator jt = types.begin(); jt != types.end(); ++jt) fprintf(fp, "\t%" PRId64, it->second->m_values[*jt]); fprintf(fp, "\n"); } fclose(fp); } void RoutineTracerFunctionStats::RtnMaster::writeResultsFull(const char *filename) { FILE *fp = fopen(filename, "w"); const ThreadStatsManager::ThreadStatTypeList& types = Sim()->getThreadStatsManager()->getThreadStatTypes(); fprintf(fp, "eip\tname\tsource\tcalls\tbits_used\tbits_total"); for(ThreadStatsManager::ThreadStatTypeList::const_iterator it = types.begin(); it != types.end(); ++it) fprintf(fp, "\t%s", Sim()->getThreadStatsManager()->getThreadStatName(*it)); fprintf(fp, "\n"); for(auto it = m_callstack_routines.begin(); it != m_callstack_routines.end(); ++it) { std::ostringstream s; s << std::hex << it->first.front(); for (auto kt = ++it->first.begin(); kt != it->first.end(); ++kt) { s << ":" << std::hex << *kt << std::dec; } fprintf(fp, "%s\t%s\t%s\t%" PRId64 "\t%" PRId64 "\t%" PRId64, s.str().c_str(), it->second->m_name, it->second->m_location, it->second->m_calls, it->second->m_bits_used, it->second->m_bits_total); for(ThreadStatsManager::ThreadStatTypeList::const_iterator jt = types.begin(); jt != types.end(); ++jt) fprintf(fp, "\t%" PRId64, it->second->m_values[*jt]); fprintf(fp, "\n"); } fclose(fp); } // Helper class to provide global icount/time statistics class ThreadStatAggregates { public: static void registerStats(); private: static UInt64 callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user); }; void RoutineTracerFunctionStats::ThreadStatAggregates::registerStats() { Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "global_instructions", callback, (UInt64)GLOBAL_INSTRUCTIONS); Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "global_nonidle_elapsed_time", callback, (UInt64)GLOBAL_NONIDLE_ELAPSED_TIME); } UInt64 RoutineTracerFunctionStats::ThreadStatAggregates::callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user) { UInt64 result = 0; switch(user) { case GLOBAL_INSTRUCTIONS: for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) result += Sim()->getCoreManager()->getCoreFromID(core_id)->getPerformanceModel()->getInstructionCount(); return result; case GLOBAL_NONIDLE_ELAPSED_TIME: for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) result += Sim()->getCoreManager()->getCoreFromID(core_id)->getPerformanceModel()->getNonIdleElapsedTime().getFS(); return result; default: LOG_PRINT_ERROR("Unexpected user value %d", user); } } // Helper class to provide simplified cpiMem component ThreadStatsManager::ThreadStatType RoutineTracerFunctionStats::ThreadStatCpiMem::registerStat() { ThreadStatCpiMem *tsns = new ThreadStatCpiMem(); return Sim()->getThreadStatsManager()->registerThreadStatMetric(ThreadStatsManager::DYNAMIC, "cpiMem", callback, (UInt64)tsns); } RoutineTracerFunctionStats::ThreadStatCpiMem::ThreadStatCpiMem() : m_stats(Sim()->getConfig()->getApplicationCores()) { for(core_id_t core_id = 0; core_id < (core_id_t)Sim()->getConfig()->getApplicationCores(); ++core_id) { for (int h = HitWhere::WHERE_FIRST ; h < HitWhere::NUM_HITWHERES ; h++) { String metricName = "cpiDataCache" + String(HitWhereString((HitWhere::where_t)h)); StatsMetricBase *m = Sim()->getStatsManager()->getMetricObject("interval_timer", core_id, metricName); LOG_ASSERT_ERROR(m != NULL, "Invalid statistic %s.%d.%s", "interval_timer", core_id, metricName.c_str()); m_stats[core_id].push_back(m); } } } UInt64 RoutineTracerFunctionStats::ThreadStatCpiMem::callback(ThreadStatsManager::ThreadStatType type, thread_id_t thread_id, Core *core, UInt64 user) { ThreadStatCpiMem* tsns = (ThreadStatCpiMem*)user; std::vector<StatsMetricBase*>& stats = tsns->m_stats[core->getId()]; UInt64 result = 0; for(std::vector<StatsMetricBase*>::iterator it = stats.begin(); it != stats.end(); ++it) result += (*it)->recordMetric(); return result; }
Print first address in hex as well for full output
[rtntracer] Print first address in hex as well for full output
C++
mit
abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper,abanaiyan/sniper
e63b1521f43216f1478519493d35cee8b627cc7a
test/block.cpp
test/block.cpp
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file block.cpp * @author Christoph Jentzsch <[email protected]> * @date 2015 * block test functions. */ #include <libethereum/CanonBlockChain.h> #include "TestHelper.h" using namespace std; using namespace json_spirit; using namespace dev; using namespace dev::eth; namespace dev { namespace test { bytes createBlockRLPFromFields(mObject& _tObj) { BOOST_REQUIRE(_tObj.count("parentHash") > 0); BOOST_REQUIRE(_tObj.count("uncleHash") > 0); BOOST_REQUIRE(_tObj.count("coinbase") > 0); BOOST_REQUIRE(_tObj.count("stateRoot") > 0); BOOST_REQUIRE(_tObj.count("transactionsTrie")> 0); BOOST_REQUIRE(_tObj.count("receiptTrie") > 0); BOOST_REQUIRE(_tObj.count("bloom") > 0); BOOST_REQUIRE(_tObj.count("difficulty") > 0); BOOST_REQUIRE(_tObj.count("number") > 0); BOOST_REQUIRE(_tObj.count("gasLimit")> 0); BOOST_REQUIRE(_tObj.count("gasUsed") > 0); BOOST_REQUIRE(_tObj.count("timestamp") > 0); BOOST_REQUIRE(_tObj.count("extraData") > 0); BOOST_REQUIRE(_tObj.count("nonce") > 0); // construct RLP of the given block cout << "done with require\n"; RLPStream rlpStream; rlpStream.appendList(14); cout << "increate aha1\n"; rlpStream << h256(_tObj["parentHash"].get_str()) << h256(_tObj["uncleHash"].get_str()) << Address(_tObj["coinbase"].get_str()); rlpStream << h256(_tObj["stateRoot"].get_str()) << h256(_tObj["transactionsTrie"].get_str()) << Address(_tObj["receiptTrie"].get_str()); rlpStream << LogBloom(_tObj["bloom"].get_str()) << u256(_tObj["difficulty"].get_str()) << u256(_tObj["number"].get_str()); rlpStream << u256(_tObj["gasLimit"].get_str()) << u256(_tObj["gasUsed"].get_str()) << u256(_tObj["timestamp"].get_str()); rlpStream << importByteArray(_tObj["extraData"].get_str()) << h256(_tObj["nonce"].get_str()); return rlpStream.out(); } void doBlockTests(json_spirit::mValue& _v, bool _fillin) { for (auto& i: _v.get_obj()) { cerr << i.first << endl; mObject& o = i.second.get_obj(); if (_fillin == false) { BOOST_REQUIRE(o.count("rlp") > 0); const bytes rlpReaded = importByteArray(o["rlp"].get_str()); RLP myRLP(rlpReaded); BlockInfo blockFromRlp; try { blockFromRlp.populateFromHeader(myRLP, false); //blockFromRlp.verifyInternals(rlpReaded); } catch(Exception const& _e) { cnote << "block construction did throw an exception: " << diagnostic_information(_e); BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); BOOST_CHECK_MESSAGE(o.count("block") == 0, "A block object should not be defined because the block RLP is invalid!"); return; } BOOST_REQUIRE(o.count("block") > 0); mObject tObj = o["block"].get_obj(); BlockInfo blockFromFields; const bytes rlpreade2 = createBlockRLPFromFields(tObj); RLP mysecondRLP(rlpreade2); blockFromFields.populateFromHeader(mysecondRLP, false); //Check the fields restored from RLP to original fields BOOST_CHECK_MESSAGE(blockFromFields.hash == blockFromRlp.hash, "hash in given RLP not matching the block hash!"); BOOST_CHECK_MESSAGE(blockFromFields.parentHash == blockFromRlp.parentHash, "parentHash in given RLP not matching the block parentHash!"); BOOST_CHECK_MESSAGE(blockFromFields.sha3Uncles == blockFromRlp.sha3Uncles, "sha3Uncles in given RLP not matching the block sha3Uncles!"); BOOST_CHECK_MESSAGE(blockFromFields.coinbaseAddress == blockFromRlp.coinbaseAddress,"coinbaseAddress in given RLP not matching the block coinbaseAddress!"); BOOST_CHECK_MESSAGE(blockFromFields.stateRoot == blockFromRlp.stateRoot, "stateRoot in given RLP not matching the block stateRoot!"); BOOST_CHECK_MESSAGE(blockFromFields.transactionsRoot == blockFromRlp.transactionsRoot, "transactionsRoot in given RLP not matching the block transactionsRoot!"); BOOST_CHECK_MESSAGE(blockFromFields.logBloom == blockFromRlp.logBloom, "logBloom in given RLP not matching the block logBloom!"); BOOST_CHECK_MESSAGE(blockFromFields.difficulty == blockFromRlp.difficulty, "difficulty in given RLP not matching the block difficulty!"); BOOST_CHECK_MESSAGE(blockFromFields.number == blockFromRlp.number, "number in given RLP not matching the block number!"); BOOST_CHECK_MESSAGE(blockFromFields.gasLimit == blockFromRlp.gasLimit,"gasLimit in given RLP not matching the block gasLimit!"); BOOST_CHECK_MESSAGE(blockFromFields.gasUsed == blockFromRlp.gasUsed, "gasUsed in given RLP not matching the block gasUsed!"); BOOST_CHECK_MESSAGE(blockFromFields.timestamp == blockFromRlp.timestamp, "timestamp in given RLP not matching the block timestamp!"); BOOST_CHECK_MESSAGE(blockFromFields.extraData == blockFromRlp.extraData, "extraData in given RLP not matching the block extraData!"); BOOST_CHECK_MESSAGE(blockFromFields.nonce == blockFromRlp.nonce, "nonce in given RLP not matching the block nonce!"); BOOST_CHECK_MESSAGE(blockFromFields == blockFromRlp, "However, blockFromFields != blockFromRlp!"); } else { // BOOST_REQUIRE(o.count("block") > 0); // // construct Rlp of the given block // bytes blockRLP = createBlockRLPFromFields(o["block"].get_obj()); // RLP myRLP(blockRLP); // o["rlp"] = toHex(blockRLP); // try // { // BlockInfo blockFromFields; // blockFromFields.populateFromHeader(myRLP, false); // (void)blockFromFields; // //blockFromFields.verifyInternals(blockRLP); // } // catch (Exception const& _e) // { // cnote << "block construction did throw an exception: " << diagnostic_information(_e); // BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); // o.erase(o.find("block")); // } // catch (std::exception const& _e) // { // cnote << "block construction did throw an exception: " << _e.what(); // BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); // o.erase(o.find("block")); // } // catch(...) // { // cnote << "block construction did throw an unknow exception\n"; // o.erase(o.find("block")); // } BOOST_REQUIRE(o.count("transactions") > 0); TransactionQueue txs; for (auto const& txObj: o["transactions"].get_array()) { mObject tx = txObj.get_obj(); BOOST_REQUIRE(tx.count("nonce") > 0); BOOST_REQUIRE(tx.count("gasPrice") > 0); BOOST_REQUIRE(tx.count("gasLimit") > 0); BOOST_REQUIRE(tx.count("to") > 0); BOOST_REQUIRE(tx.count("value") > 0); BOOST_REQUIRE(tx.count("v") > 0); BOOST_REQUIRE(tx.count("r") > 0); BOOST_REQUIRE(tx.count("s") > 0); BOOST_REQUIRE(tx.count("data") > 0); cout << "attempt to import transaction\n"; txs.attemptImport(createTransactionFromFields(tx)); } cout << "done importing txs\n"; //BOOST_REQUIRE(o.count("env") > 0); //BOOST_REQUIRE(o.count("pre") > 0); // ImportTest importer; // importer.importEnv(o["env"].get_obj()); // importer.importState(o["pre"].get_obj(), m_statePre); // State theState = importer.m_statePre; // bytes output; cout << "construct bc\n"; CanonBlockChain bc(true); cout << "construct state\n"; State theState; try { cout << "sync bc and txs in state\n"; theState.sync(bc,txs); // lock cout << "commit to mine\n"; theState.commitToMine(bc); // will call uncommitToMine if a repeat. // unlock MineInfo info; cout << "mine...\n"; for (info.completed = false; !info.completed; info = theState.mine()) {} cout << "done mining, completeMine\n"; // lock theState.completeMine(); // unlock cout << "new block: " << theState.blockData() << endl << theState.info() << endl; } catch (Exception const& _e) { cnote << "state sync did throw an exception: " << diagnostic_information(_e); } catch (std::exception const& _e) { cnote << "state sync did throw an exception: " << _e.what(); } // write block and rlp to json //TODO if block rlp is invalid, delete transactions, and block } } } } }// Namespace Close BOOST_AUTO_TEST_SUITE(BlockTests) BOOST_AUTO_TEST_CASE(blFirstTest) { dev::test::executeTests("blFirstTest", "/BlockTests", dev::test::doBlockTests); } //BOOST_AUTO_TEST_CASE(ttCreateTest) //{ // for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) // { // string arg = boost::unit_test::framework::master_test_suite().argv[i]; // if (arg == "--createtest") // { // if (boost::unit_test::framework::master_test_suite().argc <= i + 2) // { // cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n"; // return; // } // try // { // cnote << "Populating tests..."; // json_spirit::mValue v; // string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1])); // BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty."); // json_spirit::read_string(s, v); // dev::test::doBlockTests(v, true); // writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true))); // } // catch (Exception const& _e) // { // BOOST_ERROR("Failed block test with Exception: " << diagnostic_information(_e)); // } // catch (std::exception const& _e) // { // BOOST_ERROR("Failed block test with Exception: " << _e.what()); // } // } // } //} //BOOST_AUTO_TEST_CASE(userDefinedFileTT) //{ // dev::test::userDefinedTest("--bltest", dev::test::doBlockTests); //} BOOST_AUTO_TEST_SUITE_END()
/* This file is part of cpp-ethereum. cpp-ethereum is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. cpp-ethereum is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with cpp-ethereum. If not, see <http://www.gnu.org/licenses/>. */ /** @file block.cpp * @author Christoph Jentzsch <[email protected]> * @date 2015 * block test functions. */ #include <libethereum/CanonBlockChain.h> #include "TestHelper.h" using namespace std; using namespace json_spirit; using namespace dev; using namespace dev::eth; namespace dev { namespace test { bytes createBlockRLPFromFields(mObject& _tObj) { BOOST_REQUIRE(_tObj.count("parentHash") > 0); BOOST_REQUIRE(_tObj.count("uncleHash") > 0); BOOST_REQUIRE(_tObj.count("coinbase") > 0); BOOST_REQUIRE(_tObj.count("stateRoot") > 0); BOOST_REQUIRE(_tObj.count("transactionsTrie")> 0); BOOST_REQUIRE(_tObj.count("receiptTrie") > 0); BOOST_REQUIRE(_tObj.count("bloom") > 0); BOOST_REQUIRE(_tObj.count("difficulty") > 0); BOOST_REQUIRE(_tObj.count("number") > 0); BOOST_REQUIRE(_tObj.count("gasLimit")> 0); BOOST_REQUIRE(_tObj.count("gasUsed") > 0); BOOST_REQUIRE(_tObj.count("timestamp") > 0); BOOST_REQUIRE(_tObj.count("extraData") > 0); BOOST_REQUIRE(_tObj.count("nonce") > 0); // construct RLP of the given block cout << "done with require\n"; RLPStream rlpStream; rlpStream.appendList(14); cout << "increate aha1\n"; rlpStream << h256(_tObj["parentHash"].get_str()) << h256(_tObj["uncleHash"].get_str()) << Address(_tObj["coinbase"].get_str()); rlpStream << h256(_tObj["stateRoot"].get_str()) << h256(_tObj["transactionsTrie"].get_str()) << Address(_tObj["receiptTrie"].get_str()); rlpStream << LogBloom(_tObj["bloom"].get_str()) << u256(_tObj["difficulty"].get_str()) << u256(_tObj["number"].get_str()); rlpStream << u256(_tObj["gasLimit"].get_str()) << u256(_tObj["gasUsed"].get_str()) << u256(_tObj["timestamp"].get_str()); rlpStream << importByteArray(_tObj["extraData"].get_str()) << h256(_tObj["nonce"].get_str()); return rlpStream.out(); } void doBlockTests(json_spirit::mValue& _v, bool _fillin) { for (auto& i: _v.get_obj()) { cerr << i.first << endl; mObject& o = i.second.get_obj(); if (_fillin == false) { BOOST_REQUIRE(o.count("rlp") > 0); const bytes rlpReaded = importByteArray(o["rlp"].get_str()); RLP myRLP(rlpReaded); BlockInfo blockFromRlp; try { blockFromRlp.populateFromHeader(myRLP, false); //blockFromRlp.verifyInternals(rlpReaded); } catch(Exception const& _e) { cnote << "block construction did throw an exception: " << diagnostic_information(_e); BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); BOOST_CHECK_MESSAGE(o.count("block") == 0, "A block object should not be defined because the block RLP is invalid!"); return; } BOOST_REQUIRE(o.count("block") > 0); mObject tObj = o["block"].get_obj(); BlockInfo blockFromFields; const bytes rlpreade2 = createBlockRLPFromFields(tObj); RLP mysecondRLP(rlpreade2); blockFromFields.populateFromHeader(mysecondRLP, false); //Check the fields restored from RLP to original fields BOOST_CHECK_MESSAGE(blockFromFields.hash == blockFromRlp.hash, "hash in given RLP not matching the block hash!"); BOOST_CHECK_MESSAGE(blockFromFields.parentHash == blockFromRlp.parentHash, "parentHash in given RLP not matching the block parentHash!"); BOOST_CHECK_MESSAGE(blockFromFields.sha3Uncles == blockFromRlp.sha3Uncles, "sha3Uncles in given RLP not matching the block sha3Uncles!"); BOOST_CHECK_MESSAGE(blockFromFields.coinbaseAddress == blockFromRlp.coinbaseAddress,"coinbaseAddress in given RLP not matching the block coinbaseAddress!"); BOOST_CHECK_MESSAGE(blockFromFields.stateRoot == blockFromRlp.stateRoot, "stateRoot in given RLP not matching the block stateRoot!"); BOOST_CHECK_MESSAGE(blockFromFields.transactionsRoot == blockFromRlp.transactionsRoot, "transactionsRoot in given RLP not matching the block transactionsRoot!"); BOOST_CHECK_MESSAGE(blockFromFields.logBloom == blockFromRlp.logBloom, "logBloom in given RLP not matching the block logBloom!"); BOOST_CHECK_MESSAGE(blockFromFields.difficulty == blockFromRlp.difficulty, "difficulty in given RLP not matching the block difficulty!"); BOOST_CHECK_MESSAGE(blockFromFields.number == blockFromRlp.number, "number in given RLP not matching the block number!"); BOOST_CHECK_MESSAGE(blockFromFields.gasLimit == blockFromRlp.gasLimit,"gasLimit in given RLP not matching the block gasLimit!"); BOOST_CHECK_MESSAGE(blockFromFields.gasUsed == blockFromRlp.gasUsed, "gasUsed in given RLP not matching the block gasUsed!"); BOOST_CHECK_MESSAGE(blockFromFields.timestamp == blockFromRlp.timestamp, "timestamp in given RLP not matching the block timestamp!"); BOOST_CHECK_MESSAGE(blockFromFields.extraData == blockFromRlp.extraData, "extraData in given RLP not matching the block extraData!"); BOOST_CHECK_MESSAGE(blockFromFields.nonce == blockFromRlp.nonce, "nonce in given RLP not matching the block nonce!"); BOOST_CHECK_MESSAGE(blockFromFields == blockFromRlp, "However, blockFromFields != blockFromRlp!"); } else { // BOOST_REQUIRE(o.count("block") > 0); // // construct Rlp of the given block // bytes blockRLP = createBlockRLPFromFields(o["block"].get_obj()); // RLP myRLP(blockRLP); // o["rlp"] = toHex(blockRLP); // try // { // BlockInfo blockFromFields; // blockFromFields.populateFromHeader(myRLP, false); // (void)blockFromFields; // //blockFromFields.verifyInternals(blockRLP); // } // catch (Exception const& _e) // { // cnote << "block construction did throw an exception: " << diagnostic_information(_e); // BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); // o.erase(o.find("block")); // } // catch (std::exception const& _e) // { // cnote << "block construction did throw an exception: " << _e.what(); // BOOST_ERROR("Failed block construction Test with Exception: " << _e.what()); // o.erase(o.find("block")); // } // catch(...) // { // cnote << "block construction did throw an unknow exception\n"; // o.erase(o.find("block")); // } BOOST_REQUIRE(o.count("transactions") > 0); TransactionQueue txs; for (auto const& txObj: o["transactions"].get_array()) { mObject tx = txObj.get_obj(); BOOST_REQUIRE(tx.count("nonce") > 0); BOOST_REQUIRE(tx.count("gasPrice") > 0); BOOST_REQUIRE(tx.count("gasLimit") > 0); BOOST_REQUIRE(tx.count("to") > 0); BOOST_REQUIRE(tx.count("value") > 0); BOOST_REQUIRE(tx.count("v") > 0); BOOST_REQUIRE(tx.count("r") > 0); BOOST_REQUIRE(tx.count("s") > 0); BOOST_REQUIRE(tx.count("data") > 0); cout << "attempt to import transaction\n"; txs.attemptImport(createTransactionFromFields(tx)); } cout << "done importing txs\n"; //BOOST_REQUIRE(o.count("env") > 0); //BOOST_REQUIRE(o.count("pre") > 0); // ImportTest importer; // importer.importEnv(o["env"].get_obj()); // importer.importState(o["pre"].get_obj(), m_statePre); // State theState = importer.m_statePre; // bytes output; cout << "construct bc\n"; CanonBlockChain bc(true); cout << "construct state\n"; State theState; try { cout << "sync bc and txs in state\n"; theState.sync(bc,txs); // lock cout << "commit to mine\n"; theState.commitToMine(bc); // will call uncommitToMine if a repeat. // unlock MineInfo info; cout << "mine...\n"; for (info.completed = false; !info.completed; info = theState.mine()) {} cout << "done mining, completeMine\n"; // lock theState.completeMine(); // unlock cout << "new block: " << theState.blockData() << endl << theState.info() << endl; } catch (Exception const& _e) { cnote << "state sync did throw an exception: " << diagnostic_information(_e); } catch (std::exception const& _e) { cnote << "state sync did throw an exception: " << _e.what(); } o["rlp"] = "0x" + toHex(theState.blockData()); // write block header mObject oBlockHeader; BlockInfo current_BlockHeader = theState.info(); oBlockHeader["parentHash"] = toString(current_BlockHeader.parentHash); oBlockHeader["uncleHash"] = toString(current_BlockHeader.sha3Uncles); oBlockHeader["coinbase"] = toString(current_BlockHeader.coinbaseAddress); oBlockHeader["stateRoot"] = toString(current_BlockHeader.stateRoot); oBlockHeader["transactionsTrie"] = toString(current_BlockHeader.transactionsRoot); oBlockHeader["receiptTrie"] = toString(current_BlockHeader.receiptsRoot); oBlockHeader["bloom"] = toString(current_BlockHeader.logBloom); oBlockHeader["difficulty"] = toString(current_BlockHeader.difficulty); oBlockHeader["number"] = toString(current_BlockHeader.number); oBlockHeader["gasLimit"] = toString(current_BlockHeader.gasLimit); oBlockHeader["gasUsed"] = toString(current_BlockHeader.gasUsed); oBlockHeader["timestamp"] = toString(current_BlockHeader.timestamp); oBlockHeader["extraData"] = toHex(current_BlockHeader.extraData); oBlockHeader["nonce"] = toString(current_BlockHeader.nonce); o["blockHeader"] = oBlockHeader; // write uncle list mArray aUncleList; // as of now, our parent is always the genesis block, so we can not have uncles. That might change. o["uncleHeaders"] = aUncleList; } } } } }// Namespace Close BOOST_AUTO_TEST_SUITE(BlockTests) BOOST_AUTO_TEST_CASE(blFirstTest) { dev::test::executeTests("blFirstTest", "/BlockTests", dev::test::doBlockTests); } //BOOST_AUTO_TEST_CASE(ttCreateTest) //{ // for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i) // { // string arg = boost::unit_test::framework::master_test_suite().argv[i]; // if (arg == "--createtest") // { // if (boost::unit_test::framework::master_test_suite().argc <= i + 2) // { // cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n"; // return; // } // try // { // cnote << "Populating tests..."; // json_spirit::mValue v; // string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1])); // BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty."); // json_spirit::read_string(s, v); // dev::test::doBlockTests(v, true); // writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true))); // } // catch (Exception const& _e) // { // BOOST_ERROR("Failed block test with Exception: " << diagnostic_information(_e)); // } // catch (std::exception const& _e) // { // BOOST_ERROR("Failed block test with Exception: " << _e.what()); // } // } // } //} //BOOST_AUTO_TEST_CASE(userDefinedFileTT) //{ // dev::test::userDefinedTest("--bltest", dev::test::doBlockTests); //} BOOST_AUTO_TEST_SUITE_END()
write block header and uncle list
write block header and uncle list
C++
mit
PaulGrey30/go-get--u-github.com-tools-godep,LefterisJP/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,PaulGrey30/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,eco/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,Sorceror32/go-get--u-github.com-tools-godep,vaporry/evmjit,smartbitcoin/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,d-das/cpp-ethereum,ethers/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,anthony-cros/cpp-ethereum,eco/cpp-ethereum,gluk256/cpp-ethereum,johnpeter66/ethminer,yann300/cpp-ethereum,joeldo/cpp-ethereum,d-das/cpp-ethereum,ethers/cpp-ethereum,expanse-org/cpp-expanse,johnpeter66/ethminer,d-das/cpp-ethereum,karek314/cpp-ethereum,xeddmc/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,karek314/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,subtly/cpp-ethereum-micro,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,smartbitcoin/cpp-ethereum,LefterisJP/cpp-ethereum,xeddmc/cpp-ethereum,karek314/cpp-ethereum,anthony-cros/cpp-ethereum,joeldo/cpp-ethereum,gluk256/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,expanse-org/cpp-expanse,smartbitcoin/cpp-ethereum,johnpeter66/ethminer,karek314/cpp-ethereum,d-das/cpp-ethereum,yann300/cpp-ethereum,yann300/cpp-ethereum,d-das/cpp-ethereum,anthony-cros/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,ethers/cpp-ethereum,subtly/cpp-ethereum-micro,yann300/cpp-ethereum,eco/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,expanse-org/cpp-expanse,smartbitcoin/cpp-ethereum,subtly/cpp-ethereum-micro,karek314/cpp-ethereum,karek314/cpp-ethereum,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,LefterisJP/cpp-ethereum,vaporry/cpp-ethereum,expanse-project/cpp-expanse,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,eco/cpp-ethereum,joeldo/cpp-ethereum,smartbitcoin/cpp-ethereum,yann300/cpp-ethereum,xeddmc/cpp-ethereum,expanse-project/cpp-expanse,expanse-org/cpp-expanse,PaulGrey30/.-git-clone-https-github.com-ethereum-cpp-ethereum,joeldo/cpp-ethereum,vaporry/cpp-ethereum,xeddmc/cpp-ethereum,chfast/webthree-umbrella,gluk256/cpp-ethereum,PaulGrey30/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,yann300/cpp-ethereum,eco/cpp-ethereum,subtly/cpp-ethereum-micro,programonauta/webthree-umbrella,xeddmc/cpp-ethereum,arkpar/webthree-umbrella,LefterisJP/webthree-umbrella,Sorceror32/go-get--u-github.com-tools-godep,PaulGrey30/go-get--u-github.com-tools-godep,vaporry/cpp-ethereum,expanse-project/cpp-expanse,eco/cpp-ethereum,smartbitcoin/cpp-ethereum,LefterisJP/cpp-ethereum,anthony-cros/cpp-ethereum,gluk256/cpp-ethereum,vaporry/webthree-umbrella,anthony-cros/cpp-ethereum,LefterisJP/cpp-ethereum,joeldo/cpp-ethereum,vaporry/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,gluk256/cpp-ethereum,Sorceror32/go-get--u-github.com-tools-godep,ethers/cpp-ethereum,LefterisJP/webthree-umbrella,d-das/cpp-ethereum,subtly/cpp-ethereum-micro,anthony-cros/cpp-ethereum,gluk256/cpp-ethereum,expanse-project/cpp-expanse,xeddmc/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,programonauta/webthree-umbrella,expanse-project/cpp-expanse,expanse-org/cpp-expanse,ethers/cpp-ethereum,Sorceror32/.-git-clone-https-github.com-ethereum-cpp-ethereum,LefterisJP/cpp-ethereum,joeldo/cpp-ethereum,ethers/cpp-ethereum,subtly/cpp-ethereum-micro,vaporry/evmjit,expanse-project/cpp-expanse,expanse-org/cpp-expanse
f444e47e800b0fa5f5a7846ac2a2dd24fd93f5db
cpp/schedulers/greedy_turbo_scheduler.cpp
cpp/schedulers/greedy_turbo_scheduler.cpp
#include "schedulers/greedy_turbo_scheduler.h" namespace schedulers { GreedyTurboScheduler::GreedyTurboScheduler(const game::Race& race, game::CarTracker& car_tracker) : race_(race), car_tracker_(car_tracker), turbo_available_(false), should_fire_now_(false) { } // Returns if should we use turbo bool GreedyTurboScheduler::ShouldFireTurbo() { return should_fire_now_; } // Makes decision on turbo usage void GreedyTurboScheduler::Schedule(const game::CarState& state) { if (!turbo_available_) { should_fire_now_ = false; return; } // TODO(kareth) strategies // TODO check if its safe to fire turbo now. if (state.position().lap() <= race_.laps() - 1 && race_.track().IsLastStraight(state.position())) should_fire_now_ = true; } // Prepare for overtake void GreedyTurboScheduler::Overtake(const string& color) { printf("Feature not implemented.\n"); } void GreedyTurboScheduler::NewTurbo(const game::Turbo& turbo) { turbo_available_ = true; turbo_ = turbo; } void GreedyTurboScheduler::TurboUsed() { turbo_available_ = false; should_fire_now_ = false; } } // namespace schedulers
#include "schedulers/greedy_turbo_scheduler.h" namespace schedulers { GreedyTurboScheduler::GreedyTurboScheduler(const game::Race& race, game::CarTracker& car_tracker) : race_(race), car_tracker_(car_tracker), turbo_available_(false), should_fire_now_(false) { } // Returns if should we use turbo bool GreedyTurboScheduler::ShouldFireTurbo() { return should_fire_now_; } // Makes decision on turbo usage void GreedyTurboScheduler::Schedule(const game::CarState& state) { if (!turbo_available_) { should_fire_now_ = false; return; } // TODO(kareth) strategies // TODO check if its safe to fire turbo now. if (state.position().lap() == race_.laps() - 1 && race_.track().IsLastStraight(state.position())) should_fire_now_ = true; } // Prepare for overtake void GreedyTurboScheduler::Overtake(const string& color) { printf("Feature not implemented.\n"); } void GreedyTurboScheduler::NewTurbo(const game::Turbo& turbo) { turbo_available_ = true; turbo_ = turbo; } void GreedyTurboScheduler::TurboUsed() { turbo_available_ = false; should_fire_now_ = false; } } // namespace schedulers
revert turbo firing
revert turbo firing
C++
apache-2.0
kareth/helloworldopen2014,kareth/helloworldopen2014,kareth/helloworldopen2014,kareth/helloworldopen2014,kareth/helloworldopen2014
fb5286dea5e7d09759e923768a76010a01266d39
2D-Game-Engine/Window.cpp
2D-Game-Engine/Window.cpp
#include "Window.h" #include <GLFW/glfw3.h> #include <exception> #include "Input.h" Window::Window(string title, int32 width, int32 height) : m_title(title), m_width(width), m_height(height) { glfwSetErrorCallback([](int32 error, const char* desc) -> void { DEBUG_LOG(desc); }); if (!glfwInit()) { throw runtime_error("Failed to initialize GLFW."); } glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); m_handle = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (!m_handle) { glfwTerminate(); throw runtime_error("Failed to initialize window."); } glfwMakeContextCurrent(m_handle); glfwSwapInterval(1); // Center window const GLFWvidmode* vid = glfwGetVideoMode(glfwGetPrimaryMonitor()); int32 x = (vid->width / 2) - (width / 2); int32 y = (vid->height / 2) - (height / 2); glfwSetWindowPos(m_handle, x, y); glfwShowWindow(m_handle); glfwSetWindowUserPointer(m_handle, this); glfwSetWindowSizeCallback(m_handle, windowSizeCallback); m_input = new Input(this); } Window::~Window() { delete m_input; glfwTerminate(); } static void windowSizeCallback(GLFWwindow* window, int32 width, int32 height) { Window* windowPtr = (Window*)glfwGetWindowUserPointer(window); windowPtr->m_width = width; windowPtr->m_height = height; } void Window::setTitle(const string& title) { this->m_title = title; glfwSetWindowTitle(m_handle, title.c_str()); } void Window::swapBuffers() const { glfwSwapBuffers(m_handle); } int32 Window::shouldClose() const { return glfwWindowShouldClose(m_handle); } void Window::pollEvents() { glfwPollEvents(); }
#include "Window.h" #include <GL\glew.h> #include <GLFW/glfw3.h> #include <exception> #include "Input.h" Window::Window(string title, int32 width, int32 height) : m_title(title), m_width(width), m_height(height) { glfwSetErrorCallback([](int32 error, const char* desc) -> void { DEBUG_LOG(desc); }); if (!glfwInit()) { throw runtime_error("Failed to initialize GLFW."); } glfwDefaultWindowHints(); glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE); glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE); m_handle = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (!m_handle) { glfwTerminate(); throw runtime_error("Failed to initialize window."); } glfwMakeContextCurrent(m_handle); glfwSwapInterval(1); // Center window const GLFWvidmode* vid = glfwGetVideoMode(glfwGetPrimaryMonitor()); int32 x = (vid->width / 2) - (width / 2); int32 y = (vid->height / 2) - (height / 2); glfwSetWindowPos(m_handle, x, y); glfwShowWindow(m_handle); glfwSetWindowUserPointer(m_handle, this); glfwSetWindowSizeCallback(m_handle, windowSizeCallback); m_input = new Input(this); } Window::~Window() { delete m_input; glfwTerminate(); } static void windowSizeCallback(GLFWwindow* window, int32 width, int32 height) { Window* windowPtr = (Window*)glfwGetWindowUserPointer(window); windowPtr->m_width = width; windowPtr->m_height = height; glViewport(0, 0, width, height); } void Window::setTitle(const string& title) { this->m_title = title; glfwSetWindowTitle(m_handle, title.c_str()); } void Window::swapBuffers() const { glfwSwapBuffers(m_handle); } int32 Window::shouldClose() const { return glfwWindowShouldClose(m_handle); } void Window::pollEvents() { glfwPollEvents(); }
Fix view port not changing when window rezises
Fix view port not changing when window rezises
C++
mit
simon-bourque/2D-Game-Engine-Cpp,simon-bourque/2D-Game-Engine-Cpp
d178a8aebb6cccce8f333a0272f0509ffdb098a0
ouzel/thread/Thread.cpp
ouzel/thread/Thread.cpp
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include <sys/proc.h> #include "Thread.hpp" #if defined(_MSC_VER) static const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) #endif #if defined(_MSC_VER) static DWORD WINAPI threadFunction(LPVOID parameter) #else static void* threadFunction(void* parameter) #endif { ouzel::Thread::State* state = static_cast<ouzel::Thread::State*>(parameter); if (!state->name.empty()) ouzel::Thread::setCurrentThreadName(state->name); state->function(); #if defined(_MSC_VER) return 0; #else return NULL; #endif } namespace ouzel { Thread::Thread(const std::function<void()>& function, const std::string& name): state(new State()) { state->function = function; state->name = name; #if defined(_MSC_VER) handle = CreateThread(nullptr, 0, threadFunction, state.get(), 0, &threadId); if (handle == nullptr) return; #else if (pthread_create(&thread, NULL, threadFunction, state.get()) != 0) return; #endif } Thread::~Thread() { #if defined(_MSC_VER) if (handle) { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } #else if (thread) pthread_join(thread, nullptr); #endif } Thread::Thread(Thread&& other) { #if defined(_MSC_VER) handle = other.handle; threadId = other.threadId; other.handle = nullptr; other.threadId = 0; #else thread = other.thread; other.thread = 0; #endif state = std::move(other.state); } Thread& Thread::operator=(Thread&& other) { #if defined(_MSC_VER) if (handle) { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } handle = other.handle; threadId = other.threadId; other.handle = nullptr; other.threadId = 0; #else if (thread) pthread_join(thread, nullptr); thread = other.thread; other.thread = 0; #endif state = std::move(other.state); return *this; } bool Thread::join() { #if defined(_MSC_VER) return handle ? (WaitForSingleObject(handle, INFINITE) != WAIT_FAILED) : false; #else return thread ? (pthread_join(thread, nullptr) == 0) : false; #endif } bool Thread::setCurrentThreadName(const std::string& name) { #if defined(_MSC_VER) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = static_cast<DWORD>(-1); info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info)); } __except (EXCEPTION_EXECUTE_HANDLER) { } return true; #else #ifdef __APPLE__ return pthread_setname_np(name.c_str()) == 0; #else return pthread_setname_np(pthread_self(), name.c_str()) == 0; #endif #endif } }
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #include "Thread.hpp" #if defined(_MSC_VER) static const DWORD MS_VC_EXCEPTION = 0x406D1388; #pragma pack(push,8) typedef struct tagTHREADNAME_INFO { DWORD dwType; // Must be 0x1000. LPCSTR szName; // Pointer to name (in user addr space). DWORD dwThreadID; // Thread ID (-1=caller thread). DWORD dwFlags; // Reserved for future use, must be zero. } THREADNAME_INFO; #pragma pack(pop) #endif #if defined(_MSC_VER) static DWORD WINAPI threadFunction(LPVOID parameter) #else static void* threadFunction(void* parameter) #endif { ouzel::Thread::State* state = static_cast<ouzel::Thread::State*>(parameter); if (!state->name.empty()) ouzel::Thread::setCurrentThreadName(state->name); state->function(); #if defined(_MSC_VER) return 0; #else return NULL; #endif } namespace ouzel { Thread::Thread(const std::function<void()>& function, const std::string& name): state(new State()) { state->function = function; state->name = name; #if defined(_MSC_VER) handle = CreateThread(nullptr, 0, threadFunction, state.get(), 0, &threadId); if (handle == nullptr) return; #else if (pthread_create(&thread, NULL, threadFunction, state.get()) != 0) return; #endif } Thread::~Thread() { #if defined(_MSC_VER) if (handle) { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } #else if (thread) pthread_join(thread, nullptr); #endif } Thread::Thread(Thread&& other) { #if defined(_MSC_VER) handle = other.handle; threadId = other.threadId; other.handle = nullptr; other.threadId = 0; #else thread = other.thread; other.thread = 0; #endif state = std::move(other.state); } Thread& Thread::operator=(Thread&& other) { #if defined(_MSC_VER) if (handle) { WaitForSingleObject(handle, INFINITE); CloseHandle(handle); } handle = other.handle; threadId = other.threadId; other.handle = nullptr; other.threadId = 0; #else if (thread) pthread_join(thread, nullptr); thread = other.thread; other.thread = 0; #endif state = std::move(other.state); return *this; } bool Thread::join() { #if defined(_MSC_VER) return handle ? (WaitForSingleObject(handle, INFINITE) != WAIT_FAILED) : false; #else return thread ? (pthread_join(thread, nullptr) == 0) : false; #endif } bool Thread::setCurrentThreadName(const std::string& name) { #if defined(_MSC_VER) THREADNAME_INFO info; info.dwType = 0x1000; info.szName = name.c_str(); info.dwThreadID = static_cast<DWORD>(-1); info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(ULONG_PTR), reinterpret_cast<ULONG_PTR*>(&info)); } __except (EXCEPTION_EXECUTE_HANDLER) { } return true; #else #ifdef __APPLE__ return pthread_setname_np(name.c_str()) == 0; #else return pthread_setname_np(pthread_self(), name.c_str()) == 0; #endif #endif } }
Remove the unneeded include
Remove the unneeded include
C++
unlicense
elvman/ouzel,elnormous/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel
22630894eaebeeb84da4b368a44ae3c46878367e
ouzel/thread/Thread.hpp
ouzel/thread/Thread.hpp
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #include <functional> #include <memory> #include <string> #if defined(_WIN32) #include <Windows.h> #define ThreadLocal __declspec(thread) #else #include <pthread.h> #define ThreadLocal __thread #if defined(__APPLE__) #include <sys/sysctl.h> #endif // #if defined(__APPLE__) #endif namespace ouzel { inline uint32_t getCPUCount() { #if defined(_WIN32) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #else #if defined(__APPLE__) int mib[2]; mib[0] = CTL_HW; #ifdef HW_AVAILCPU mib[1] = HW_AVAILCPU; #else mib[1] = HW_NCPU; #endif int count; size_t size = sizeof(count); sysctl(mib, 2, &count, &size, NULL, 0); return (count > 0) ? static_cast<uint32_t>(count) : 0; #elif defined(__linux__) || defined(__ANDROID__) int count = sysconf(_SC_NPROCESSORS_ONLN); return (count > 0) ? static_cast<uint32_t>(count) : 0; #else return 1; #endif #endif } class Thread final { public: class ID { friend Thread; public: bool operator==(const ID& other) { #if defined(_WIN32) return threadId == other.threadId; #else return pthread_equal(thread, other.thread) != 0; #endif } bool operator!=(const ID& other) { #if defined(_WIN32) return threadId != other.threadId; #else return pthread_equal(thread, other.thread) == 0; #endif } protected: #if defined(_WIN32) ID(DWORD id): threadId(id) #else ID(pthread_t t): thread(t) #endif { } private: #if defined(_WIN32) DWORD threadId = 0; #else pthread_t thread = 0; #endif }; Thread() {} explicit Thread(const std::function<void()>& function, const std::string& name = ""); ~Thread(); Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; Thread(Thread&& other); Thread& operator=(Thread&& other); bool run(); bool join(); inline bool isJoinable() const { #if defined(_WIN32) return handle != nullptr; #else return thread != 0; #endif } ID getId() const { #if defined(_WIN32) return threadId; #else return thread; #endif } static ID getCurrentThreadId() { #if defined(_WIN32) return GetCurrentThreadId(); #else return pthread_self(); #endif } static bool setCurrentThreadName(const std::string& name); struct State { std::function<void()> function; std::string name; }; protected: std::unique_ptr<State> state; #if defined(_WIN32) HANDLE handle = nullptr; DWORD threadId = 0; #else pthread_t thread = 0; #endif }; }
// Copyright (C) 2018 Elviss Strazdins // This file is part of the Ouzel engine. #pragma once #include <functional> #include <memory> #include <string> #if defined(_WIN32) #include <Windows.h> #define ThreadLocal __declspec(thread) #else #include <pthread.h> #define ThreadLocal __thread #if defined(__APPLE__) #include <sys/sysctl.h> #else #include <unistd.h> #endif // #if defined(__APPLE__) #endif namespace ouzel { inline uint32_t getCPUCount() { #if defined(_WIN32) SYSTEM_INFO sysinfo; GetSystemInfo(&sysinfo); return sysinfo.dwNumberOfProcessors; #else #if defined(__APPLE__) int mib[2]; mib[0] = CTL_HW; #ifdef HW_AVAILCPU mib[1] = HW_AVAILCPU; #else mib[1] = HW_NCPU; #endif int count; size_t size = sizeof(count); sysctl(mib, 2, &count, &size, NULL, 0); return (count > 0) ? static_cast<uint32_t>(count) : 0; #elif defined(__linux__) || defined(__ANDROID__) int count = sysconf(_SC_NPROCESSORS_ONLN); return (count > 0) ? static_cast<uint32_t>(count) : 0; #else return 1; #endif #endif } class Thread final { public: class ID { friend Thread; public: bool operator==(const ID& other) { #if defined(_WIN32) return threadId == other.threadId; #else return pthread_equal(thread, other.thread) != 0; #endif } bool operator!=(const ID& other) { #if defined(_WIN32) return threadId != other.threadId; #else return pthread_equal(thread, other.thread) == 0; #endif } protected: #if defined(_WIN32) ID(DWORD id): threadId(id) #else ID(pthread_t t): thread(t) #endif { } private: #if defined(_WIN32) DWORD threadId = 0; #else pthread_t thread = 0; #endif }; Thread() {} explicit Thread(const std::function<void()>& function, const std::string& name = ""); ~Thread(); Thread(const Thread&) = delete; Thread& operator=(const Thread&) = delete; Thread(Thread&& other); Thread& operator=(Thread&& other); bool run(); bool join(); inline bool isJoinable() const { #if defined(_WIN32) return handle != nullptr; #else return thread != 0; #endif } ID getId() const { #if defined(_WIN32) return threadId; #else return thread; #endif } static ID getCurrentThreadId() { #if defined(_WIN32) return GetCurrentThreadId(); #else return pthread_self(); #endif } static bool setCurrentThreadName(const std::string& name); struct State { std::function<void()> function; std::string name; }; protected: std::unique_ptr<State> state; #if defined(_WIN32) HANDLE handle = nullptr; DWORD threadId = 0; #else pthread_t thread = 0; #endif }; }
Add missing include
Add missing include
C++
unlicense
elvman/ouzel,elvman/ouzel,elnormous/ouzel,elnormous/ouzel,elnormous/ouzel
949424556fbb7c43f12b9c16ffbaeee522195972
lib/generic_writer.hpp
lib/generic_writer.hpp
#ifndef PYOSMIUM_GENERIC_WRITER_HPP #define PYOSMIUM_GENERIC_WRITER_HPP #include <osmium/osm.hpp> #include <osmium/io/any_output.hpp> #include <osmium/io/writer.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/builder/osm_object_builder.hpp> #include <boost/python.hpp> class SimpleWriterWrap { enum { BUFFER_WRAP = 4096 }; public: SimpleWriterWrap(const char* filename, size_t bufsz=4096*1024) : writer(filename), buffer(bufsz < 2*BUFFER_WRAP ? 2*BUFFER_WRAP : bufsz, osmium::memory::Buffer::auto_grow::yes) {} virtual ~SimpleWriterWrap() { close(); } void add_osmium_object(const osmium::OSMObject& o) { buffer.add_item(o); flush_buffer(); } void add_node(boost::python::object o) { boost::python::extract<osmium::Node&> node(o); if (node.check()) { buffer.add_item(node()); } else { osmium::builder::NodeBuilder builder(buffer); if (hasattr(o, "location")) { osmium::Node& n = builder.object(); n.set_location(get_location(o.attr("location"))); } set_common_attributes(o, builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void add_way(const boost::python::object& o) { boost::python::extract<osmium::Way&> way(o); if (way.check()) { buffer.add_item(way()); } else { osmium::builder::WayBuilder builder(buffer); set_common_attributes(o, builder); if (hasattr(o, "nodes")) set_nodelist(o.attr("nodes"), &builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void add_relation(boost::python::object o) { boost::python::extract<osmium::Relation&> rel(o); if (rel.check()) { buffer.add_item(rel()); } else { osmium::builder::RelationBuilder builder(buffer); set_common_attributes(o, builder); if (hasattr(o, "members")) set_memberlist(o.attr("members"), &builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void close() { if (buffer) { writer(std::move(buffer)); writer.close(); buffer = osmium::memory::Buffer(); } } private: void set_object_attributes(const boost::python::object& o, osmium::OSMObject& t) { if (hasattr(o, "id")) t.set_id(boost::python::extract<osmium::object_id_type>(o.attr("id"))); if (hasattr(o, "visible")) t.set_visible(boost::python::extract<bool>(o.attr("visible"))); if (hasattr(o, "version")) t.set_version(boost::python::extract<osmium::object_version_type>(o.attr("version"))); if (hasattr(o, "changeset")) t.set_changeset(boost::python::extract<osmium::changeset_id_type>(o.attr("changeset"))); if (hasattr(o, "uid")) t.set_uid_from_signed(boost::python::extract<osmium::signed_user_id_type>(o.attr("uid"))); if (hasattr(o, "timestamp")) { boost::python::object ts = o.attr("timestamp"); boost::python::extract<osmium::Timestamp> ots(ts); if (ots.check()) { t.set_timestamp(ots()); } else { if (hasattr(ts, "timestamp")) { double epoch = boost::python::extract<double>(ts.attr("timestamp")()); t.set_timestamp(osmium::Timestamp(uint32_t(epoch))); } else { // XXX terribly inefficient because of the double string conversion // but the only painless method for converting a datetime // in python < 3.3. if (hasattr(ts, "strftime")) ts = ts.attr("strftime")("%Y-%m-%dT%H:%M:%SZ"); t.set_timestamp(osmium::Timestamp(boost::python::extract<const char *>(ts))); } } } } template <typename T> void set_common_attributes(const boost::python::object& o, T& builder) { set_object_attributes(o, builder.object()); if (hasattr(o, "user")) { auto s = boost::python::extract<const char *>(o.attr("user")); builder.add_user(s); } else { builder.add_user("", 0); } } template <typename T> void set_taglist(const boost::python::object& o, T& obuilder) { // original taglist boost::python::extract<osmium::TagList&> otl(o); if (otl.check()) { if (otl().size() > 0) obuilder.add_item(&otl()); return; } // dict boost::python::extract<boost::python::dict> tagdict(o); if (tagdict.check()) { auto items = tagdict().items(); auto len = boost::python::len(items); if (len == 0) return; osmium::builder::TagListBuilder builder(buffer, &obuilder); auto iter = items.attr("__iter__")(); for (int i = 0; i < len; ++i) { #if PY_VERSION_HEX < 0x03000000 auto tag = iter.attr("next")(); #else auto tag = iter.attr("__next__")(); #endif builder.add_tag(boost::python::extract<const char *>(tag[0]), boost::python::extract<const char *>(tag[1])); } return; } // any other iterable auto l = boost::python::len(o); if (l == 0) return; osmium::builder::TagListBuilder builder(buffer, &obuilder); for (int i = 0; i < l; ++i) { auto tag = o[i]; boost::python::extract<osmium::Tag> ot(tag); if (ot.check()) { builder.add_tag(ot); } else { builder.add_tag(boost::python::extract<const char *>(tag[0]), boost::python::extract<const char *>(tag[1])); } } } void set_nodelist(const boost::python::object& o, osmium::builder::WayBuilder *builder) { // original nodelist boost::python::extract<osmium::NodeRefList&> onl(o); if (onl.check()) { if (onl().size() > 0) builder->add_item(&onl()); return; } auto len = boost::python::len(o); if (len == 0) return; osmium::builder::WayNodeListBuilder wnl_builder(buffer, builder); for (int i = 0; i < len; ++i) { boost::python::extract<osmium::NodeRef> ref(o[i]); if (ref.check()) wnl_builder.add_node_ref(ref()); else wnl_builder.add_node_ref(boost::python::extract<osmium::object_id_type>(o[i])); } } void set_memberlist(const boost::python::object& o, osmium::builder::RelationBuilder *builder) { // original memberlist boost::python::extract<osmium::RelationMemberList&> oml(o); if (oml.check()) { if (oml().size() > 0) builder->add_item(&oml()); return; } auto len = boost::python::len(o); if (len == 0) return; osmium::builder::RelationMemberListBuilder rml_builder(buffer, builder); for (int i = 0; i < len; ++i) { auto member = o[i]; auto type = osmium::char_to_item_type(boost::python::extract<const char*>(member[0])()[0]); auto id = boost::python::extract<osmium::object_id_type>(member[1])(); auto role = boost::python::extract<const char*>(member[2])(); rml_builder.add_member(type, id, role); } } osmium::Location get_location(const boost::python::object& o) { boost::python::extract<osmium::Location> ol(o); if (ol.check()) return ol; // default is a tuple with two floats return osmium::Location(boost::python::extract<float>(o[0]), boost::python::extract<float>(o[1])); } bool hasattr(const boost::python::object& obj, char const *attr) { return PyObject_HasAttrString(obj.ptr(), attr) && (obj.attr(attr) != boost::python::object()); } void flush_buffer() { buffer.commit(); if (buffer.committed() > buffer.capacity() - BUFFER_WRAP) { osmium::memory::Buffer new_buffer(buffer.capacity(), osmium::memory::Buffer::auto_grow::yes); using std::swap; swap(buffer, new_buffer); writer(std::move(new_buffer)); } } osmium::io::Writer writer; osmium::memory::Buffer buffer; }; #endif // PYOSMIUM_GENERIC_WRITER_HPP
#ifndef PYOSMIUM_GENERIC_WRITER_HPP #define PYOSMIUM_GENERIC_WRITER_HPP #include <osmium/osm.hpp> #include <osmium/io/any_output.hpp> #include <osmium/io/writer.hpp> #include <osmium/memory/buffer.hpp> #include <osmium/builder/osm_object_builder.hpp> #include <boost/python.hpp> class SimpleWriterWrap { enum { BUFFER_WRAP = 4096 }; public: SimpleWriterWrap(const char* filename, size_t bufsz=4096*1024) : writer(filename), buffer(bufsz < 2*BUFFER_WRAP ? 2*BUFFER_WRAP : bufsz, osmium::memory::Buffer::auto_grow::yes) {} virtual ~SimpleWriterWrap() { close(); } void add_osmium_object(const osmium::OSMObject& o) { buffer.add_item(o); flush_buffer(); } void add_node(boost::python::object o) { boost::python::extract<osmium::Node&> node(o); if (node.check()) { buffer.add_item(node()); } else { osmium::builder::NodeBuilder builder(buffer); if (hasattr(o, "location")) { osmium::Node& n = builder.object(); n.set_location(get_location(o.attr("location"))); } set_common_attributes(o, builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void add_way(const boost::python::object& o) { boost::python::extract<osmium::Way&> way(o); if (way.check()) { buffer.add_item(way()); } else { osmium::builder::WayBuilder builder(buffer); set_common_attributes(o, builder); if (hasattr(o, "nodes")) set_nodelist(o.attr("nodes"), &builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void add_relation(boost::python::object o) { boost::python::extract<osmium::Relation&> rel(o); if (rel.check()) { buffer.add_item(rel()); } else { osmium::builder::RelationBuilder builder(buffer); set_common_attributes(o, builder); if (hasattr(o, "members")) set_memberlist(o.attr("members"), &builder); if (hasattr(o, "tags")) set_taglist(o.attr("tags"), builder); } flush_buffer(); } void close() { if (buffer) { writer(std::move(buffer)); writer.close(); buffer = osmium::memory::Buffer(); } } private: void set_object_attributes(const boost::python::object& o, osmium::OSMObject& t) { if (hasattr(o, "id")) t.set_id(boost::python::extract<osmium::object_id_type>(o.attr("id"))); if (hasattr(o, "visible")) t.set_visible(boost::python::extract<bool>(o.attr("visible"))); if (hasattr(o, "version")) t.set_version(boost::python::extract<osmium::object_version_type>(o.attr("version"))); if (hasattr(o, "changeset")) t.set_changeset(boost::python::extract<osmium::changeset_id_type>(o.attr("changeset"))); if (hasattr(o, "uid")) t.set_uid_from_signed(boost::python::extract<osmium::signed_user_id_type>(o.attr("uid"))); if (hasattr(o, "timestamp")) { boost::python::object ts = o.attr("timestamp"); boost::python::extract<osmium::Timestamp> ots(ts); if (ots.check()) { t.set_timestamp(ots()); } else { if (hasattr(ts, "timestamp")) { double epoch = boost::python::extract<double>(ts.attr("timestamp")()); t.set_timestamp(osmium::Timestamp(uint32_t(epoch))); } else { // XXX terribly inefficient because of the double string conversion // but the only painless method for converting a datetime // in python < 3.3. if (hasattr(ts, "strftime")) ts = ts.attr("strftime")("%Y-%m-%dT%H:%M:%SZ"); t.set_timestamp(osmium::Timestamp(boost::python::extract<const char *>(ts))); } } } } template <typename T> void set_common_attributes(const boost::python::object& o, T& builder) { set_object_attributes(o, builder.object()); if (hasattr(o, "user")) { auto s = boost::python::extract<const char *>(o.attr("user")); builder.set_user(s); } } template <typename T> void set_taglist(const boost::python::object& o, T& obuilder) { // original taglist boost::python::extract<osmium::TagList&> otl(o); if (otl.check()) { if (otl().size() > 0) obuilder.add_item(otl()); return; } // dict boost::python::extract<boost::python::dict> tagdict(o); if (tagdict.check()) { auto items = tagdict().items(); auto len = boost::python::len(items); if (len == 0) return; osmium::builder::TagListBuilder builder(buffer, &obuilder); auto iter = items.attr("__iter__")(); for (int i = 0; i < len; ++i) { #if PY_VERSION_HEX < 0x03000000 auto tag = iter.attr("next")(); #else auto tag = iter.attr("__next__")(); #endif builder.add_tag(boost::python::extract<const char *>(tag[0]), boost::python::extract<const char *>(tag[1])); } return; } // any other iterable auto l = boost::python::len(o); if (l == 0) return; osmium::builder::TagListBuilder builder(buffer, &obuilder); for (int i = 0; i < l; ++i) { auto tag = o[i]; boost::python::extract<osmium::Tag> ot(tag); if (ot.check()) { builder.add_tag(ot); } else { builder.add_tag(boost::python::extract<const char *>(tag[0]), boost::python::extract<const char *>(tag[1])); } } } void set_nodelist(const boost::python::object& o, osmium::builder::WayBuilder *builder) { // original nodelist boost::python::extract<osmium::NodeRefList&> onl(o); if (onl.check()) { if (onl().size() > 0) builder->add_item(onl()); return; } auto len = boost::python::len(o); if (len == 0) return; osmium::builder::WayNodeListBuilder wnl_builder(buffer, builder); for (int i = 0; i < len; ++i) { boost::python::extract<osmium::NodeRef> ref(o[i]); if (ref.check()) wnl_builder.add_node_ref(ref()); else wnl_builder.add_node_ref(boost::python::extract<osmium::object_id_type>(o[i])); } } void set_memberlist(const boost::python::object& o, osmium::builder::RelationBuilder *builder) { // original memberlist boost::python::extract<osmium::RelationMemberList&> oml(o); if (oml.check()) { if (oml().size() > 0) builder->add_item(oml()); return; } auto len = boost::python::len(o); if (len == 0) return; osmium::builder::RelationMemberListBuilder rml_builder(buffer, builder); for (int i = 0; i < len; ++i) { auto member = o[i]; auto type = osmium::char_to_item_type(boost::python::extract<const char*>(member[0])()[0]); auto id = boost::python::extract<osmium::object_id_type>(member[1])(); auto role = boost::python::extract<const char*>(member[2])(); rml_builder.add_member(type, id, role); } } osmium::Location get_location(const boost::python::object& o) { boost::python::extract<osmium::Location> ol(o); if (ol.check()) return ol; // default is a tuple with two floats return osmium::Location(boost::python::extract<float>(o[0]), boost::python::extract<float>(o[1])); } bool hasattr(const boost::python::object& obj, char const *attr) { return PyObject_HasAttrString(obj.ptr(), attr) && (obj.attr(attr) != boost::python::object()); } void flush_buffer() { buffer.commit(); if (buffer.committed() > buffer.capacity() - BUFFER_WRAP) { osmium::memory::Buffer new_buffer(buffer.capacity(), osmium::memory::Buffer::auto_grow::yes); using std::swap; swap(buffer, new_buffer); writer(std::move(new_buffer)); } } osmium::io::Writer writer; osmium::memory::Buffer buffer; }; #endif // PYOSMIUM_GENERIC_WRITER_HPP
Switch from deprecated functions in libosmium to their replacements.
Switch from deprecated functions in libosmium to their replacements.
C++
bsd-2-clause
osmcode/pyosmium,osmcode/pyosmium,osmcode/pyosmium
5cb231aa6115f9b58ec23009dbcc1be02bb30984
kpilot/kpilot/kpilotConfigWizard.cc
kpilot/kpilot/kpilotConfigWizard.cc
/* conduitConfigDialog.cc KPilot ** ** Copyright (C) 2004 by Dan Pilone ** Written 2004 by Reinhold Kainhofer ** ** This file defines a .ui-based configuration dialog for conduits. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ static const char *conduitconfigdialog_id = "$Id$"; //#include "options.h" #include <qpushbutton.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qlineedit.h> #include <kmessagebox.h> #include <kglobal.h> #include <klocale.h> #include <kconfigskeleton.h> #include "kpilotConfig.h" #include "options.h" #include "kpilotConfigWizard_base1.h" #include "kpilotConfigWizard_base2.h" #include "kpilotConfigWizard_base3.h" #include "kpilotConfigWizard.moc" ConfigWizard::ConfigWizard(QWidget *parent, const char *n) : KWizard(parent, n) { page1=new ConfigWizard_base1(this); addPage( page1, i18n("Select connection type") ); page2=new ConfigWizard_base2(this); addPage( page2, i18n("Pilot info") ); page3=new ConfigWizard_base3(this); addPage( page3, i18n("Application to sync with") ); setFinishEnabled( page3, true ); connect( page2->fProbeButton, SIGNAL( pressed() ), this, SLOT( probeHandheld() ) ); KPilotSettings::self()->readConfig(); page2->fUserName->setText( KPilotSettings::userName() ); page2->fDeviceName->setText( KPilotSettings::pilotDevice() ); page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() ); } ConfigWizard::~ConfigWizard() { } void ConfigWizard::accept() { FUNCTIONSETUP; QString username( page2->fUserName->text() ); QString devicename( page2->fDeviceName->text() ); // int devicetype( page1->fConnectionType->selectedId() ); enum eSyncApp { eAppKDE=0, eAppKontact, eAppEvolution } app; app=(eSyncApp)( page3->fAppType->selectedId() ); bool keepPermanently( page2->fPilotRunningPermanently->isChecked() ); #ifdef DEBUG DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl; #endif KPilotSettings::setPilotDevice( devicename ); KPilotSettings::setUserName(username); KPilotSettings::setEncoding("iso 8859-15"); KPilotSettings::setDockDaemon( true ); KPilotSettings::setKillDaemonAtExit( !keepPermanently); KPilotSettings::setQuitAfterSync( !keepPermanently ); KPilotSettings::setStartDaemonAtLogin( keepPermanently ); KPilotSettings::setSyncType(0); KPilotSettings::setFullSyncOnPCChange( true ); KPilotSettings::setConflictResolution(0); QStringList conduits = KPilotSettings::installedConduits(); // TODO: enable the right conduits #define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a) QString applicationName(i18n("general KDE-PIM")); APPEND_CONDUIT("internal_fileinstall"); APPEND_CONDUIT("todo-conduit"); APPEND_CONDUIT("vcal-conduit"); switch (app) { case eAppEvolution: applicationName=i18n("Gnome's PIM suite", "Evolution"); conduits.remove("knotes-conduit"); // TODO: Once the Evolution abook resource is finished, enable it... conduits.remove("abbrowser_conduit"); // TODO: settings for conduits break; case eAppKontact: applicationName=i18n("KDE's PIM suite", "Kontact"); case eAppKDE: default: APPEND_CONDUIT("knotes-conduit"); APPEND_CONDUIT("abbrowser_conduit"); // TODO: settings for conduits break; } KPilotSettings::setInstalledConduits( conduits ); #undef APPEND_CONDUIT KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n" "The remaining options in the config dialog are advanced options and can " "be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished")); KPilotSettings::self()->writeConfig(); QDialog::accept(); } // Devices to probe: // void ConfigWizard::probeHandheld() { // TODO KMessageBox::information(this, "Probing the handheld, not yet implemented", "Probing"); }
/* conduitConfigDialog.cc KPilot ** ** Copyright (C) 2004 by Dan Pilone ** Written 2004 by Reinhold Kainhofer ** ** This file defines a .ui-based configuration dialog for conduits. */ /* ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or ** (at your option) any later version. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU General Public License for more details. ** ** You should have received a copy of the GNU General Public License ** along with this program in a file called COPYING; if not, write to ** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, ** MA 02111-1307, USA. */ /* ** Bug reports and questions can be sent to [email protected] */ static const char *conduitconfigdialog_id = "$Id$"; //#include "options.h" #include <qpushbutton.h> #include <qbuttongroup.h> #include <qcheckbox.h> #include <qlineedit.h> #include <kmessagebox.h> #include <kglobal.h> #include <klocale.h> #include <kconfigskeleton.h> #include "kpilotConfig.h" #include "options.h" #include "kpilotConfigWizard_base1.h" #include "kpilotConfigWizard_base2.h" #include "kpilotConfigWizard_base3.h" #include "kpilotConfigWizard.moc" ConfigWizard::ConfigWizard(QWidget *parent, const char *n) : KWizard(parent, n) { page1=new ConfigWizard_base1(this); addPage( page1, i18n("Select connection type") ); page2=new ConfigWizard_base2(this); addPage( page2, i18n("Pilot info") ); page3=new ConfigWizard_base3(this); addPage( page3, i18n("Application to sync with") ); setFinishEnabled( page3, true ); connect( page2->fProbeButton, SIGNAL( pressed() ), this, SLOT( probeHandheld() ) ); KPilotSettings::self()->readConfig(); page2->fUserName->setText( KPilotSettings::userName() ); page2->fDeviceName->setText( KPilotSettings::pilotDevice() ); page2->fPilotRunningPermanently->setChecked( KPilotSettings::startDaemonAtLogin() ); } ConfigWizard::~ConfigWizard() { } void ConfigWizard::accept() { FUNCTIONSETUP; QString username( page2->fUserName->text() ); QString devicename( page2->fDeviceName->text() ); // int devicetype( page1->fConnectionType->selectedId() ); enum eSyncApp { eAppKDE=0, eAppKontact, eAppEvolution } app; app=(eSyncApp)( page3->fAppType->selectedId() ); bool keepPermanently( page2->fPilotRunningPermanently->isChecked() ); #ifdef DEBUG DEBUGCONDUIT<<fname<<"Keep permanently: "<<keepPermanently<<endl; #endif KPilotSettings::setPilotDevice( devicename ); KPilotSettings::setUserName(username); KPilotSettings::setEncoding("iso 8859-15"); KPilotSettings::setDockDaemon( true ); KPilotSettings::setKillDaemonAtExit( !keepPermanently); KPilotSettings::setQuitAfterSync( !keepPermanently ); KPilotSettings::setStartDaemonAtLogin( keepPermanently ); KPilotSettings::setSyncType(0); KPilotSettings::setFullSyncOnPCChange( true ); KPilotSettings::setConflictResolution(0); QStringList conduits = KPilotSettings::installedConduits(); // TODO: enable the right conduits #define APPEND_CONDUIT(a) if (!conduits.contains(a)) conduits.append(a) QString applicationName(i18n("general KDE-PIM")); APPEND_CONDUIT("internal_fileinstall"); APPEND_CONDUIT("todo-conduit"); APPEND_CONDUIT("vcal-conduit"); switch (app) { case eAppEvolution: applicationName=i18n("Gnome's PIM suite", "Evolution"); conduits.remove("knotes-conduit"); // TODO: Once the Evolution abook resource is finished, enable it... conduits.remove("abbrowser_conduit"); // TODO: settings for conduits break; case eAppKontact: applicationName=i18n("KDE's PIM suite", "Kontact"); case eAppKDE: default: APPEND_CONDUIT("knotes-conduit"); APPEND_CONDUIT("abbrowser_conduit"); // TODO: settings for conduits break; } KPilotSettings::setInstalledConduits( conduits ); #undef APPEND_CONDUIT KMessageBox::information(this, i18n("KPilot is now configured to sync with %1.\n" "The remaining options in the config dialog are advanced options and can " "be used to fine-tune KPilot.").arg(applicationName), i18n("Automatic configuration finished")); KPilotSettings::self()->writeConfig(); QDialog::accept(); } // Devices to probe: // Linux: /dev/pilot (symlink), /dev/ttyS* (serial + irda), /dev/tts/[012345...] (with devfs), // /dev/ttyUSB*, /dev/usb/tts/[012345...] // *BSD: /dev/pilot, /dev/cuaa[01] (serial), /dev/ucom* (usb) void ConfigWizard::probeHandheld() { // TODO KMessageBox::information(this, "Probing the handheld, not yet implemented", "Probing"); }
Add a comment about the devices we'll have to probe in the config wizard.
CVS_SILENT: Add a comment about the devices we'll have to probe in the config wizard. svn path=/trunk/kdepim/; revision=296846
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
2b1addbcc2e9e7553b7c54702c636085c3dbd091
src/Application/ConfigServer/ConfigDatabaseManager.cpp
src/Application/ConfigServer/ConfigDatabaseManager.cpp
#include "ConfigDatabaseManager.h" #include "Framework/Replication/Quorums/QuorumDatabase.h" #include "Framework/Storage/StoragePageCache.h" #include "System/Config.h" void ConfigDatabaseManager::Init() { Buffer envpath; envpath.Writef("%s", configFile.GetValue("database.dir", "db")); environment.Open(envpath); environment.config.numLogSegmentFileChunks = 0; environment.CreateShard(1, QUORUM_DATABASE_SYSTEM_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_STANDARD); environment.CreateShard(1, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_DUMP); environment.CreateShard(1, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_LOG); systemConfigShard.Init(&environment, QUORUM_DATABASE_SYSTEM_CONTEXT, 1); quorumPaxosShard.Init(&environment, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1); quorumLogShard.Init(&environment, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1); paxosID = 0; configState.Init(); Read(); SetControllers(); } void ConfigDatabaseManager::Shutdown() { environment.Close(); StoragePageCache::Shutdown(); } ConfigState* ConfigDatabaseManager::GetConfigState() { return &configState; } void ConfigDatabaseManager::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ConfigDatabaseManager::GetPaxosID() { return paxosID; } StorageShardProxy* ConfigDatabaseManager::GetSystemShard() { return &systemConfigShard; } StorageShardProxy* ConfigDatabaseManager::GetQuorumPaxosShard() { return &quorumPaxosShard; } StorageShardProxy* ConfigDatabaseManager::GetQuorumLogShard() { return &quorumLogShard; } bool ConfigDatabaseManager::ShardExists(uint64_t tableID, ReadBuffer firstKey) { ConfigShard* shard; FOREACH (shard, configState.shards) { if (shard->tableID == tableID && ReadBuffer::Cmp(firstKey, shard->firstKey) == 0) return true; } return false; } void ConfigDatabaseManager::Read() { bool ret; ReadBuffer value; int read; ret = true; if (!systemConfigShard.Get(ReadBuffer("state"), value)) { Log_Message("Starting with empty database..."); return; } read = value.Readf("%U:", &paxosID); if (read < 2) ASSERT_FAIL(); value.Advance(read); if (!configState.Read(value)) ASSERT_FAIL(); Log_Trace("%R", &value); } void ConfigDatabaseManager::Write() { writeBuffer.Writef("%U:", paxosID); configState.Write(writeBuffer); systemConfigShard.Set(ReadBuffer("state"), ReadBuffer(writeBuffer)); } void ConfigDatabaseManager::SetControllers() { unsigned num; uint64_t nodeID; ReadBuffer rb; ConfigController* controller; configState.controllers.DeleteList(); num = configFile.GetListNum("controllers"); for (nodeID = 0; nodeID < num; nodeID++) { controller = new ConfigController; controller->nodeID = nodeID; rb = configFile.GetListValue("controllers", nodeID, ""); controller->endpoint.Set(rb, true); configState.controllers.Append(controller); } }
#include "ConfigDatabaseManager.h" #include "Application/Common/ContextTransport.h" #include "Framework/Replication/Quorums/QuorumDatabase.h" #include "Framework/Storage/StoragePageCache.h" #include "System/Config.h" void ConfigDatabaseManager::Init() { Buffer envpath; envpath.Writef("%s", configFile.GetValue("database.dir", "db")); environment.Open(envpath); environment.config.numLogSegmentFileChunks = 0; environment.CreateShard(1, QUORUM_DATABASE_SYSTEM_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_STANDARD); environment.CreateShard(1, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_DUMP); environment.CreateShard(1, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1, 0, "", "", true, STORAGE_SHARD_TYPE_LOG); systemConfigShard.Init(&environment, QUORUM_DATABASE_SYSTEM_CONTEXT, 1); quorumPaxosShard.Init(&environment, QUORUM_DATABASE_QUORUM_PAXOS_CONTEXT, 1); quorumLogShard.Init(&environment, QUORUM_DATABASE_QUORUM_LOG_CONTEXT, 1); paxosID = 0; configState.Init(); Read(); SetControllers(); } void ConfigDatabaseManager::Shutdown() { environment.Close(); StoragePageCache::Shutdown(); } ConfigState* ConfigDatabaseManager::GetConfigState() { return &configState; } void ConfigDatabaseManager::SetPaxosID(uint64_t paxosID_) { paxosID = paxosID_; } uint64_t ConfigDatabaseManager::GetPaxosID() { return paxosID; } StorageShardProxy* ConfigDatabaseManager::GetSystemShard() { return &systemConfigShard; } StorageShardProxy* ConfigDatabaseManager::GetQuorumPaxosShard() { return &quorumPaxosShard; } StorageShardProxy* ConfigDatabaseManager::GetQuorumLogShard() { return &quorumLogShard; } bool ConfigDatabaseManager::ShardExists(uint64_t tableID, ReadBuffer firstKey) { ConfigShard* shard; FOREACH (shard, configState.shards) { if (shard->tableID == tableID && ReadBuffer::Cmp(firstKey, shard->firstKey) == 0) return true; } return false; } void ConfigDatabaseManager::Read() { bool ret; ReadBuffer value; int read; ret = true; if (!systemConfigShard.Get(ReadBuffer("state"), value)) { Log_Message("Starting with empty database..."); return; } read = value.Readf("%U:", &paxosID); if (read < 2) ASSERT_FAIL(); value.Advance(read); if (!configState.Read(value)) ASSERT_FAIL(); Log_Trace("%R", &value); } void ConfigDatabaseManager::Write() { writeBuffer.Writef("%U:", paxosID); configState.Write(writeBuffer); systemConfigShard.Set(ReadBuffer("state"), ReadBuffer(writeBuffer)); } void ConfigDatabaseManager::SetControllers() { unsigned num; uint64_t nodeID; ReadBuffer rb; ConfigController* controller; configState.controllers.DeleteList(); num = configFile.GetListNum("controllers"); for (nodeID = 0; nodeID < num; nodeID++) { controller = new ConfigController; controller->nodeID = nodeID; rb = configFile.GetListValue("controllers", nodeID, ""); controller->endpoint.Set(rb, true); controller->isConnected = CONTEXT_TRANSPORT->IsConnected(controller->nodeID); configState.controllers.Append(controller); } }
Set controller connectivity status after catchup. Fixes #333
Set controller connectivity status after catchup. Fixes #333
C++
agpl-3.0
scalien/scaliendb,scalien/scaliendb,timoc/scaliendb,scalien/scaliendb,scalien/scaliendb,scalien/scaliendb,scalien/scaliendb,timoc/scaliendb,scalien/scaliendb,timoc/scaliendb,timoc/scaliendb,timoc/scaliendb,timoc/scaliendb,timoc/scaliendb,scalien/scaliendb,timoc/scaliendb,timoc/scaliendb
7fca96939af0a97821c53f23b4bd6decc3815f8f
src/core/kext/Client.cpp
src/core/kext/Client.cpp
extern "C" { #include <sys/systm.h> #include <sys/un.h> #include <sys/kpi_socket.h> errno_t sock_nointerrupt(socket_t so, int on); } #include "Client.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { struct sockaddr_un sockaddr_; void releaseSocket(socket_t &socket) { errno_t error = sock_shutdown(socket, SHUT_RDWR); if (error) { printf("[KeyRemap4MacBook ERROR] sock_shutdown failed(%d)\n", error); } sock_close(socket); } bool makeSocket(socket_t &socket) { int error = sock_socket(PF_LOCAL, SOCK_STREAM, 0, NULL, NULL, &socket); if (error) { printf("[KeyRemap4MacBook ERROR] sock_socket failed(%d)\n", error); return false; } // ---------------------------------------- struct timeval tv; tv.tv_sec = KeyRemap4MacBook_client::TIMEOUT; tv.tv_usec = 0; error = sock_setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } error = sock_setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } return true; error: releaseSocket(socket); printf("KeyRemap4MacBook_client makeSocket failed(%d)\n", error); return false; } bool connectSocket(socket_t &socket) { errno_t error = sock_connect(socket, reinterpret_cast<const sockaddr *>(&sockaddr_), 0); if (error) { printf("[KeyRemap4MacBook ERROR] sock_connect failed(%d)\n", error); return false; } error = sock_nointerrupt(socket, TRUE); if (error) { printf("[KeyRemap4MacBook ERROR] sock_nointerrupt failed(%d)\n", error); return false; } return true; } } void KeyRemap4MacBook_client::initialize(void) { memset(&sockaddr_, 0, sizeof(sockaddr_)); sockaddr_.sun_len = sizeof(sockaddr_); sockaddr_.sun_family = AF_UNIX; strncpy(sockaddr_.sun_path, KeyRemap4MacBook_bridge::socketPath, sizeof(sockaddr_.sun_path) - 8); } int KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::RequestType type, void *request, size_t requestsize, void *reply, size_t replysize) { printf("[BEGIN] KeyRemap4MacBook_client::sendmsg\n"); socket_t socket; if (! makeSocket(socket)) { return EIO; } if (! connectSocket(socket)) { releaseSocket(socket); return EIO; } // ---------------------------------------- struct msghdr msg; memset(&msg, 0, sizeof(msg)); struct iovec aiov[3]; size_t iolen; aiov[0].iov_base = reinterpret_cast<caddr_t>(&type); aiov[0].iov_len = sizeof(type); if (requestsize <= 0) { msg.msg_iovlen = 1; } else { aiov[1].iov_base = reinterpret_cast<caddr_t>(&requestsize); aiov[1].iov_len = sizeof(requestsize); aiov[2].iov_base = reinterpret_cast<caddr_t>(request); aiov[2].iov_len = requestsize; msg.msg_iovlen = 3; } msg.msg_iov = aiov; int error = sock_send(socket, &msg, 0, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_send failed(%d)\n", error); releaseSocket(socket); return error; } // ---------------------------------------- memset(&msg, 0, sizeof(msg)); int result; aiov[0].iov_base = reinterpret_cast<caddr_t>(&result); aiov[0].iov_len = sizeof(result); aiov[1].iov_base = reinterpret_cast<caddr_t>(reply); aiov[1].iov_len = replysize; msg.msg_iov = aiov; msg.msg_iovlen = (replysize == 0 ? 1 : 2); for (;;) { error = sock_receive(socket, &msg, MSG_WAITALL, &iolen); if (error == EWOULDBLOCK) continue; if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_receive failed(%d)\n", error); } break; } releaseSocket(socket); if (error) { return error; } if (result) { printf("KeyRemap4MacBook_client::sendmsg error result (%d)\n", result); } return result; } }
extern "C" { #include <sys/systm.h> #include <sys/un.h> #include <sys/kpi_socket.h> errno_t sock_nointerrupt(socket_t so, int on); } #include "Client.hpp" namespace org_pqrs_KeyRemap4MacBook { namespace { struct sockaddr_un sockaddr_; void releaseSocket(socket_t &socket) { sock_shutdown(socket, SHUT_RDWR); sock_close(socket); } bool makeSocket(socket_t &socket) { int error = sock_socket(PF_LOCAL, SOCK_STREAM, 0, NULL, NULL, &socket); if (error) { printf("[KeyRemap4MacBook ERROR] sock_socket failed(%d)\n", error); return false; } // ---------------------------------------- struct timeval tv; tv.tv_sec = KeyRemap4MacBook_client::TIMEOUT; tv.tv_usec = 0; error = sock_setsockopt(socket, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } error = sock_setsockopt(socket, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(struct timeval)); if (error) { printf("[KeyRemap4MacBook ERROR] sock_setsockopt failed(%d)\n", error); goto error; } return true; error: releaseSocket(socket); printf("KeyRemap4MacBook_client makeSocket failed(%d)\n", error); return false; } bool connectSocket(socket_t &socket) { errno_t error = sock_connect(socket, reinterpret_cast<const sockaddr *>(&sockaddr_), 0); if (error) { printf("[KeyRemap4MacBook ERROR] sock_connect failed(%d)\n", error); return false; } error = sock_nointerrupt(socket, TRUE); if (error) { printf("[KeyRemap4MacBook ERROR] sock_nointerrupt failed(%d)\n", error); return false; } return true; } } void KeyRemap4MacBook_client::initialize(void) { memset(&sockaddr_, 0, sizeof(sockaddr_)); sockaddr_.sun_len = sizeof(sockaddr_); sockaddr_.sun_family = AF_UNIX; strncpy(sockaddr_.sun_path, KeyRemap4MacBook_bridge::socketPath, sizeof(sockaddr_.sun_path) - 8); } int KeyRemap4MacBook_client::sendmsg(KeyRemap4MacBook_bridge::RequestType type, void *request, size_t requestsize, void *reply, size_t replysize) { printf("[BEGIN] KeyRemap4MacBook_client::sendmsg\n"); socket_t socket; if (! makeSocket(socket)) { return EIO; } if (! connectSocket(socket)) { releaseSocket(socket); return EIO; } // ---------------------------------------- struct msghdr msg; memset(&msg, 0, sizeof(msg)); struct iovec aiov[3]; size_t iolen; aiov[0].iov_base = reinterpret_cast<caddr_t>(&type); aiov[0].iov_len = sizeof(type); if (requestsize <= 0) { msg.msg_iovlen = 1; } else { aiov[1].iov_base = reinterpret_cast<caddr_t>(&requestsize); aiov[1].iov_len = sizeof(requestsize); aiov[2].iov_base = reinterpret_cast<caddr_t>(request); aiov[2].iov_len = requestsize; msg.msg_iovlen = 3; } msg.msg_iov = aiov; int error = sock_send(socket, &msg, 0, &iolen); if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_send failed(%d)\n", error); releaseSocket(socket); return error; } // ---------------------------------------- memset(&msg, 0, sizeof(msg)); int result; aiov[0].iov_base = reinterpret_cast<caddr_t>(&result); aiov[0].iov_len = sizeof(result); aiov[1].iov_base = reinterpret_cast<caddr_t>(reply); aiov[1].iov_len = replysize; msg.msg_iov = aiov; msg.msg_iovlen = (replysize == 0 ? 1 : 2); for (;;) { error = sock_receive(socket, &msg, MSG_WAITALL, &iolen); if (error == EWOULDBLOCK) continue; if (error) { printf("KeyRemap4MacBook_client::sendmsg sock_receive failed(%d)\n", error); } break; } releaseSocket(socket); if (error) { return error; } if (result) { printf("KeyRemap4MacBook_client::sendmsg error result (%d)\n", result); } return result; } }
update src/core/kext/Client.cpp
update src/core/kext/Client.cpp
C++
unlicense
chzyer-dev/Karabiner,chzyer-dev/Karabiner,tekezo/Karabiner,tekezo/Karabiner,muramasa64/Karabiner,muramasa64/Karabiner,miaotaizi/Karabiner,wataash/Karabiner,chzyer-dev/Karabiner,e-gaulue/Karabiner,muramasa64/Karabiner,runarbu/Karabiner,e-gaulue/Karabiner,miaotaizi/Karabiner,e-gaulue/Karabiner,wataash/Karabiner,astachurski/Karabiner,astachurski/Karabiner,runarbu/Karabiner,miaotaizi/Karabiner,wataash/Karabiner,muramasa64/Karabiner,runarbu/Karabiner,runarbu/Karabiner,e-gaulue/Karabiner,miaotaizi/Karabiner,astachurski/Karabiner,wataash/Karabiner,tekezo/Karabiner,chzyer-dev/Karabiner,tekezo/Karabiner,astachurski/Karabiner
e36162fc98554abca39b8d302ad0e516673db7e2
test/event.cpp
test/event.cpp
/* * Copyright 2017 deepstreamHub GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <algorithm> #include <buffer.hpp> #include <event.hpp> #include <message.hpp> #include <message_builder.hpp> #include <scope_guard.hpp> namespace deepstream { BOOST_AUTO_TEST_CASE(simple) { int state = -1; const Event::Name name("name"); const std::string pattern("pattern"); auto send = [&state, name, pattern] (const Message& message) { if( state == -1 ) BOOST_FAIL( "Internal state is faulty" ); DEEPSTREAM_ON_EXIT( [&state] () { state = -1; } ); BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); if( state == 0 ) { BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 1 ) { BOOST_CHECK_EQUAL( message.action(), Action::LISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } if( state == 2 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNSUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 3 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNLISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } assert(0); return false; }; Event event(send); Event::SubscribeFn f = [] (const Buffer&) {}; Event::SubscribeFnPtr p1( new Event::SubscribeFn(f) ); Event::SubscribeFnPtr p2( new Event::SubscribeFn(f) ); state = 0; event.subscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); BOOST_CHECK_EQUAL( it->second.front(), p1 ); } event.subscribe(name, p2); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 2 ); } event.unsubscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); } BOOST_CHECK( event.listener_map_.empty() ); Event::ListenFn g = [] (const Event::Name&, const Buffer&) {}; Event::ListenFnPtr q1( new Event::ListenFn(g) ); Event::ListenFnPtr q2( new Event::ListenFn(g) ); state = 1; event.listen(pattern, q1); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } event.listen(pattern, q2); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); event.unsubscribe(name, p1); // we removed p1 above already BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); state = 2; event.unsubscribe(name, p2); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); state = 3; event.unlisten(pattern); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK( event.listener_map_.empty() ); } BOOST_AUTO_TEST_CASE(subscriber_notification) { const Event::Name name("name"); const Buffer data("data"); bool is_subscribed = false; auto send = [name, &is_subscribed] (const Message& message) -> bool { BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( std::equal(name.cbegin(), name.cend(), message[0].cbegin()) ); is_subscribed = true; return true; }; Event event(send); unsigned num_calls = 0; Event::SubscribeFn f = [data, &num_calls] (const Buffer& my_data) { BOOST_CHECK( std::equal(data.cbegin(), data.cend(), my_data.cbegin()) ); ++num_calls; }; Event::SubscribeFnPtr p_f = event.subscribe(name, f); BOOST_CHECK( p_f ); BOOST_CHECK( is_subscribed ); BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); MessageBuilder message(Topic::EVENT, Action::EVENT); message.add_argument(name); message.add_argument(data); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 1 ); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 2 ); } }
/* * Copyright 2017 deepstreamHub GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define BOOST_TEST_MAIN #include <boost/test/unit_test.hpp> #include <algorithm> #include <buffer.hpp> #include <event.hpp> #include <message.hpp> #include <message_builder.hpp> #include <scope_guard.hpp> namespace deepstream { BOOST_AUTO_TEST_CASE(simple) { int state = -1; const Event::Name name("name"); const std::string pattern("pattern"); auto send = [&state, name, pattern] (const Message& message) { if( state == -1 ) BOOST_FAIL( "Internal state is faulty" ); DEEPSTREAM_ON_EXIT( [&state] () { state = -1; } ); BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); if( state == 0 ) { BOOST_CHECK_EQUAL( message.action(), Action::SUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 1 ) { BOOST_CHECK_EQUAL( message.action(), Action::LISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } if( state == 2 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNSUBSCRIBE ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( name.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), name.cbegin()) ); return true; } if( state == 3 ) { BOOST_CHECK_EQUAL( message.action(), Action::UNLISTEN ); BOOST_CHECK( !message.is_ack() ); BOOST_REQUIRE_EQUAL( message.num_arguments(), 1 ); const Buffer& arg = message[0]; BOOST_REQUIRE_EQUAL( pattern.size(), arg.size() ); BOOST_CHECK( std::equal(arg.cbegin(), arg.cend(), pattern.cbegin()) ); return true; } assert(0); return false; }; Event event(send); Event::SubscribeFn f = [] (const Buffer&) {}; Event::SubscribeFnPtr p1( new Event::SubscribeFn(f) ); Event::SubscribeFnPtr p2( new Event::SubscribeFn(f) ); state = 0; event.subscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); BOOST_CHECK_EQUAL( it->second.front(), p1 ); } event.subscribe(name, p2); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 2 ); } event.unsubscribe(name, p1); { BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); auto it = event.subscriber_map_.find(name); BOOST_REQUIRE( it != event.subscriber_map_.end() ); BOOST_CHECK_EQUAL( it->second.size(), 1 ); } BOOST_CHECK( event.listener_map_.empty() ); Event::ListenFn g = [] (const Event::Name&, const Buffer&) {}; Event::ListenFnPtr q1( new Event::ListenFn(g) ); Event::ListenFnPtr q2( new Event::ListenFn(g) ); state = 1; event.listen(pattern, q1); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } event.listen(pattern, q2); { BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); auto it = event.listener_map_.find(pattern); BOOST_REQUIRE( it != event.listener_map_.end() ); BOOST_REQUIRE_EQUAL( it->first, pattern ); BOOST_REQUIRE_EQUAL( it->second, q1 ); } BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); event.unsubscribe(name, p1); // we removed p1 above already BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); state = 2; event.unsubscribe(name, p2); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK_EQUAL( event.listener_map_.size(), 1 ); state = 3; event.unlisten(pattern); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK( event.listener_map_.empty() ); } BOOST_AUTO_TEST_CASE(subscriber_notification) { const Event::Name name("name"); const Buffer data("data"); bool is_subscribed = false; auto send = [name, &is_subscribed] (const Message& message) -> bool { BOOST_CHECK_EQUAL( message.topic(), Topic::EVENT ); BOOST_CHECK( std::equal(name.cbegin(), name.cend(), message[0].cbegin()) ); if( message.action() == Action::SUBSCRIBE ) is_subscribed = true; else if( message.action() == Action::UNSUBSCRIBE ) is_subscribed = false; else BOOST_FAIL( "This branch should not be taken" ); return true; }; Event event(send); unsigned num_calls = 0; Event::SubscribeFn f = [data, &num_calls] (const Buffer& my_data) { BOOST_CHECK( std::equal(data.cbegin(), data.cend(), my_data.cbegin()) ); ++num_calls; }; Event::SubscribeFnPtr p_f = event.subscribe(name, f); BOOST_CHECK( p_f ); BOOST_CHECK( is_subscribed ); BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); MessageBuilder message(Topic::EVENT, Action::EVENT); message.add_argument(name); message.add_argument(data); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 1 ); Event::SubscribeFn g = [name, data, &num_calls, &event, &p_f] (const Buffer& my_data) { BOOST_CHECK( std::equal(data.cbegin(), data.cend(), my_data.cbegin()) ); num_calls += 10; event.unsubscribe(name, p_f); }; Event::SubscribeFnPtr p_g = event.subscribe(name, g); event.notify_(message); BOOST_CHECK_EQUAL( num_calls, 12 ); BOOST_CHECK_EQUAL( event.subscriber_map_.size(), 1 ); Event::SubscriberMap::const_iterator ci = event.subscriber_map_.cbegin(); const Event::SubscriberList& subscribers = ci->second; BOOST_CHECK_EQUAL( subscribers.size(), 1 ); BOOST_CHECK_EQUAL( subscribers.front(), p_g ); event.unsubscribe(name); BOOST_CHECK( event.subscriber_map_.empty() ); BOOST_CHECK( !is_subscribed ); } }
make existing event test harder
Test: make existing event test harder
C++
apache-2.0
deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp,deepstreamIO/deepstream.io-client-cpp
0818a2187bb9cdd9445ad4a2124d09f48e3f2b20
SDK/src/NDK/Entity.cpp
SDK/src/NDK/Entity.cpp
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Entity.hpp> #include <NDK/BaseComponent.hpp> #include <NDK/World.hpp> namespace Ndk { /*! * \ingroup NDK * \class Ndk::Entity * \brief NDK class that represents an entity in a world */ /*! * \brief Constructs a Entity object by move semantic * * \param entity Entity to move into this */ Entity::Entity(Entity&& entity) : HandledObject(std::move(entity)), m_components(std::move(entity.m_components)), m_componentBits(std::move(entity.m_componentBits)), m_systemBits(std::move(entity.m_systemBits)), m_id(entity.m_id), m_world(entity.m_world), m_enabled(entity.m_enabled), m_valid(entity.m_valid) { } /*! * \brief Constructs a Entity object linked to a world and with an id * * \param world World in which the entity interact * \param id Identifier of the entity */ Entity::Entity(World* world, EntityId id) : m_id(id), m_world(world) { } /*! * \brief Destructs the object and calls Destroy * * \see Destroy */ Entity::~Entity() { Destroy(); } /*! * \brief Adds a component to the entity * \return A reference to the newly added component * * \param componentPtr Component to add to the entity * * \remark Produces a NazaraAssert if component is nullptr */ BaseComponent& Entity::AddComponent(std::unique_ptr<BaseComponent>&& componentPtr) { NazaraAssert(componentPtr, "Component must be valid"); ComponentIndex index = componentPtr->GetIndex(); // We ensure that the vector has enough space if (index >= m_components.size()) m_components.resize(index + 1); // Affectation and return of the component m_components[index] = std::move(componentPtr); m_componentBits.UnboundedSet(index); m_removedComponentBits.UnboundedReset(index); Invalidate(); // We get the new component and we alert other existing components of the new one BaseComponent& component = *m_components[index].get(); component.SetEntity(this); for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) { if (i != index) m_components[i]->OnComponentAttached(component); } return component; } /*! * \brief Clones the entity * \return The clone newly created * * \remark The close is enable by default, even if the original is disabled * \remark Produces a NazaraAssert if the entity is not valid */ const EntityHandle& Entity::Clone() const { NazaraAssert(IsValid(), "Invalid entity"); return m_world->CloneEntity(m_id); } /*! * \brief Kills the entity */ void Entity::Kill() { m_world->KillEntity(this); } /*! * \brief Invalidates the entity */ void Entity::Invalidate() { // We alert everyone that we have been updated m_world->Invalidate(m_id); } /*! * \brief Creates the entity */ void Entity::Create() { m_enabled = true; m_valid = true; } /*! * \brief Destroys the entity */ void Entity::Destroy() { OnEntityDestruction(this); OnEntityDestruction.Clear(); // We prepare components for entity destruction (some components needs this to handle some final callbacks while the entity is still valid) for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) m_components[i]->OnEntityDestruction(); // We alert each system for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) { auto sysIndex = static_cast<Ndk::SystemIndex>(index); if (m_world->HasSystem(sysIndex)) { BaseSystem& system = m_world->GetSystem(sysIndex); system.RemoveEntity(this); } } m_systemBits.Clear(); // We properly destroy each component for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) m_components[i]->SetEntity(nullptr); m_components.clear(); m_componentBits.Reset(); // And then free every handle UnregisterAllHandles(); m_valid = false; } /*! * \brief Destroys a component by index * * \param index Index of the component * * \remark If component is not available, no action is performed */ void Entity::DestroyComponent(ComponentIndex index) { if (HasComponent(index)) { // We get the component and we alert existing components of the deleted one BaseComponent& component = *m_components[index].get(); for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) { if (i != index) m_components[i]->OnComponentDetached(component); } component.SetEntity(nullptr); m_components[index].reset(); m_componentBits.Reset(index); } } }
// Copyright (C) 2017 Jérôme Leclercq // This file is part of the "Nazara Development Kit" // For conditions of distribution and use, see copyright notice in Prerequesites.hpp #include <NDK/Entity.hpp> #include <NDK/BaseComponent.hpp> #include <NDK/World.hpp> namespace Ndk { /*! * \ingroup NDK * \class Ndk::Entity * \brief NDK class that represents an entity in a world */ /*! * \brief Constructs a Entity object by move semantic * * \param entity Entity to move into this */ Entity::Entity(Entity&& entity) : HandledObject(std::move(entity)), m_components(std::move(entity.m_components)), m_componentBits(std::move(entity.m_componentBits)), m_systemBits(std::move(entity.m_systemBits)), m_id(entity.m_id), m_world(entity.m_world), m_enabled(entity.m_enabled), m_valid(entity.m_valid) { } /*! * \brief Constructs a Entity object linked to a world and with an id * * \param world World in which the entity interact * \param id Identifier of the entity */ Entity::Entity(World* world, EntityId id) : m_id(id), m_world(world) { } /*! * \brief Destructs the object and calls Destroy * * \see Destroy */ Entity::~Entity() { Destroy(); } /*! * \brief Adds a component to the entity * \return A reference to the newly added component * * \param componentPtr Component to add to the entity * * \remark Produces a NazaraAssert if component is nullptr */ BaseComponent& Entity::AddComponent(std::unique_ptr<BaseComponent>&& componentPtr) { NazaraAssert(componentPtr, "Component must be valid"); ComponentIndex index = componentPtr->GetIndex(); // We ensure that the vector has enough space if (index >= m_components.size()) m_components.resize(index + 1); // Affectation and return of the component m_components[index] = std::move(componentPtr); m_componentBits.UnboundedSet(index); m_removedComponentBits.UnboundedReset(index); Invalidate(); // We get the new component and we alert other existing components of the new one BaseComponent& component = *m_components[index].get(); component.SetEntity(this); for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) { if (i != index) m_components[i]->OnComponentAttached(component); } return component; } /*! * \brief Clones the entity * \return The clone newly created * * \remark The close is enable by default, even if the original is disabled * \remark Produces a NazaraAssert if the entity is not valid */ const EntityHandle& Entity::Clone() const { NazaraAssert(IsValid(), "Invalid entity"); return m_world->CloneEntity(m_id); } /*! * \brief Kills the entity */ void Entity::Kill() { m_world->KillEntity(this); } /*! * \brief Invalidates the entity */ void Entity::Invalidate() { // We alert everyone that we have been updated m_world->Invalidate(m_id); } /*! * \brief Creates the entity */ void Entity::Create() { m_enabled = true; m_valid = true; } /*! * \brief Destroys the entity */ void Entity::Destroy() { OnEntityDestruction(this); OnEntityDestruction.Clear(); // We prepare components for entity destruction (some components needs this to handle some final callbacks while the entity is still valid) for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) m_components[i]->OnEntityDestruction(); // Detach components while they're still attached to systems for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) m_components[i]->SetEntity(nullptr); // We alert each system for (std::size_t index = m_systemBits.FindFirst(); index != m_systemBits.npos; index = m_systemBits.FindNext(index)) { auto sysIndex = static_cast<Ndk::SystemIndex>(index); if (m_world->HasSystem(sysIndex)) { BaseSystem& system = m_world->GetSystem(sysIndex); system.RemoveEntity(this); } } m_systemBits.Clear(); // Destroy components m_components.clear(); m_componentBits.Reset(); // And then free every handle UnregisterAllHandles(); m_valid = false; } /*! * \brief Destroys a component by index * * \param index Index of the component * * \remark If component is not available, no action is performed */ void Entity::DestroyComponent(ComponentIndex index) { if (HasComponent(index)) { // We get the component and we alert existing components of the deleted one BaseComponent& component = *m_components[index].get(); for (std::size_t i = m_componentBits.FindFirst(); i != m_componentBits.npos; i = m_componentBits.FindNext(i)) { if (i != index) m_components[i]->OnComponentDetached(component); } component.SetEntity(nullptr); m_components[index].reset(); m_componentBits.Reset(index); } } }
Fix OnDetached being called after OnEntityRemove when destructing
Sdk/Entity: Fix OnDetached being called after OnEntityRemove when destructing
C++
mit
DigitalPulseSoftware/NazaraEngine
e1d991dce721e5069df3c0cb75d7d36bfa58fc62
src/Modulator/BPSK/Modulator_BPSK.cpp
src/Modulator/BPSK/Modulator_BPSK.cpp
#include "Modulator_BPSK.hpp" template <typename B, typename R, typename Q> Modulator_BPSK<B,R,Q> ::Modulator_BPSK(const int N, const R sigma, const bool disable_sig2, const int n_frames, const std::string name) : Modulator<B,R,Q>(N, n_frames, name), disable_sig2(disable_sig2), two_on_square_sigma((R)2.0 / (sigma * sigma)) { } template <typename B, typename R, typename Q> Modulator_BPSK<B,R,Q> ::~Modulator_BPSK() { } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::modulate(const mipp::vector<B>& X_N1, mipp::vector<R>& X_N2) { auto size = X_N1.size(); for (unsigned i = 0; i < size; i++) X_N2[i] = 1 - (X_N1[i] + X_N1[i]); // (X_N[i] == 1) ? -1 : +1 } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::demodulate(const mipp::vector<Q>& Y_N1, mipp::vector<Q>& Y_N2) { assert(typeid(R) == typeid(Q)); assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double)); if (disable_sig2) Y_N2 = Y_N1; else { auto size = Y_N1.size(); for (unsigned i = 0; i < size; i++) Y_N2[i] = Y_N1[i] * two_on_square_sigma; } } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::demodulate(const mipp::vector<Q>& Y_N1, const mipp::vector<Q>& Y_N2, mipp::vector<Q>& Y_N3) { assert(typeid(R) == typeid(Q)); assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double)); auto size = Y_N1.size(); if (disable_sig2) for (unsigned i = 0; i < size; i++) Y_N3[i] = Y_N1[i] + Y_N2[i]; else for (unsigned i = 0; i < size; i++) Y_N3[i] = (Y_N1[i] * two_on_square_sigma) + Y_N2[i]; } // ==================================================================================== explicit template instantiation #include "../../Tools/types.h" #ifdef MULTI_PREC template struct Modulator_BPSK<B_8,R_8,R_8>; template struct Modulator_BPSK<B_8,R_8,Q_8>; template struct Modulator_BPSK<B_16,R_16,R_16>; template struct Modulator_BPSK<B_16,R_16,Q_16>; template struct Modulator_BPSK<B_32,R_32,R_32>; template struct Modulator_BPSK<B_64,R_64,R_64>; #else template struct Modulator_BPSK<B,R,Q>; #if !defined(PREC_32_BIT) && !defined(PREC_64_BIT) template struct Modulator_BPSK<B,R,R>; #endif #endif // ==================================================================================== explicit template instantiation
#include "Modulator_BPSK.hpp" template <typename B, typename R, typename Q> Modulator_BPSK<B,R,Q> ::Modulator_BPSK(const int N, const R sigma, const bool disable_sig2, const int n_frames, const std::string name) : Modulator<B,R,Q>(N, n_frames, name), disable_sig2(disable_sig2), two_on_square_sigma((R)2.0 / (sigma * sigma)) { } template <typename B, typename R, typename Q> Modulator_BPSK<B,R,Q> ::~Modulator_BPSK() { } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::modulate(const mipp::vector<B>& X_N1, mipp::vector<R>& X_N2) { auto size = X_N1.size(); for (unsigned i = 0; i < size; i++) X_N2[i] = 1 - (X_N1[i] + X_N1[i]); // (X_N[i] == 1) ? -1 : +1 } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::demodulate(const mipp::vector<Q>& Y_N1, mipp::vector<Q>& Y_N2) { assert(typeid(R) == typeid(Q)); assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double)); if (disable_sig2) Y_N2 = Y_N1; else { auto size = Y_N1.size(); for (unsigned i = 0; i < size; i++) Y_N2[i] = Y_N1[i] * two_on_square_sigma; } } template <typename B, typename R, typename Q> void Modulator_BPSK<B,R,Q> ::demodulate(const mipp::vector<Q>& Y_N1, const mipp::vector<Q>& Y_N2, mipp::vector<Q>& Y_N3) { assert(typeid(R) == typeid(Q)); assert(typeid(Q) == typeid(float) || typeid(Q) == typeid(double)); auto size = Y_N1.size(); if (disable_sig2) for (unsigned i = 0; i < size; i++) Y_N3[i] = Y_N1[i] + Y_N2[i]; else for (unsigned i = 0; i < size; i++) Y_N3[i] = (Y_N1[i] * two_on_square_sigma) + Y_N2[i]; } // ==================================================================================== explicit template instantiation #include "../../Tools/types.h" #ifdef MULTI_PREC template class Modulator_BPSK<B_8,R_8,R_8>; template class Modulator_BPSK<B_8,R_8,Q_8>; template class Modulator_BPSK<B_16,R_16,R_16>; template class Modulator_BPSK<B_16,R_16,Q_16>; template class Modulator_BPSK<B_32,R_32,R_32>; template class Modulator_BPSK<B_64,R_64,R_64>; #else template class Modulator_BPSK<B,R,Q>; #if !defined(PREC_32_BIT) && !defined(PREC_64_BIT) template class Modulator_BPSK<B,R,R>; #endif #endif // ==================================================================================== explicit template instantiation
Fix warnings.
Fix warnings.
C++
mit
aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct,aff3ct/aff3ct
4dff4f724b5a9298099335ebc561afe42ad579c1
src/Nazara/Utility/X11/CursorImpl.cpp
src/Nazara/Utility/X11/CursorImpl.cpp
// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Utility/X11/CursorImpl.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Utility/Image.hpp> #include <Nazara/Utility/PixelFormat.hpp> #include <Nazara/Utility/X11/Display.hpp> #include <xcb/xcb_image.h> #include <xcb/xcb_renderutil.h> #include <Nazara/Utility/Debug.hpp> namespace Nz { bool CursorImpl::Create(const Image& cursor, int hotSpotX, int hotSpotY) { Image cursorImage(cursor); // Vive le COW if (!cursorImage.Convert(Nz::PixelFormatType_BGRA8)) { NazaraError("Failed to convert cursor to BGRA8"); return false; } auto width = cursorImage.GetWidth(); auto height = cursorImage.GetHeight(); ScopedXCBConnection connection; xcb_screen_t* screen = X11::XCBDefaultScreen(connection); ScopedXCB<xcb_generic_error_t> error(nullptr); ScopedXCB<xcb_render_query_pict_formats_reply_t> formatsReply = xcb_render_query_pict_formats_reply( connection, xcb_render_query_pict_formats(connection), &error); if (!formatsReply || error) { NazaraError("Failed to get pict formats"); return false; } xcb_render_pictforminfo_t* fmt = xcb_render_util_find_standard_format( formatsReply.get(), XCB_PICT_STANDARD_ARGB_32); if (!fmt) { NazaraError("Failed to find format PICT_STANDARD_ARGB_32"); return false; } xcb_image_t* xi = xcb_image_create( width, height, XCB_IMAGE_FORMAT_Z_PIXMAP, 32, 32, 32, 32, XCB_IMAGE_ORDER_LSB_FIRST, XCB_IMAGE_ORDER_MSB_FIRST, 0, 0, 0); if (!xi) { NazaraError("Failed to create image for cursor"); return false; } std::unique_ptr<uint8_t[]> data(new uint8_t[xi->stride * height]); if (!data) { xcb_image_destroy(xi); NazaraError("Failed to allocate memory for cursor image"); return false; } xi->data = data.get(); std::copy(cursorImage.GetConstPixels(), cursorImage.GetConstPixels() + cursorImage.GetBytesPerPixel() * width * height, xi->data); xcb_render_picture_t pic = XCB_NONE; CallOnExit onExit([&](){ xcb_image_destroy(xi); if (pic != XCB_NONE) xcb_render_free_picture(connection, pic); }); XCBPixmap pix(connection); if (!pix.Create(32, screen->root, width, height)) { NazaraError("Failed to create pixmap for cursor"); return false; } pic = xcb_generate_id(connection); if (!X11::CheckCookie( connection, xcb_render_create_picture( connection, pic, pix, fmt->id, 0, nullptr ))) { NazaraError("Failed to create render picture for cursor"); return false; } XCBGContext gc(connection); if (!gc.Create(pix, 0, nullptr)) { NazaraError("Failed to create gcontext for cursor"); return false; } if (!X11::CheckCookie( connection, xcb_image_put( connection, pix, gc, xi, 0, 0, 0 ))) { NazaraError("Failed to put image for cursor"); return false; } m_cursor = xcb_generate_id(connection); if (!X11::CheckCookie( connection, xcb_render_create_cursor( connection, m_cursor, pic, hotSpotX, hotSpotY ))) { NazaraError("Failed to create cursor"); return false; } return true; } void CursorImpl::Destroy() { ScopedXCBConnection connection; xcb_free_cursor(connection, m_cursor); m_cursor = 0; } xcb_cursor_t CursorImpl::GetCursor() { return m_cursor; } }
// Copyright (C) 2015 Jérôme Leclercq // This file is part of the "Nazara Engine - Utility module" // For conditions of distribution and use, see copyright notice in Config.hpp #include <Nazara/Utility/X11/CursorImpl.hpp> #include <Nazara/Core/CallOnExit.hpp> #include <Nazara/Core/Error.hpp> #include <Nazara/Utility/Image.hpp> #include <Nazara/Utility/PixelFormat.hpp> #include <Nazara/Utility/X11/Display.hpp> #include <xcb/xcb_image.h> // Some older versions of xcb/util-renderutil (notably the one available on Travis CI) use `template` as an argument name // This is a fixed bug (https://cgit.freedesktop.org/xcb/util-renderutil/commit/?id=8d15acc45a47dc4c922eee5b99885db42bc62c17) but until Travis-CI // has upgraded their Ubuntu version, I'm forced to use this ugly trick. #define template ptemplate #include <xcb/xcb_renderutil.h> #undef template #include <Nazara/Utility/Debug.hpp> namespace Nz { bool CursorImpl::Create(const Image& cursor, int hotSpotX, int hotSpotY) { Image cursorImage(cursor); // Vive le COW if (!cursorImage.Convert(Nz::PixelFormatType_BGRA8)) { NazaraError("Failed to convert cursor to BGRA8"); return false; } auto width = cursorImage.GetWidth(); auto height = cursorImage.GetHeight(); ScopedXCBConnection connection; xcb_screen_t* screen = X11::XCBDefaultScreen(connection); ScopedXCB<xcb_generic_error_t> error(nullptr); ScopedXCB<xcb_render_query_pict_formats_reply_t> formatsReply = xcb_render_query_pict_formats_reply( connection, xcb_render_query_pict_formats(connection), &error); if (!formatsReply || error) { NazaraError("Failed to get pict formats"); return false; } xcb_render_pictforminfo_t* fmt = xcb_render_util_find_standard_format( formatsReply.get(), XCB_PICT_STANDARD_ARGB_32); if (!fmt) { NazaraError("Failed to find format PICT_STANDARD_ARGB_32"); return false; } xcb_image_t* xi = xcb_image_create( width, height, XCB_IMAGE_FORMAT_Z_PIXMAP, 32, 32, 32, 32, XCB_IMAGE_ORDER_LSB_FIRST, XCB_IMAGE_ORDER_MSB_FIRST, 0, 0, 0); if (!xi) { NazaraError("Failed to create image for cursor"); return false; } std::unique_ptr<uint8_t[]> data(new uint8_t[xi->stride * height]); if (!data) { xcb_image_destroy(xi); NazaraError("Failed to allocate memory for cursor image"); return false; } xi->data = data.get(); std::copy(cursorImage.GetConstPixels(), cursorImage.GetConstPixels() + cursorImage.GetBytesPerPixel() * width * height, xi->data); xcb_render_picture_t pic = XCB_NONE; CallOnExit onExit([&](){ xcb_image_destroy(xi); if (pic != XCB_NONE) xcb_render_free_picture(connection, pic); }); XCBPixmap pix(connection); if (!pix.Create(32, screen->root, width, height)) { NazaraError("Failed to create pixmap for cursor"); return false; } pic = xcb_generate_id(connection); if (!X11::CheckCookie( connection, xcb_render_create_picture( connection, pic, pix, fmt->id, 0, nullptr ))) { NazaraError("Failed to create render picture for cursor"); return false; } XCBGContext gc(connection); if (!gc.Create(pix, 0, nullptr)) { NazaraError("Failed to create gcontext for cursor"); return false; } if (!X11::CheckCookie( connection, xcb_image_put( connection, pix, gc, xi, 0, 0, 0 ))) { NazaraError("Failed to put image for cursor"); return false; } m_cursor = xcb_generate_id(connection); if (!X11::CheckCookie( connection, xcb_render_create_cursor( connection, m_cursor, pic, hotSpotX, hotSpotY ))) { NazaraError("Failed to create cursor"); return false; } return true; } void CursorImpl::Destroy() { ScopedXCBConnection connection; xcb_free_cursor(connection, m_cursor); m_cursor = 0; } xcb_cursor_t CursorImpl::GetCursor() { return m_cursor; } }
Fix xcb_renderutil.h compile error on olders systems (Travis CI for example)
Utility/X11: Fix xcb_renderutil.h compile error on olders systems (Travis CI for example) Former-commit-id: d244d237356fa61293e8af28654a97df3f127de6 [formerly 348621c8a478a8b2f286b5fcb02b687e10216294] [formerly 25deef8c480e56fe2d2e0f1f8a22b942ace56ef6 [formerly e936f13a7c07985663fc0d35e4d0332a7aad6762]] Former-commit-id: f419ba91ab932b4695632bf2bf6e13cb2d396ffb [formerly 4d66289f24743ce633846a33207a46be5b97f307] Former-commit-id: 38f18e32f5e7154f8bbad8869559279ae268ddee
C++
mit
DigitalPulseSoftware/NazaraEngine
7c2f3f7af1ebf6ca88780271e0d6f0f8147c3a33
src/cpp/server/server.cc
src/cpp/server/server.cc
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google 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. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include "src/cpp/proto/proto_utils.h" namespace grpc { Server::Server(ThreadPoolInterface *thread_pool, bool thread_pool_owned, ServerCredentials *creds) : started_(false), shutdown_(false), num_running_cb_(0), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned), secure_(creds != nullptr) { if (creds) { server_ = grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr); } else { server_ = grpc_server_create(cq_.cq(), nullptr); } } Server::Server() { // Should not be called. GPR_ASSERT(false); } Server::~Server() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } else { lock.unlock(); } grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } } bool Server::RegisterService(RpcService *service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod *method = service->GetMethod(i); void *tag = grpc_server_register_method(server_, method->name(), nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } methods_.emplace_back(method, tag); } return true; } int Server::AddPort(const grpc::string &addr) { GPR_ASSERT(!started_); if (secure_) { return grpc_server_add_secure_http2_port(server_, addr.c_str()); } else { return grpc_server_add_http2_port(server_, addr.c_str()); } } class Server::MethodRequestData final : public CompletionQueueTag { public: MethodRequestData(RpcServiceMethod *method, void *tag) : method_(method), tag_(tag), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::CLIENT_STREAMING) { grpc_metadata_array_init(&request_metadata_); } static MethodRequestData *Wait(CompletionQueue *cq, bool *ok) { void *tag; if (!cq->Next(&tag, ok)) { return nullptr; } auto *mrd = static_cast<MethodRequestData *>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void Request(grpc_server *server) { GPR_ASSERT(!in_flight_); in_flight_ = true; cq_ = grpc_completion_queue_create(); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, this)); } void FinalizeResult(void **tag, bool *status) override {} class CallData { public: explicit CallData(MethodRequestData *mrd) : cq_(mrd->cq_), call_(mrd->call_, nullptr, &cq_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), has_response_payload_(mrd->has_response_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } void Run() { std::unique_ptr<google::protobuf::Message> req; std::unique_ptr<google::protobuf::Message> res; if (has_request_payload_) { req.reset(method_->AllocateRequestProto()); if (!DeserializeProto(request_payload_, req.get())) { abort(); // for now } } if (has_response_payload_) { req.reset(method_->AllocateResponseProto()); } auto status = method_->handler()->RunHandler( MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get())); CallOpBuffer buf; buf.AddServerSendStatus(nullptr, status); if (has_response_payload_) { buf.AddSendMessage(*res); } call_.PerformOps(&buf); GPR_ASSERT(cq_.Pluck(&buf)); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; const bool has_response_payload_; grpc_byte_buffer *request_payload_; RpcServiceMethod *const method_; }; private: RpcServiceMethod *const method_; void *const tag_; bool in_flight_ = false; const bool has_request_payload_; const bool has_response_payload_; grpc_call *call_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer *request_payload_; grpc_completion_queue *cq_; }; bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); // Start processing rpcs. if (!methods_.empty()) { for (auto &m : methods_) { m.Request(server_); } ScheduleCallback(); } return true; } void Server::Shutdown() { { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown(server_); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } } void Server::ScheduleCallback() { { std::unique_lock<std::mutex> lock(mu_); num_running_cb_++; } thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto *mrd = MethodRequestData::Wait(&cq_, &ok); if (mrd) { MethodRequestData::CallData cd(mrd); if (ok) { mrd->Request(server_); ScheduleCallback(); cd.Run(); } } { std::unique_lock<std::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc
/* * * Copyright 2014, Google Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google 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. * */ #include <grpc++/server.h> #include <utility> #include <grpc/grpc.h> #include <grpc/grpc_security.h> #include <grpc/support/log.h> #include <grpc++/completion_queue.h> #include <grpc++/impl/rpc_service_method.h> #include <grpc++/server_context.h> #include <grpc++/server_credentials.h> #include <grpc++/thread_pool_interface.h> #include "src/cpp/proto/proto_utils.h" namespace grpc { Server::Server(ThreadPoolInterface *thread_pool, bool thread_pool_owned, ServerCredentials *creds) : started_(false), shutdown_(false), num_running_cb_(0), thread_pool_(thread_pool), thread_pool_owned_(thread_pool_owned), secure_(creds != nullptr) { if (creds) { server_ = grpc_secure_server_create(creds->GetRawCreds(), cq_.cq(), nullptr); } else { server_ = grpc_server_create(cq_.cq(), nullptr); } } Server::Server() { // Should not be called. GPR_ASSERT(false); } Server::~Server() { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { lock.unlock(); Shutdown(); } else { lock.unlock(); } grpc_server_destroy(server_); if (thread_pool_owned_) { delete thread_pool_; } } bool Server::RegisterService(RpcService *service) { for (int i = 0; i < service->GetMethodCount(); ++i) { RpcServiceMethod *method = service->GetMethod(i); void *tag = grpc_server_register_method(server_, method->name(), nullptr); if (!tag) { gpr_log(GPR_DEBUG, "Attempt to register %s multiple times", method->name()); return false; } methods_.emplace_back(method, tag); } return true; } int Server::AddPort(const grpc::string &addr) { GPR_ASSERT(!started_); if (secure_) { return grpc_server_add_secure_http2_port(server_, addr.c_str()); } else { return grpc_server_add_http2_port(server_, addr.c_str()); } } class Server::MethodRequestData final : public CompletionQueueTag { public: MethodRequestData(RpcServiceMethod *method, void *tag) : method_(method), tag_(tag), has_request_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::SERVER_STREAMING), has_response_payload_(method->method_type() == RpcMethod::NORMAL_RPC || method->method_type() == RpcMethod::CLIENT_STREAMING) { grpc_metadata_array_init(&request_metadata_); } static MethodRequestData *Wait(CompletionQueue *cq, bool *ok) { void *tag; if (!cq->Next(&tag, ok)) { return nullptr; } auto *mrd = static_cast<MethodRequestData *>(tag); GPR_ASSERT(mrd->in_flight_); return mrd; } void Request(grpc_server *server) { GPR_ASSERT(!in_flight_); in_flight_ = true; cq_ = grpc_completion_queue_create(); GPR_ASSERT(GRPC_CALL_OK == grpc_server_request_registered_call( server, tag_, &call_, &deadline_, &request_metadata_, has_request_payload_ ? &request_payload_ : nullptr, cq_, this)); } void FinalizeResult(void **tag, bool *status) override {} class CallData { public: explicit CallData(MethodRequestData *mrd) : cq_(mrd->cq_), call_(mrd->call_, nullptr, &cq_), ctx_(mrd->deadline_, mrd->request_metadata_.metadata, mrd->request_metadata_.count), has_request_payload_(mrd->has_request_payload_), has_response_payload_(mrd->has_response_payload_), request_payload_(mrd->request_payload_), method_(mrd->method_) { GPR_ASSERT(mrd->in_flight_); mrd->in_flight_ = false; mrd->request_metadata_.count = 0; } void Run() { std::unique_ptr<google::protobuf::Message> req; std::unique_ptr<google::protobuf::Message> res; if (has_request_payload_) { req.reset(method_->AllocateRequestProto()); if (!DeserializeProto(request_payload_, req.get())) { abort(); // for now } } if (has_response_payload_) { res.reset(method_->AllocateResponseProto()); } auto status = method_->handler()->RunHandler( MethodHandler::HandlerParameter(&call_, &ctx_, req.get(), res.get())); CallOpBuffer buf; buf.AddServerSendStatus(nullptr, status); if (has_response_payload_) { buf.AddSendMessage(*res); } call_.PerformOps(&buf); GPR_ASSERT(cq_.Pluck(&buf)); } private: CompletionQueue cq_; Call call_; ServerContext ctx_; const bool has_request_payload_; const bool has_response_payload_; grpc_byte_buffer *request_payload_; RpcServiceMethod *const method_; }; private: RpcServiceMethod *const method_; void *const tag_; bool in_flight_ = false; const bool has_request_payload_; const bool has_response_payload_; grpc_call *call_; gpr_timespec deadline_; grpc_metadata_array request_metadata_; grpc_byte_buffer *request_payload_; grpc_completion_queue *cq_; }; bool Server::Start() { GPR_ASSERT(!started_); started_ = true; grpc_server_start(server_); // Start processing rpcs. if (!methods_.empty()) { for (auto &m : methods_) { m.Request(server_); } ScheduleCallback(); } return true; } void Server::Shutdown() { { std::unique_lock<std::mutex> lock(mu_); if (started_ && !shutdown_) { shutdown_ = true; grpc_server_shutdown(server_); // Wait for running callbacks to finish. while (num_running_cb_ != 0) { callback_cv_.wait(lock); } } } } void Server::ScheduleCallback() { { std::unique_lock<std::mutex> lock(mu_); num_running_cb_++; } thread_pool_->ScheduleCallback(std::bind(&Server::RunRpc, this)); } void Server::RunRpc() { // Wait for one more incoming rpc. bool ok; auto *mrd = MethodRequestData::Wait(&cq_, &ok); if (mrd) { MethodRequestData::CallData cd(mrd); if (ok) { mrd->Request(server_); ScheduleCallback(); cd.Run(); } } { std::unique_lock<std::mutex> lock(mu_); num_running_cb_--; if (shutdown_) { callback_cv_.notify_all(); } } } } // namespace grpc
Fix typo causing crash
Fix typo causing crash
C++
apache-2.0
vjpai/grpc,apolcyn/grpc,a-veitch/grpc,kpayson64/grpc,firebase/grpc,carl-mastrangelo/grpc,andrewpollock/grpc,fichter/grpc,wcevans/grpc,matt-kwong/grpc,fichter/grpc,matt-kwong/grpc,miselin/grpc,soltanmm-google/grpc,pmarks-net/grpc,msiedlarek/grpc,matt-kwong/grpc,bogdandrutu/grpc,andrewpollock/grpc,carl-mastrangelo/grpc,chenbaihu/grpc,grpc/grpc,zeliard/grpc,daniel-j-born/grpc,ncteisen/grpc,doubi-workshop/grpc,nicolasnoble/grpc,yang-g/grpc,murgatroid99/grpc,infinit/grpc,tamihiro/grpc,grani/grpc,Crevil/grpc,vsco/grpc,dklempner/grpc,yongni/grpc,soltanmm-google/grpc,msmania/grpc,doubi-workshop/grpc,kskalski/grpc,nathanielmanistaatgoogle/grpc,mehrdada/grpc,bogdandrutu/grpc,jboeuf/grpc,mway08/grpc,chrisdunelm/grpc,7anner/grpc,zeliard/grpc,xtopsoft/grpc,JoeWoo/grpc,stanley-cheung/grpc,jtattermusch/grpc,goldenbull/grpc,dgquintas/grpc,pszemus/grpc,xtopsoft/grpc,msmania/grpc,VcamX/grpc,apolcyn/grpc,leifurhauks/grpc,VcamX/grpc,maxwell-demon/grpc,nmittler/grpc,LuminateWireless/grpc,stanley-cheung/grpc,wangyikai/grpc,7anner/grpc,crast/grpc,ppietrasa/grpc,jtattermusch/grpc,mway08/grpc,ncteisen/grpc,apolcyn/grpc,y-zeng/grpc,tatsuhiro-t/grpc,madongfly/grpc,donnadionne/grpc,nicolasnoble/grpc,doubi-workshop/grpc,Crevil/grpc,pmarks-net/grpc,malexzx/grpc,vsco/grpc,chenbaihu/grpc,ncteisen/grpc,tengyifei/grpc,soltanmm/grpc,msiedlarek/grpc,wcevans/grpc,kumaralokgithub/grpc,andrewpollock/grpc,doubi-workshop/grpc,vsco/grpc,carl-mastrangelo/grpc,muxi/grpc,thunderboltsid/grpc,gpndata/grpc,grani/grpc,madongfly/grpc,kriswuollett/grpc,ipylypiv/grpc,kumaralokgithub/grpc,maxwell-demon/grpc,leifurhauks/grpc,Crevil/grpc,mehrdada/grpc,a-veitch/grpc,makdharma/grpc,vjpai/grpc,thinkerou/grpc,grpc/grpc,thinkerou/grpc,kpayson64/grpc,VcamX/grpc,grani/grpc,thinkerou/grpc,ananthonline/grpc,perumaalgoog/grpc,ctiller/grpc,nicolasnoble/grpc,murgatroid99/grpc,apolcyn/grpc,quizlet/grpc,7anner/grpc,arkmaxim/grpc,dgquintas/grpc,Vizerai/grpc,xtopsoft/grpc,LuminateWireless/grpc,donnadionne/grpc,ananthonline/grpc,jtattermusch/grpc,fuchsia-mirror/third_party-grpc,nathanielmanistaatgoogle/grpc,bjori/grpc,simonkuang/grpc,infinit/grpc,msiedlarek/grpc,stanley-cheung/grpc,jboeuf/grpc,surround-io/grpc,thunderboltsid/grpc,PeterFaiman/ruby-grpc-minimal,JoeWoo/grpc,ipylypiv/grpc,rjshade/grpc,royalharsh/grpc,VcamX/grpc,mzhaom/grpc,mway08/grpc,donnadionne/grpc,matt-kwong/grpc,msmania/grpc,nicolasnoble/grpc,sreecha/grpc,ppietrasa/grpc,w4-sjcho/grpc,infinit/grpc,stanley-cheung/grpc,msmania/grpc,hstefan/grpc,ncteisen/grpc,royalharsh/grpc,yangjae/grpc,fichter/grpc,chrisdunelm/grpc,yangjae/grpc,maxwell-demon/grpc,chrisdunelm/grpc,fuchsia-mirror/third_party-grpc,podsvirov/grpc,donnadionne/grpc,dklempner/grpc,cgvarela/grpc,ipylypiv/grpc,andrewpollock/grpc,larsonmpdx/grpc,firebase/grpc,yonglehou/grpc,ofrobots/grpc,ofrobots/grpc,fuchsia-mirror/third_party-grpc,cgvarela/grpc,royalharsh/grpc,VcamX/grpc,wkubiak/grpc,sreecha/grpc,fuchsia-mirror/third_party-grpc,vjpai/grpc,tempbottle/grpc,mzhaom/grpc,stanley-cheung/grpc,cgvarela/grpc,fuchsia-mirror/third_party-grpc,kpayson64/grpc,geffzhang/grpc,apolcyn/grpc,yangjae/grpc,arkmaxim/grpc,yangjae/grpc,maxwell-demon/grpc,zhimingxie/grpc,philcleveland/grpc,ejona86/grpc,Juzley/grpc,sidrakesh93/grpc,yugui/grpc,philcleveland/grpc,tengyifei/grpc,tengyifei/grpc,grani/grpc,zhimingxie/grpc,leifurhauks/grpc,kriswuollett/grpc,tempbottle/grpc,malexzx/grpc,murgatroid99/grpc,vsco/grpc,muxi/grpc,kskalski/grpc,thunderboltsid/grpc,wkubiak/grpc,surround-io/grpc,MakMukhi/grpc,makdharma/grpc,soltanmm/grpc,deepaklukose/grpc,tamihiro/grpc,simonkuang/grpc,greasypizza/grpc,JoeWoo/grpc,ananthonline/grpc,baylabs/grpc,mway08/grpc,deepaklukose/grpc,goldenbull/grpc,donnadionne/grpc,wkubiak/grpc,yugui/grpc,MakMukhi/grpc,LuminateWireless/grpc,Juzley/grpc,firebase/grpc,ananthonline/grpc,ctiller/grpc,yongni/grpc,iMilind/grpc,yongni/grpc,cgvarela/grpc,yinsu/grpc,maxwell-demon/grpc,jcanizales/grpc,miselin/grpc,adelez/grpc,tamihiro/grpc,hstefan/grpc,ejona86/grpc,andrewpollock/grpc,crast/grpc,ctiller/grpc,malexzx/grpc,murgatroid99/grpc,soltanmm-google/grpc,ipylypiv/grpc,grani/grpc,daniel-j-born/grpc,jtattermusch/grpc,surround-io/grpc,vjpai/grpc,iMilind/grpc,vsco/grpc,ksophocleous/grpc,yang-g/grpc,jcanizales/grpc,soltanmm-google/grpc,yugui/grpc,nmittler/grpc,wcevans/grpc,yinsu/grpc,vsco/grpc,yangjae/grpc,deepaklukose/grpc,perumaalgoog/grpc,sreecha/grpc,yinsu/grpc,bogdandrutu/grpc,tamihiro/grpc,perumaalgoog/grpc,jcanizales/grpc,ctiller/grpc,grpc/grpc,leifurhauks/grpc,y-zeng/grpc,ppietrasa/grpc,zhimingxie/grpc,xtopsoft/grpc,pmarks-net/grpc,greasypizza/grpc,tempbottle/grpc,soltanmm-google/grpc,leifurhauks/grpc,makdharma/grpc,hstefan/grpc,dgquintas/grpc,JoeWoo/grpc,makdharma/grpc,surround-io/grpc,ncteisen/grpc,msmania/grpc,carl-mastrangelo/grpc,murgatroid99/grpc,sreecha/grpc,xtopsoft/grpc,grpc/grpc,xtopsoft/grpc,fichter/grpc,ipylypiv/grpc,geffzhang/grpc,deepaklukose/grpc,muxi/grpc,ncteisen/grpc,dgquintas/grpc,yinsu/grpc,iMilind/grpc,ncteisen/grpc,kriswuollett/grpc,tengyifei/grpc,surround-io/grpc,kriswuollett/grpc,muxi/grpc,podsvirov/grpc,chenbaihu/grpc,chrisdunelm/grpc,goldenbull/grpc,a-veitch/grpc,kpayson64/grpc,chrisdunelm/grpc,baylabs/grpc,muxi/grpc,cgvarela/grpc,kpayson64/grpc,murgatroid99/grpc,chrisdunelm/grpc,donnadionne/grpc,firebase/grpc,leifurhauks/grpc,makdharma/grpc,PeterFaiman/ruby-grpc-minimal,kriswuollett/grpc,malexzx/grpc,nmittler/grpc,stanley-cheung/grpc,madongfly/grpc,zhimingxie/grpc,JoeWoo/grpc,Vizerai/grpc,matt-kwong/grpc,baylabs/grpc,rjshade/grpc,yongni/grpc,PeterFaiman/ruby-grpc-minimal,yonglehou/grpc,dgquintas/grpc,vjpai/grpc,vjpai/grpc,tatsuhiro-t/grpc,pszemus/grpc,tamihiro/grpc,firebase/grpc,infinit/grpc,donnadionne/grpc,a-veitch/grpc,grpc/grpc,deepaklukose/grpc,mway08/grpc,andrewpollock/grpc,dklempner/grpc,PeterFaiman/ruby-grpc-minimal,yugui/grpc,Vizerai/grpc,vjpai/grpc,gpndata/grpc,perumaalgoog/grpc,kriswuollett/grpc,bjori/grpc,zhimingxie/grpc,firebase/grpc,meisterpeeps/grpc,chenbaihu/grpc,thinkerou/grpc,miselin/grpc,infinit/grpc,meisterpeeps/grpc,dklempner/grpc,larsonmpdx/grpc,sidrakesh93/grpc,a11r/grpc,dgquintas/grpc,yangjae/grpc,a-veitch/grpc,rjshade/grpc,ananthonline/grpc,thinkerou/grpc,mzhaom/grpc,kpayson64/grpc,tatsuhiro-t/grpc,bjori/grpc,ksophocleous/grpc,ctiller/grpc,vsco/grpc,philcleveland/grpc,7anner/grpc,VcamX/grpc,adelez/grpc,ctiller/grpc,grani/grpc,murgatroid99/grpc,baylabs/grpc,grani/grpc,pszemus/grpc,royalharsh/grpc,daniel-j-born/grpc,larsonmpdx/grpc,a11r/grpc,ksophocleous/grpc,jtattermusch/grpc,fuchsia-mirror/third_party-grpc,w4-sjcho/grpc,iMilind/grpc,geffzhang/grpc,greasypizza/grpc,Vizerai/grpc,malexzx/grpc,surround-io/grpc,mzhaom/grpc,fuchsia-mirror/third_party-grpc,simonkuang/grpc,makdharma/grpc,pszemus/grpc,MakMukhi/grpc,larsonmpdx/grpc,jtattermusch/grpc,jtattermusch/grpc,larsonmpdx/grpc,makdharma/grpc,a11r/grpc,Crevil/grpc,madongfly/grpc,yugui/grpc,msiedlarek/grpc,Juzley/grpc,rjshade/grpc,kskalski/grpc,quizlet/grpc,jtattermusch/grpc,mway08/grpc,stanley-cheung/grpc,daniel-j-born/grpc,muxi/grpc,pszemus/grpc,LuminateWireless/grpc,donnadionne/grpc,jboeuf/grpc,bjori/grpc,7anner/grpc,Crevil/grpc,Juzley/grpc,y-zeng/grpc,greasypizza/grpc,iMilind/grpc,ofrobots/grpc,dgquintas/grpc,greasypizza/grpc,goldenbull/grpc,Juzley/grpc,pszemus/grpc,a11r/grpc,thinkerou/grpc,LuminateWireless/grpc,miselin/grpc,thinkerou/grpc,LuminateWireless/grpc,carl-mastrangelo/grpc,wangyikai/grpc,w4-sjcho/grpc,mzhaom/grpc,ananthonline/grpc,muxi/grpc,w4-sjcho/grpc,arkmaxim/grpc,infinit/grpc,surround-io/grpc,soltanmm-google/grpc,zeliard/grpc,adelez/grpc,MakMukhi/grpc,soltanmm/grpc,iMilind/grpc,rjshade/grpc,sreecha/grpc,ctiller/grpc,nicolasnoble/grpc,dklempner/grpc,apolcyn/grpc,grpc/grpc,tempbottle/grpc,jtattermusch/grpc,zhimingxie/grpc,arkmaxim/grpc,pszemus/grpc,Juzley/grpc,nicolasnoble/grpc,soltanmm/grpc,wkubiak/grpc,infinit/grpc,carl-mastrangelo/grpc,yang-g/grpc,muxi/grpc,nicolasnoble/grpc,geffzhang/grpc,gpndata/grpc,fichter/grpc,podsvirov/grpc,wangyikai/grpc,ctiller/grpc,tamihiro/grpc,arkmaxim/grpc,zhimingxie/grpc,tengyifei/grpc,sidrakesh93/grpc,crast/grpc,wkubiak/grpc,xtopsoft/grpc,mzhaom/grpc,tatsuhiro-t/grpc,miselin/grpc,sidrakesh93/grpc,rjshade/grpc,madongfly/grpc,tempbottle/grpc,wangyikai/grpc,firebase/grpc,mehrdada/grpc,zhimingxie/grpc,jcanizales/grpc,zeliard/grpc,yang-g/grpc,philcleveland/grpc,muxi/grpc,tengyifei/grpc,ejona86/grpc,hstefan/grpc,yongni/grpc,arkmaxim/grpc,kskalski/grpc,zhimingxie/grpc,Vizerai/grpc,ejona86/grpc,w4-sjcho/grpc,andrewpollock/grpc,goldenbull/grpc,PeterFaiman/ruby-grpc-minimal,fichter/grpc,sidrakesh93/grpc,infinit/grpc,muxi/grpc,wangyikai/grpc,dgquintas/grpc,jcanizales/grpc,sreecha/grpc,ejona86/grpc,hstefan/grpc,pszemus/grpc,wangyikai/grpc,baylabs/grpc,meisterpeeps/grpc,adelez/grpc,wcevans/grpc,mway08/grpc,arkmaxim/grpc,y-zeng/grpc,yonglehou/grpc,ncteisen/grpc,bjori/grpc,jboeuf/grpc,gpndata/grpc,MakMukhi/grpc,pmarks-net/grpc,LuminateWireless/grpc,yugui/grpc,leifurhauks/grpc,quizlet/grpc,stanley-cheung/grpc,yinsu/grpc,geffzhang/grpc,daniel-j-born/grpc,jcanizales/grpc,stanley-cheung/grpc,PeterFaiman/ruby-grpc-minimal,ejona86/grpc,bogdandrutu/grpc,rjshade/grpc,VcamX/grpc,iMilind/grpc,bjori/grpc,LuminateWireless/grpc,daniel-j-born/grpc,wcevans/grpc,meisterpeeps/grpc,murgatroid99/grpc,JoeWoo/grpc,murgatroid99/grpc,meisterpeeps/grpc,maxwell-demon/grpc,ksophocleous/grpc,nathanielmanistaatgoogle/grpc,carl-mastrangelo/grpc,nathanielmanistaatgoogle/grpc,kriswuollett/grpc,jboeuf/grpc,wcevans/grpc,deepaklukose/grpc,VcamX/grpc,ejona86/grpc,thunderboltsid/grpc,PeterFaiman/ruby-grpc-minimal,fuchsia-mirror/third_party-grpc,kskalski/grpc,jcanizales/grpc,Vizerai/grpc,yongni/grpc,crast/grpc,kriswuollett/grpc,soltanmm-google/grpc,soltanmm/grpc,leifurhauks/grpc,soltanmm/grpc,msiedlarek/grpc,gpndata/grpc,grpc/grpc,donnadionne/grpc,carl-mastrangelo/grpc,ksophocleous/grpc,royalharsh/grpc,fichter/grpc,malexzx/grpc,kumaralokgithub/grpc,a11r/grpc,ctiller/grpc,sidrakesh93/grpc,madongfly/grpc,ksophocleous/grpc,philcleveland/grpc,sreecha/grpc,mehrdada/grpc,pszemus/grpc,adelez/grpc,fichter/grpc,larsonmpdx/grpc,jcanizales/grpc,makdharma/grpc,chrisdunelm/grpc,vsco/grpc,greasypizza/grpc,MakMukhi/grpc,deepaklukose/grpc,wkubiak/grpc,jboeuf/grpc,msiedlarek/grpc,yonglehou/grpc,soltanmm/grpc,ofrobots/grpc,nmittler/grpc,7anner/grpc,mzhaom/grpc,quizlet/grpc,tamihiro/grpc,vsco/grpc,zeliard/grpc,Vizerai/grpc,greasypizza/grpc,msiedlarek/grpc,kumaralokgithub/grpc,quizlet/grpc,yang-g/grpc,goldenbull/grpc,mehrdada/grpc,cgvarela/grpc,matt-kwong/grpc,tamihiro/grpc,andrewpollock/grpc,baylabs/grpc,iMilind/grpc,kumaralokgithub/grpc,cgvarela/grpc,ppietrasa/grpc,baylabs/grpc,jtattermusch/grpc,carl-mastrangelo/grpc,thinkerou/grpc,bogdandrutu/grpc,kpayson64/grpc,ctiller/grpc,thunderboltsid/grpc,goldenbull/grpc,apolcyn/grpc,ofrobots/grpc,perumaalgoog/grpc,Juzley/grpc,yangjae/grpc,simonkuang/grpc,ipylypiv/grpc,tempbottle/grpc,pmarks-net/grpc,bogdandrutu/grpc,JoeWoo/grpc,chrisdunelm/grpc,mehrdada/grpc,surround-io/grpc,thunderboltsid/grpc,stanley-cheung/grpc,tatsuhiro-t/grpc,Juzley/grpc,larsonmpdx/grpc,grpc/grpc,greasypizza/grpc,a11r/grpc,geffzhang/grpc,bogdandrutu/grpc,doubi-workshop/grpc,perumaalgoog/grpc,tengyifei/grpc,gpndata/grpc,kpayson64/grpc,sidrakesh93/grpc,bjori/grpc,miselin/grpc,firebase/grpc,yinsu/grpc,donnadionne/grpc,nicolasnoble/grpc,adelez/grpc,arkmaxim/grpc,meisterpeeps/grpc,ananthonline/grpc,w4-sjcho/grpc,sidrakesh93/grpc,tengyifei/grpc,larsonmpdx/grpc,yongni/grpc,MakMukhi/grpc,carl-mastrangelo/grpc,vjpai/grpc,wangyikai/grpc,Crevil/grpc,dklempner/grpc,simonkuang/grpc,kskalski/grpc,malexzx/grpc,tamihiro/grpc,arkmaxim/grpc,nicolasnoble/grpc,ofrobots/grpc,VcamX/grpc,doubi-workshop/grpc,fuchsia-mirror/third_party-grpc,jboeuf/grpc,murgatroid99/grpc,larsonmpdx/grpc,ncteisen/grpc,donnadionne/grpc,MakMukhi/grpc,soltanmm-google/grpc,Vizerai/grpc,crast/grpc,a11r/grpc,kumaralokgithub/grpc,podsvirov/grpc,ppietrasa/grpc,doubi-workshop/grpc,maxwell-demon/grpc,kpayson64/grpc,vjpai/grpc,yinsu/grpc,xtopsoft/grpc,podsvirov/grpc,7anner/grpc,grani/grpc,a11r/grpc,kumaralokgithub/grpc,thunderboltsid/grpc,deepaklukose/grpc,JoeWoo/grpc,jcanizales/grpc,dgquintas/grpc,wcevans/grpc,w4-sjcho/grpc,philcleveland/grpc,PeterFaiman/ruby-grpc-minimal,tempbottle/grpc,mehrdada/grpc,ejona86/grpc,wangyikai/grpc,ncteisen/grpc,yang-g/grpc,msmania/grpc,grani/grpc,ppietrasa/grpc,a-veitch/grpc,pszemus/grpc,kumaralokgithub/grpc,nicolasnoble/grpc,gpndata/grpc,sreecha/grpc,geffzhang/grpc,wcevans/grpc,hstefan/grpc,royalharsh/grpc,thunderboltsid/grpc,nathanielmanistaatgoogle/grpc,kpayson64/grpc,hstefan/grpc,yonglehou/grpc,pszemus/grpc,adelez/grpc,chrisdunelm/grpc,ejona86/grpc,jboeuf/grpc,meisterpeeps/grpc,a11r/grpc,ctiller/grpc,grpc/grpc,tatsuhiro-t/grpc,carl-mastrangelo/grpc,vjpai/grpc,ksophocleous/grpc,philcleveland/grpc,soltanmm/grpc,greasypizza/grpc,nicolasnoble/grpc,bogdandrutu/grpc,nathanielmanistaatgoogle/grpc,thinkerou/grpc,yonglehou/grpc,infinit/grpc,yang-g/grpc,a-veitch/grpc,goldenbull/grpc,msmania/grpc,y-zeng/grpc,kpayson64/grpc,thinkerou/grpc,miselin/grpc,7anner/grpc,apolcyn/grpc,ipylypiv/grpc,crast/grpc,ananthonline/grpc,bogdandrutu/grpc,perumaalgoog/grpc,quizlet/grpc,maxwell-demon/grpc,quizlet/grpc,yang-g/grpc,chenbaihu/grpc,y-zeng/grpc,carl-mastrangelo/grpc,andrewpollock/grpc,bjori/grpc,madongfly/grpc,rjshade/grpc,podsvirov/grpc,Vizerai/grpc,nathanielmanistaatgoogle/grpc,pmarks-net/grpc,firebase/grpc,ppietrasa/grpc,firebase/grpc,yongni/grpc,msiedlarek/grpc,stanley-cheung/grpc,gpndata/grpc,jtattermusch/grpc,ncteisen/grpc,goldenbull/grpc,bjori/grpc,geffzhang/grpc,ctiller/grpc,pmarks-net/grpc,jboeuf/grpc,nathanielmanistaatgoogle/grpc,nmittler/grpc,matt-kwong/grpc,quizlet/grpc,y-zeng/grpc,Crevil/grpc,miselin/grpc,msmania/grpc,PeterFaiman/ruby-grpc-minimal,chrisdunelm/grpc,ipylypiv/grpc,w4-sjcho/grpc,matt-kwong/grpc,sreecha/grpc,rjshade/grpc,jboeuf/grpc,doubi-workshop/grpc,kskalski/grpc,yugui/grpc,tempbottle/grpc,simonkuang/grpc,matt-kwong/grpc,fuchsia-mirror/third_party-grpc,makdharma/grpc,soltanmm-google/grpc,ejona86/grpc,stanley-cheung/grpc,muxi/grpc,y-zeng/grpc,nmittler/grpc,vjpai/grpc,ipylypiv/grpc,yugui/grpc,msiedlarek/grpc,wcevans/grpc,wkubiak/grpc,7anner/grpc,jtattermusch/grpc,yang-g/grpc,ksophocleous/grpc,malexzx/grpc,tatsuhiro-t/grpc,adelez/grpc,ofrobots/grpc,dklempner/grpc,chenbaihu/grpc,simonkuang/grpc,firebase/grpc,msmania/grpc,thinkerou/grpc,wkubiak/grpc,chenbaihu/grpc,zeliard/grpc,crast/grpc,baylabs/grpc,MakMukhi/grpc,ncteisen/grpc,adelez/grpc,sreecha/grpc,y-zeng/grpc,ppietrasa/grpc,leifurhauks/grpc,dgquintas/grpc,jboeuf/grpc,w4-sjcho/grpc,grpc/grpc,mehrdada/grpc,philcleveland/grpc,mzhaom/grpc,crast/grpc,hstefan/grpc,baylabs/grpc,pmarks-net/grpc,ofrobots/grpc,tengyifei/grpc,a-veitch/grpc,daniel-j-born/grpc,yonglehou/grpc,podsvirov/grpc,thinkerou/grpc,yongni/grpc,pszemus/grpc,zeliard/grpc,Crevil/grpc,LuminateWireless/grpc,dklempner/grpc,apolcyn/grpc,Crevil/grpc,yonglehou/grpc,jboeuf/grpc,royalharsh/grpc,PeterFaiman/ruby-grpc-minimal,Vizerai/grpc,yinsu/grpc,quizlet/grpc,doubi-workshop/grpc,firebase/grpc,madongfly/grpc,vjpai/grpc,a-veitch/grpc,Vizerai/grpc,mehrdada/grpc,soltanmm/grpc,cgvarela/grpc,iMilind/grpc,yugui/grpc,nicolasnoble/grpc,meisterpeeps/grpc,miselin/grpc,wangyikai/grpc,ofrobots/grpc,mehrdada/grpc,chrisdunelm/grpc,dgquintas/grpc,nmittler/grpc,ppietrasa/grpc,grpc/grpc,donnadionne/grpc,podsvirov/grpc,ejona86/grpc,perumaalgoog/grpc,royalharsh/grpc,yinsu/grpc,kskalski/grpc,daniel-j-born/grpc,simonkuang/grpc,tatsuhiro-t/grpc,grpc/grpc,mehrdada/grpc,maxwell-demon/grpc,kriswuollett/grpc,simonkuang/grpc,sreecha/grpc,philcleveland/grpc,mway08/grpc,dklempner/grpc,ananthonline/grpc,mehrdada/grpc,pmarks-net/grpc,chenbaihu/grpc,sreecha/grpc,JoeWoo/grpc,hstefan/grpc,ejona86/grpc,deepaklukose/grpc,nmittler/grpc,madongfly/grpc,zeliard/grpc,yangjae/grpc,daniel-j-born/grpc,geffzhang/grpc,perumaalgoog/grpc,malexzx/grpc,podsvirov/grpc,royalharsh/grpc,thunderboltsid/grpc,kskalski/grpc,kumaralokgithub/grpc,muxi/grpc
ef12362e4bd7d8ed54c6280fcd4bc1c0451a9ef3
Siv3D/include/Siv3D/JSONWriter.hpp
Siv3D/include/Siv3D/JSONWriter.hpp
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <memory> # include "Fwd.hpp" # include "Array.hpp" namespace s3d { namespace detail { struct JSONWriterDetail; }; class JSONWriter { private: std::shared_ptr<detail::JSONWriterDetail> pImpl; public: JSONWriter(); JSONWriter& setIndent(char32 ch, size_t count); JSONWriter& setMaxDecimalPlaces(int32 maxDecimalPlaces); void startObject(); void endObject(); void startArray(); void endArray(); JSONWriter& key(StringView key); void writeString(StringView value); void writeInt32(int32 value); void writeUint32(uint32 value); void writeInt64(int64 value); void writeUint64(uint64 value); void writeDouble(double value); void writeBool(bool value); void writeNull(); template <class Type> void writeArray(std::initializer_list<Type> ilist) { startArray(); for (const auto& value : ilist) { write(value); } endArray(); } template <class Type, size_t Size> void writeArray(const std::array<Type, Size>& values) { startArray(); for (const auto& value : values) { write(value); } endArray(); } template <class Type> void writeArray(const Array<Type>& values) { startArray(); for (const auto& value : values) { write(value); } endArray(); } void write(int8 value); void write(uint8 value); void write(int16 value); void write(uint16 value); void write(int32 value); void write(uint32 value); void write(int64 value); void write(uint64 value); void write(float value); void write(double value); void write(StringView value); void write(const String& value); void write(const char32* value); void write(char32 value); template <class Bool, std::enable_if_t<std::is_same_v<Bool, bool>> * = nullptr> void write(bool value) { writeBool(value); } template <class Type, class = decltype(Formatter(std::declval<FormatData&>(), std::declval<Type>()))> void write(const Type& value) { writeString(Format(value)); } [[nodiscard]] bool isComplete() const; [[nodiscard]] String get() const; bool save(FilePathView path); }; }
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (c) 2008-2019 Ryo Suzuki // Copyright (c) 2016-2019 OpenSiv3D Project // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include <memory> # include "Fwd.hpp" # include "Array.hpp" namespace s3d { namespace detail { struct JSONWriterDetail; }; class JSONWriter { private: std::shared_ptr<detail::JSONWriterDetail> pImpl; public: JSONWriter(); JSONWriter& setIndent(char32 ch, size_t count); JSONWriter& setMaxDecimalPlaces(int32 maxDecimalPlaces); void startObject(); void endObject(); void startArray(); void endArray(); JSONWriter& key(StringView key); void writeString(StringView value); void writeInt32(int32 value); void writeUint32(uint32 value); void writeInt64(int64 value); void writeUint64(uint64 value); void writeDouble(double value); void writeBool(bool value); void writeNull(); template <class Type> void writeArray(std::initializer_list<Type> ilist) { startArray(); for (const auto& value : ilist) { write(value); } endArray(); } template <class Type, size_t Size> void writeArray(const std::array<Type, Size>& values) { startArray(); for (const auto& value : values) { write(value); } endArray(); } template <class Type> void writeArray(const Array<Type>& values) { startArray(); for (const auto& value : values) { write(value); } endArray(); } void write(int8 value); void write(uint8 value); void write(int16 value); void write(uint16 value); void write(int32 value); void write(uint32 value); void write(int64 value); void write(uint64 value); void write(float value); void write(double value); void write(StringView value); void write(const String& value); void write(const char32* value); void write(char32 value); template <class Bool, std::enable_if_t<std::is_same_v<Bool, bool>>* = nullptr> void write(const Bool& value) { writeBool(value); } template <class Type, class = decltype(Formatter(std::declval<FormatData&>(), std::declval<Type>())), std::enable_if_t<!std::is_same_v<Type, bool>>* = nullptr> void write(const Type& value) { writeString(Format(value)); } [[nodiscard]] bool isComplete() const; [[nodiscard]] String get() const; bool save(FilePathView path); }; }
fix #457
fix #457
C++
mit
Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D,Siv3D/OpenSiv3D
01af52132f5a3a37c1bd3cfb0183c6f6ac0e252f
lib/Target/AMDGPU/SIInsertSkips.cpp
lib/Target/AMDGPU/SIInsertSkips.cpp
//===-- SIInsertSkips.cpp - Use predicates for control flow ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// This pass inserts branches on the 0 exec mask over divergent branches /// branches when it's expected that jumping over the untaken control flow will /// be cheaper than having every workitem no-op through it. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "MCTargetDesc/AMDGPUMCTargetDesc.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/DebugLoc.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include <cassert> #include <cstdint> #include <iterator> using namespace llvm; #define DEBUG_TYPE "si-insert-skips" static cl::opt<unsigned> SkipThresholdFlag( "amdgpu-skip-threshold", cl::desc("Number of instructions before jumping over divergent control flow"), cl::init(12), cl::Hidden); namespace { class SIInsertSkips : public MachineFunctionPass { private: const SIRegisterInfo *TRI = nullptr; const SIInstrInfo *TII = nullptr; unsigned SkipThreshold = 0; bool shouldSkip(const MachineBasicBlock &From, const MachineBasicBlock &To) const; bool skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB); void kill(MachineInstr &MI); MachineBasicBlock *insertSkipBlock(MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const; bool skipMaskBranch(MachineInstr &MI, MachineBasicBlock &MBB); public: static char ID; SIInsertSkips() : MachineFunctionPass(ID) {} bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI insert s_cbranch_execz instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { MachineFunctionPass::getAnalysisUsage(AU); } }; } // end anonymous namespace char SIInsertSkips::ID = 0; INITIALIZE_PASS(SIInsertSkips, DEBUG_TYPE, "SI insert s_cbranch_execz instructions", false, false) char &llvm::SIInsertSkipsPassID = SIInsertSkips::ID; static bool opcodeEmitsNoInsts(unsigned Opc) { switch (Opc) { case TargetOpcode::IMPLICIT_DEF: case TargetOpcode::KILL: case TargetOpcode::BUNDLE: case TargetOpcode::CFI_INSTRUCTION: case TargetOpcode::EH_LABEL: case TargetOpcode::GC_LABEL: case TargetOpcode::DBG_VALUE: return true; default: return false; } } bool SIInsertSkips::shouldSkip(const MachineBasicBlock &From, const MachineBasicBlock &To) const { if (From.succ_empty()) return false; unsigned NumInstr = 0; const MachineFunction *MF = From.getParent(); for (MachineFunction::const_iterator MBBI(&From), ToI(&To), End = MF->end(); MBBI != End && MBBI != ToI; ++MBBI) { const MachineBasicBlock &MBB = *MBBI; for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end(); NumInstr < SkipThreshold && I != E; ++I) { if (opcodeEmitsNoInsts(I->getOpcode())) continue; // FIXME: Since this is required for correctness, this should be inserted // during SILowerControlFlow. // When a uniform loop is inside non-uniform control flow, the branch // leaving the loop might be an S_CBRANCH_VCCNZ, which is never taken // when EXEC = 0. We should skip the loop lest it becomes infinite. if (I->getOpcode() == AMDGPU::S_CBRANCH_VCCNZ || I->getOpcode() == AMDGPU::S_CBRANCH_VCCZ) return true; if (TII->hasUnwantedEffectsWhenEXECEmpty(*I)) return true; ++NumInstr; if (NumInstr >= SkipThreshold) return true; } } return false; } bool SIInsertSkips::skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB) { MachineBasicBlock &MBB = *MI.getParent(); MachineFunction *MF = MBB.getParent(); if (MF->getFunction().getCallingConv() != CallingConv::AMDGPU_PS || !shouldSkip(MBB, MBB.getParent()->back())) return false; MachineBasicBlock *SkipBB = insertSkipBlock(MBB, MI.getIterator()); const DebugLoc &DL = MI.getDebugLoc(); // If the exec mask is non-zero, skip the next two instructions BuildMI(&MBB, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) .addMBB(&NextBB); MachineBasicBlock::iterator Insert = SkipBB->begin(); // Exec mask is zero: Export to NULL target... BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::EXP_DONE)) .addImm(0x09) // V_008DFC_SQ_EXP_NULL .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addImm(1) // vm .addImm(0) // compr .addImm(0); // en // ... and terminate wavefront. BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::S_ENDPGM)); return true; } void SIInsertSkips::kill(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); DebugLoc DL = MI.getDebugLoc(); switch (MI.getOpcode()) { case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR: { unsigned Opcode = 0; // The opcodes are inverted because the inline immediate has to be // the first operand, e.g. from "x < imm" to "imm > x" switch (MI.getOperand(2).getImm()) { case ISD::SETOEQ: case ISD::SETEQ: Opcode = AMDGPU::V_CMPX_EQ_F32_e64; break; case ISD::SETOGT: case ISD::SETGT: Opcode = AMDGPU::V_CMPX_LT_F32_e64; break; case ISD::SETOGE: case ISD::SETGE: Opcode = AMDGPU::V_CMPX_LE_F32_e64; break; case ISD::SETOLT: case ISD::SETLT: Opcode = AMDGPU::V_CMPX_GT_F32_e64; break; case ISD::SETOLE: case ISD::SETLE: Opcode = AMDGPU::V_CMPX_GE_F32_e64; break; case ISD::SETONE: case ISD::SETNE: Opcode = AMDGPU::V_CMPX_LG_F32_e64; break; case ISD::SETO: Opcode = AMDGPU::V_CMPX_O_F32_e64; break; case ISD::SETUO: Opcode = AMDGPU::V_CMPX_U_F32_e64; break; case ISD::SETUEQ: Opcode = AMDGPU::V_CMPX_NLG_F32_e64; break; case ISD::SETUGT: Opcode = AMDGPU::V_CMPX_NGE_F32_e64; break; case ISD::SETUGE: Opcode = AMDGPU::V_CMPX_NGT_F32_e64; break; case ISD::SETULT: Opcode = AMDGPU::V_CMPX_NLE_F32_e64; break; case ISD::SETULE: Opcode = AMDGPU::V_CMPX_NLT_F32_e64; break; case ISD::SETUNE: Opcode = AMDGPU::V_CMPX_NEQ_F32_e64; break; default: llvm_unreachable("invalid ISD:SET cond code"); } assert(MI.getOperand(0).isReg()); if (TRI->isVGPR(MBB.getParent()->getRegInfo(), MI.getOperand(0).getReg())) { Opcode = AMDGPU::getVOPe32(Opcode); BuildMI(MBB, &MI, DL, TII->get(Opcode)) .add(MI.getOperand(1)) .add(MI.getOperand(0)); } else { BuildMI(MBB, &MI, DL, TII->get(Opcode)) .addReg(AMDGPU::VCC, RegState::Define) .addImm(0) // src0 modifiers .add(MI.getOperand(1)) .addImm(0) // src1 modifiers .add(MI.getOperand(0)) .addImm(0); // omod } break; } case AMDGPU::SI_KILL_I1_TERMINATOR: { const MachineOperand &Op = MI.getOperand(0); int64_t KillVal = MI.getOperand(1).getImm(); assert(KillVal == 0 || KillVal == -1); // Kill all threads if Op0 is an immediate and equal to the Kill value. if (Op.isImm()) { int64_t Imm = Op.getImm(); assert(Imm == 0 || Imm == -1); if (Imm == KillVal) BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) .addImm(0); break; } unsigned Opcode = KillVal ? AMDGPU::S_ANDN2_B64 : AMDGPU::S_AND_B64; BuildMI(MBB, &MI, DL, TII->get(Opcode), AMDGPU::EXEC) .addReg(AMDGPU::EXEC) .add(Op); break; } default: llvm_unreachable("invalid opcode, expected SI_KILL_*_TERMINATOR"); } } MachineBasicBlock *SIInsertSkips::insertSkipBlock( MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { MachineFunction *MF = MBB.getParent(); MachineBasicBlock *SkipBB = MF->CreateMachineBasicBlock(); MachineFunction::iterator MBBI(MBB); ++MBBI; MF->insert(MBBI, SkipBB); MBB.addSuccessor(SkipBB); return SkipBB; } // Returns true if a branch over the block was inserted. bool SIInsertSkips::skipMaskBranch(MachineInstr &MI, MachineBasicBlock &SrcMBB) { MachineBasicBlock *DestBB = MI.getOperand(0).getMBB(); if (!shouldSkip(**SrcMBB.succ_begin(), *DestBB)) return false; const DebugLoc &DL = MI.getDebugLoc(); MachineBasicBlock::iterator InsPt = std::next(MI.getIterator()); BuildMI(SrcMBB, InsPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ)) .addMBB(DestBB); return true; } bool SIInsertSkips::runOnMachineFunction(MachineFunction &MF) { const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); TII = ST.getInstrInfo(); TRI = &TII->getRegisterInfo(); SkipThreshold = SkipThresholdFlag; bool HaveKill = false; bool MadeChange = false; // Track depth of exec mask, divergent branches. SmallVector<MachineBasicBlock *, 16> ExecBranchStack; MachineFunction::iterator NextBB; MachineBasicBlock *EmptyMBBAtEnd = nullptr; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; BI = NextBB) { NextBB = std::next(BI); MachineBasicBlock &MBB = *BI; bool HaveSkipBlock = false; if (!ExecBranchStack.empty() && ExecBranchStack.back() == &MBB) { // Reached convergence point for last divergent branch. ExecBranchStack.pop_back(); } if (HaveKill && ExecBranchStack.empty()) { HaveKill = false; // TODO: Insert skip if exec is 0? } MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; switch (MI.getOpcode()) { case AMDGPU::SI_MASK_BRANCH: ExecBranchStack.push_back(MI.getOperand(0).getMBB()); MadeChange |= skipMaskBranch(MI, MBB); break; case AMDGPU::S_BRANCH: // Optimize out branches to the next block. // FIXME: Shouldn't this be handled by BranchFolding? if (MBB.isLayoutSuccessor(MI.getOperand(0).getMBB())) { MI.eraseFromParent(); } else if (HaveSkipBlock) { // Remove the given unconditional branch when a skip block has been // inserted after the current one and let skip the two instructions // performing the kill if the exec mask is non-zero. MI.eraseFromParent(); } break; case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR: case AMDGPU::SI_KILL_I1_TERMINATOR: MadeChange = true; kill(MI); if (ExecBranchStack.empty()) { if (skipIfDead(MI, *NextBB)) { HaveSkipBlock = true; NextBB = std::next(BI); BE = MF.end(); } } else { HaveKill = true; } MI.eraseFromParent(); break; case AMDGPU::SI_RETURN_TO_EPILOG: // FIXME: Should move somewhere else assert(!MF.getInfo<SIMachineFunctionInfo>()->returnsVoid()); // Graphics shaders returning non-void shouldn't contain S_ENDPGM, // because external bytecode will be appended at the end. if (BI != --MF.end() || I != MBB.getFirstTerminator()) { // SI_RETURN_TO_EPILOG is not the last instruction. Add an empty block at // the end and jump there. if (!EmptyMBBAtEnd) { EmptyMBBAtEnd = MF.CreateMachineBasicBlock(); MF.insert(MF.end(), EmptyMBBAtEnd); } MBB.addSuccessor(EmptyMBBAtEnd); BuildMI(*BI, I, MI.getDebugLoc(), TII->get(AMDGPU::S_BRANCH)) .addMBB(EmptyMBBAtEnd); I->eraseFromParent(); } break; default: break; } } } return MadeChange; }
//===-- SIInsertSkips.cpp - Use predicates for control flow ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// This pass inserts branches on the 0 exec mask over divergent branches /// branches when it's expected that jumping over the untaken control flow will /// be cheaper than having every workitem no-op through it. // //===----------------------------------------------------------------------===// #include "AMDGPU.h" #include "AMDGPUSubtarget.h" #include "SIInstrInfo.h" #include "SIMachineFunctionInfo.h" #include "MCTargetDesc/AMDGPUMCTargetDesc.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/CodeGen/MachineBasicBlock.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineInstrBuilder.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/IR/CallingConv.h" #include "llvm/IR/DebugLoc.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/Pass.h" #include "llvm/Support/CommandLine.h" #include "llvm/Target/TargetMachine.h" #include <cassert> #include <cstdint> #include <iterator> using namespace llvm; #define DEBUG_TYPE "si-insert-skips" static cl::opt<unsigned> SkipThresholdFlag( "amdgpu-skip-threshold", cl::desc("Number of instructions before jumping over divergent control flow"), cl::init(12), cl::Hidden); namespace { class SIInsertSkips : public MachineFunctionPass { private: const SIRegisterInfo *TRI = nullptr; const SIInstrInfo *TII = nullptr; unsigned SkipThreshold = 0; bool shouldSkip(const MachineBasicBlock &From, const MachineBasicBlock &To) const; bool skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB); void kill(MachineInstr &MI); MachineBasicBlock *insertSkipBlock(MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const; bool skipMaskBranch(MachineInstr &MI, MachineBasicBlock &MBB); public: static char ID; SIInsertSkips() : MachineFunctionPass(ID) {} bool runOnMachineFunction(MachineFunction &MF) override; StringRef getPassName() const override { return "SI insert s_cbranch_execz instructions"; } void getAnalysisUsage(AnalysisUsage &AU) const override { MachineFunctionPass::getAnalysisUsage(AU); } }; } // end anonymous namespace char SIInsertSkips::ID = 0; INITIALIZE_PASS(SIInsertSkips, DEBUG_TYPE, "SI insert s_cbranch_execz instructions", false, false) char &llvm::SIInsertSkipsPassID = SIInsertSkips::ID; static bool opcodeEmitsNoInsts(unsigned Opc) { switch (Opc) { case TargetOpcode::IMPLICIT_DEF: case TargetOpcode::KILL: case TargetOpcode::BUNDLE: case TargetOpcode::CFI_INSTRUCTION: case TargetOpcode::EH_LABEL: case TargetOpcode::GC_LABEL: case TargetOpcode::DBG_VALUE: return true; default: return false; } } bool SIInsertSkips::shouldSkip(const MachineBasicBlock &From, const MachineBasicBlock &To) const { if (From.succ_empty()) return false; unsigned NumInstr = 0; const MachineFunction *MF = From.getParent(); for (MachineFunction::const_iterator MBBI(&From), ToI(&To), End = MF->end(); MBBI != End && MBBI != ToI; ++MBBI) { const MachineBasicBlock &MBB = *MBBI; for (MachineBasicBlock::const_iterator I = MBB.begin(), E = MBB.end(); NumInstr < SkipThreshold && I != E; ++I) { if (opcodeEmitsNoInsts(I->getOpcode())) continue; // FIXME: Since this is required for correctness, this should be inserted // during SILowerControlFlow. // When a uniform loop is inside non-uniform control flow, the branch // leaving the loop might be an S_CBRANCH_VCCNZ, which is never taken // when EXEC = 0. We should skip the loop lest it becomes infinite. if (I->getOpcode() == AMDGPU::S_CBRANCH_VCCNZ || I->getOpcode() == AMDGPU::S_CBRANCH_VCCZ) return true; // V_READFIRSTLANE/V_READLANE destination register may be used as operand // by some SALU instruction. If exec mask is zero vector instruction // defining the register that is used by the scalar one is not executed // and scalar instruction will operate on undefined data. For // V_READFIRSTLANE/V_READLANE we should avoid predicated execution. if ((I->getOpcode() == AMDGPU::V_READFIRSTLANE_B32) || (I->getOpcode() == AMDGPU::V_READLANE_B32)) { return true; } ++NumInstr; if (NumInstr >= SkipThreshold) return true; } } return false; } bool SIInsertSkips::skipIfDead(MachineInstr &MI, MachineBasicBlock &NextBB) { MachineBasicBlock &MBB = *MI.getParent(); MachineFunction *MF = MBB.getParent(); if (MF->getFunction().getCallingConv() != CallingConv::AMDGPU_PS || !shouldSkip(MBB, MBB.getParent()->back())) return false; MachineBasicBlock *SkipBB = insertSkipBlock(MBB, MI.getIterator()); const DebugLoc &DL = MI.getDebugLoc(); // If the exec mask is non-zero, skip the next two instructions BuildMI(&MBB, DL, TII->get(AMDGPU::S_CBRANCH_EXECNZ)) .addMBB(&NextBB); MachineBasicBlock::iterator Insert = SkipBB->begin(); // Exec mask is zero: Export to NULL target... BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::EXP_DONE)) .addImm(0x09) // V_008DFC_SQ_EXP_NULL .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addReg(AMDGPU::VGPR0, RegState::Undef) .addImm(1) // vm .addImm(0) // compr .addImm(0); // en // ... and terminate wavefront. BuildMI(*SkipBB, Insert, DL, TII->get(AMDGPU::S_ENDPGM)); return true; } void SIInsertSkips::kill(MachineInstr &MI) { MachineBasicBlock &MBB = *MI.getParent(); DebugLoc DL = MI.getDebugLoc(); switch (MI.getOpcode()) { case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR: { unsigned Opcode = 0; // The opcodes are inverted because the inline immediate has to be // the first operand, e.g. from "x < imm" to "imm > x" switch (MI.getOperand(2).getImm()) { case ISD::SETOEQ: case ISD::SETEQ: Opcode = AMDGPU::V_CMPX_EQ_F32_e64; break; case ISD::SETOGT: case ISD::SETGT: Opcode = AMDGPU::V_CMPX_LT_F32_e64; break; case ISD::SETOGE: case ISD::SETGE: Opcode = AMDGPU::V_CMPX_LE_F32_e64; break; case ISD::SETOLT: case ISD::SETLT: Opcode = AMDGPU::V_CMPX_GT_F32_e64; break; case ISD::SETOLE: case ISD::SETLE: Opcode = AMDGPU::V_CMPX_GE_F32_e64; break; case ISD::SETONE: case ISD::SETNE: Opcode = AMDGPU::V_CMPX_LG_F32_e64; break; case ISD::SETO: Opcode = AMDGPU::V_CMPX_O_F32_e64; break; case ISD::SETUO: Opcode = AMDGPU::V_CMPX_U_F32_e64; break; case ISD::SETUEQ: Opcode = AMDGPU::V_CMPX_NLG_F32_e64; break; case ISD::SETUGT: Opcode = AMDGPU::V_CMPX_NGE_F32_e64; break; case ISD::SETUGE: Opcode = AMDGPU::V_CMPX_NGT_F32_e64; break; case ISD::SETULT: Opcode = AMDGPU::V_CMPX_NLE_F32_e64; break; case ISD::SETULE: Opcode = AMDGPU::V_CMPX_NLT_F32_e64; break; case ISD::SETUNE: Opcode = AMDGPU::V_CMPX_NEQ_F32_e64; break; default: llvm_unreachable("invalid ISD:SET cond code"); } assert(MI.getOperand(0).isReg()); if (TRI->isVGPR(MBB.getParent()->getRegInfo(), MI.getOperand(0).getReg())) { Opcode = AMDGPU::getVOPe32(Opcode); BuildMI(MBB, &MI, DL, TII->get(Opcode)) .add(MI.getOperand(1)) .add(MI.getOperand(0)); } else { BuildMI(MBB, &MI, DL, TII->get(Opcode)) .addReg(AMDGPU::VCC, RegState::Define) .addImm(0) // src0 modifiers .add(MI.getOperand(1)) .addImm(0) // src1 modifiers .add(MI.getOperand(0)) .addImm(0); // omod } break; } case AMDGPU::SI_KILL_I1_TERMINATOR: { const MachineOperand &Op = MI.getOperand(0); int64_t KillVal = MI.getOperand(1).getImm(); assert(KillVal == 0 || KillVal == -1); // Kill all threads if Op0 is an immediate and equal to the Kill value. if (Op.isImm()) { int64_t Imm = Op.getImm(); assert(Imm == 0 || Imm == -1); if (Imm == KillVal) BuildMI(MBB, &MI, DL, TII->get(AMDGPU::S_MOV_B64), AMDGPU::EXEC) .addImm(0); break; } unsigned Opcode = KillVal ? AMDGPU::S_ANDN2_B64 : AMDGPU::S_AND_B64; BuildMI(MBB, &MI, DL, TII->get(Opcode), AMDGPU::EXEC) .addReg(AMDGPU::EXEC) .add(Op); break; } default: llvm_unreachable("invalid opcode, expected SI_KILL_*_TERMINATOR"); } } MachineBasicBlock *SIInsertSkips::insertSkipBlock( MachineBasicBlock &MBB, MachineBasicBlock::iterator I) const { MachineFunction *MF = MBB.getParent(); MachineBasicBlock *SkipBB = MF->CreateMachineBasicBlock(); MachineFunction::iterator MBBI(MBB); ++MBBI; MF->insert(MBBI, SkipBB); MBB.addSuccessor(SkipBB); return SkipBB; } // Returns true if a branch over the block was inserted. bool SIInsertSkips::skipMaskBranch(MachineInstr &MI, MachineBasicBlock &SrcMBB) { MachineBasicBlock *DestBB = MI.getOperand(0).getMBB(); if (!shouldSkip(**SrcMBB.succ_begin(), *DestBB)) return false; const DebugLoc &DL = MI.getDebugLoc(); MachineBasicBlock::iterator InsPt = std::next(MI.getIterator()); BuildMI(SrcMBB, InsPt, DL, TII->get(AMDGPU::S_CBRANCH_EXECZ)) .addMBB(DestBB); return true; } bool SIInsertSkips::runOnMachineFunction(MachineFunction &MF) { const GCNSubtarget &ST = MF.getSubtarget<GCNSubtarget>(); TII = ST.getInstrInfo(); TRI = &TII->getRegisterInfo(); SkipThreshold = SkipThresholdFlag; bool HaveKill = false; bool MadeChange = false; // Track depth of exec mask, divergent branches. SmallVector<MachineBasicBlock *, 16> ExecBranchStack; MachineFunction::iterator NextBB; MachineBasicBlock *EmptyMBBAtEnd = nullptr; for (MachineFunction::iterator BI = MF.begin(), BE = MF.end(); BI != BE; BI = NextBB) { NextBB = std::next(BI); MachineBasicBlock &MBB = *BI; bool HaveSkipBlock = false; if (!ExecBranchStack.empty() && ExecBranchStack.back() == &MBB) { // Reached convergence point for last divergent branch. ExecBranchStack.pop_back(); } if (HaveKill && ExecBranchStack.empty()) { HaveKill = false; // TODO: Insert skip if exec is 0? } MachineBasicBlock::iterator I, Next; for (I = MBB.begin(); I != MBB.end(); I = Next) { Next = std::next(I); MachineInstr &MI = *I; switch (MI.getOpcode()) { case AMDGPU::SI_MASK_BRANCH: ExecBranchStack.push_back(MI.getOperand(0).getMBB()); MadeChange |= skipMaskBranch(MI, MBB); break; case AMDGPU::S_BRANCH: // Optimize out branches to the next block. // FIXME: Shouldn't this be handled by BranchFolding? if (MBB.isLayoutSuccessor(MI.getOperand(0).getMBB())) { MI.eraseFromParent(); } else if (HaveSkipBlock) { // Remove the given unconditional branch when a skip block has been // inserted after the current one and let skip the two instructions // performing the kill if the exec mask is non-zero. MI.eraseFromParent(); } break; case AMDGPU::SI_KILL_F32_COND_IMM_TERMINATOR: case AMDGPU::SI_KILL_I1_TERMINATOR: MadeChange = true; kill(MI); if (ExecBranchStack.empty()) { if (skipIfDead(MI, *NextBB)) { HaveSkipBlock = true; NextBB = std::next(BI); BE = MF.end(); } } else { HaveKill = true; } MI.eraseFromParent(); break; case AMDGPU::SI_RETURN_TO_EPILOG: // FIXME: Should move somewhere else assert(!MF.getInfo<SIMachineFunctionInfo>()->returnsVoid()); // Graphics shaders returning non-void shouldn't contain S_ENDPGM, // because external bytecode will be appended at the end. if (BI != --MF.end() || I != MBB.getFirstTerminator()) { // SI_RETURN_TO_EPILOG is not the last instruction. Add an empty block at // the end and jump there. if (!EmptyMBBAtEnd) { EmptyMBBAtEnd = MF.CreateMachineBasicBlock(); MF.insert(MF.end(), EmptyMBBAtEnd); } MBB.addSuccessor(EmptyMBBAtEnd); BuildMI(*BI, I, MI.getDebugLoc(), TII->get(AMDGPU::S_BRANCH)) .addMBB(EmptyMBBAtEnd); I->eraseFromParent(); } break; default: break; } } } return MadeChange; }
Revert bfada89 AMDGPU: Force skip over s_sendmsg and exp instructions
Revert bfada89 AMDGPU: Force skip over s_sendmsg and exp instructions This is a temporary reversion until we can properly fix a problem where the done exp of a pixel shader was skipped when all lanes were killed. Change-Id: If4cbfbe7fe989ca6cd4c54f7bb5cf6ec547e372f
C++
apache-2.0
GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm
a39ee13e979cf9ae1e7217e30f64a3540c9ab842
cccallcc_fork.hpp
cccallcc_fork.hpp
#ifndef __CCCALLCC_HPP__ #define __CCCALLCC_HPP__ #include <functional> #include <memory> #include <unistd.h> #ifdef __GNUC__ #define NORETURN __attribute__((noreturn)) #else #define NORETURN #endif template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) NORETURN { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) NORETURN { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; if (fork()) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < ssize_t(sizeof(T))) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCCALLCC_HPP__)
#ifndef __CCCALLCC_FORK_HPP__ #define __CCCALLCC_FORK_HPP__ #include <functional> #include <memory> #include <unistd.h> #ifdef __GNUC__ #define NORETURN __attribute__((noreturn)) #else #define NORETURN #endif template <typename T> class cont { public: typedef std::function<T (cont<T>)> call_cc_arg; static T call_cc(call_cc_arg f); void operator()(const T &x) NORETURN { m_impl_ptr->invoke(x); } private: class impl { public: impl(int pipe) : m_pipe(pipe) { } ~impl() { close(m_pipe); } void invoke(const T &x) NORETURN { write(m_pipe, &x, sizeof(T)); exit(0); } private: int m_pipe; }; cont(int pipe) : m_impl_ptr(new impl(pipe)) { } std::shared_ptr<impl> m_impl_ptr; }; template <typename T> T cont<T>::call_cc(call_cc_arg f) { int fd[2]; pipe(fd); int read_fd = fd[0]; int write_fd = fd[1]; if (fork()) { // parent close(read_fd); return f( cont<T>(write_fd) ); } else { // child close(write_fd); char buf[sizeof(T)]; if (read(read_fd, buf, sizeof(T)) < ssize_t(sizeof(T))) exit(0); close(read_fd); return *reinterpret_cast<T*>(buf); } } template <typename T> inline T call_cc(typename cont<T>::call_cc_arg f) { return cont<T>::call_cc(f); } #endif // !defined(__CCCALLCC_FORK_HPP__)
update double-include guards
update double-include guards
C++
bsd-3-clause
kmcallister/cccallcc,kmcallister/cccallcc
cc8582535fe786d2d0ae9c3022e8c96bb9d14bf4
test/print.cpp
test/print.cpp
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_vector.hpp" #include "etl/fast_matrix.hpp" #include "etl/dyn_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/print.hpp" //{{{ to_octave TEST_CASE( "to_octave/fast_vector", "to_octave" ) { etl::fast_vector<double, 3> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_octave(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_octave/fast_matrix", "to_octave" ) { etl::fast_matrix<double, 3, 2> test_matrix({1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_octave(test_matrix) == "[1.000000,-2.000000;3.000000,0.500000;0.000000,-1.000000]"); } TEST_CASE( "to_octave/dyn_vector", "to_octave" ) { etl::dyn_vector<double> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_octave(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_octave/dyn_matrix", "to_octave" ) { etl::dyn_matrix<double> test_matrix(3,2,{1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_octave(test_matrix) == "[1.000000,-2.000000;3.000000,0.500000;0.000000,-1.000000]"); } //}}} //{{{ to_string TEST_CASE( "to_string/fast_vector", "to_string" ) { etl::fast_vector<double, 3> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_string(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_string/fast_matrix", "to_string" ) { etl::fast_matrix<double, 3, 2> test_matrix({1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_string(test_matrix) == "[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]]"); } TEST_CASE( "to_string/dyn_vector", "to_string" ) { etl::dyn_vector<double> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_string(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_string/dyn_matrix", "to_string" ) { etl::dyn_matrix<double> test_matrix(3,2,{1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_string(test_matrix) == "[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]]"); } //}}}
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_vector.hpp" #include "etl/fast_matrix.hpp" #include "etl/dyn_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/print.hpp" //{{{ to_octave TEST_CASE( "to_octave/fast_vector", "to_octave" ) { etl::fast_vector<double, 3> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_octave(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_octave/fast_matrix", "to_octave" ) { etl::fast_matrix<double, 3, 2> test_matrix({1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_octave(test_matrix) == "[1.000000,-2.000000;3.000000,0.500000;0.000000,-1.000000]"); } TEST_CASE( "to_octave/dyn_vector", "to_octave" ) { etl::dyn_vector<double> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_octave(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_octave/dyn_matrix", "to_octave" ) { etl::dyn_matrix<double> test_matrix(3,2,{1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_octave(test_matrix) == "[1.000000,-2.000000;3.000000,0.500000;0.000000,-1.000000]"); } //}}} //{{{ to_string TEST_CASE( "to_string/fast_vector", "to_string" ) { etl::fast_vector<double, 3> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_string(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_string/fast_matrix", "to_string" ) { etl::fast_matrix<double, 3, 2> test_matrix({1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_string(test_matrix) == "[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]]"); } TEST_CASE( "to_string/fast_matrix_3d", "to_string" ) { etl::fast_matrix<double, 2, 3, 2> test_matrix({1.0, -2.0, 3.0, 0.5, 0.0, -1, 1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_string(test_matrix) == "[[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]];[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]]]"); } TEST_CASE( "to_string/dyn_vector", "to_string" ) { etl::dyn_vector<double> test_vector({1.0, -2.0, 3.0}); REQUIRE(to_string(test_vector) == "[1.000000,-2.000000,3.000000]"); } TEST_CASE( "to_string/dyn_matrix", "to_string" ) { etl::dyn_matrix<double> test_matrix(3,2,{1.0, -2.0, 3.0, 0.5, 0.0, -1}); REQUIRE(to_string(test_matrix) == "[[1.000000,-2.000000]\n[3.000000,0.500000]\n[0.000000,-1.000000]]"); } //}}}
Add new test
Add new test
C++
mit
wichtounet/etl,wichtounet/etl
78a546d4ae02993a9e1fbc8547dbc3d165252c51
Service/src/Device.cpp
Service/src/Device.cpp
#include "Device.h" map<string,pfunc> device_api_list; Device::Device(){ this->mysql = new MysqlHelper(); this->mysql->init("127.0.0.1", "root", "root", "smart_car"); this->initApiList(); } Device::~Device(){ } void Device::initApiList() { device_api_list[API_DEVICE_INFO] = &Device::handlerDeverInfo; } void Device::call(Conn* &conn, Json::Value &request_data,const string func){ if(func.length() == 0){ Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); return; } if (device_api_list.count(func)) { (this->*(device_api_list[func]))(conn,request_data); } else { Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); } } void Device::sendData(Conn* &conn,const string resp_data){ char* data = new char[resp_data.length()+1]; resp_data.copy(data,resp_data.length(),0); conn->AddToWriteBuffer(data, resp_data.length()); delete[] data; } void Device::handlerDeverInfo(Conn* &conn, Json::Value &request_data){ Json::Value root; Json::Value data; string sql = "select * from device where "; string name = request_data["name"].asString(); string mac = request_data["mac"].asString(); //获取fd并转string int fd = conn->GetFd(); char intToStr[12]; sprintf(intToStr,"%d",fd); string str_fd = string(intToStr); //检查设备是否存在 sql = sql+"name=\""+name+"\" and mac=\""+mac+"\""; MysqlHelper::MysqlData dataSet = this->mysql->queryRecord(sql); if (dataSet.size() == 0) { //不存在,新增 MysqlHelper::RECORD_DATA record; record.insert(make_pair("name",make_pair(MysqlHelper::DB_STR,name))); record.insert(make_pair("mac",make_pair(MysqlHelper::DB_STR,mac))); record.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"1"))); record.insert(make_pair("status",make_pair(MysqlHelper::DB_INT,"1"))); record.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,str_fd))); int insert_id = this->mysql->insertRecord("device",record); data["id"] = insert_id; }else{ //存在,更新状态 string up_sql = "where mac = \""+mac+"\""; MysqlHelper::RECORD_DATA recordChange; recordChange.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"1"))); recordChange.insert(make_pair("status",make_pair(MysqlHelper::DB_INT,"1"))); recordChange.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,str_fd))); this->mysql->updateRecord("device",recordChange,up_sql); data["id"] = dataSet[0]["id"]; } root["protocol"] = API_DEVICE_INFO; root["data"] = data; this->sendData(conn,root.toStyledString()); } void Device::start(const char* ip,unsigned int port){ this->AddSignalEvent(SIGINT, Device::QuitCb); this->SetPort(port); this->SetAddress(ip); this->StartRun(); } void Device::ReadEvent(Conn *conn){ Json::Reader reader; Json::Value data; //读取客户端数据 int len = conn->GetReadBufferLen(); char* str = new char[len+1]; conn->GetReadBuffer(str,len); //解析数据 if(reader.parse(str, data)){ string func = data["protocol"].asString(); this->call(conn,data["data"],func); }else{ Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); } } void Device::WriteEvent(Conn *conn){ } void Device::ConnectionEvent(Conn *conn){ Device *me = (Device*)conn->GetThread()->tcpConnect; me->vec.push_back(conn); printf("new client fd: %d\n", conn->GetFd()); } void Device::CloseEvent(Conn *conn, short events){ char str_fd[12]; sprintf(str_fd,"%d",conn->GetFd()); string sql = "select * from device where sock_fd = "+string(str_fd); MysqlHelper::MysqlData dataSet = this->mysql->queryRecord(sql); if (dataSet.size() != 0) { string up_sql = "where mac = \""+dataSet[0]["mac"]+"\""; MysqlHelper::RECORD_DATA recordChange; recordChange.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"2"))); recordChange.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,"0"))); this->mysql->updateRecord("device",recordChange,up_sql); data["id"] = dataSet[0]["id"]; }else{ printf("close sock_fd error,not find mysql socke_fd !!\n"); } printf("connection closed: %d\n", conn->GetFd()); vector<Conn*>::iterator iter=find(this->vec.begin(),this->vec.end(),conn); if(iter!=this->vec.end())this->vec.erase(iter); } void Device::QuitCb(int sig, short events, void *data) { Device *me = (Device*)data; me->StopRun(NULL); }
#include "Device.h" map<string,pfunc> device_api_list; Device::Device(){ this->mysql = new MysqlHelper(); this->mysql->init("127.0.0.1", "root", "root", "smart_car"); this->initApiList(); } Device::~Device(){ } void Device::initApiList() { device_api_list[API_DEVICE_INFO] = &Device::handlerDeverInfo; } void Device::call(Conn* &conn, Json::Value &request_data,const string func){ if(func.length() == 0){ Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); return; } if (device_api_list.count(func)) { (this->*(device_api_list[func]))(conn,request_data); } else { Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); } } void Device::sendData(Conn* &conn,const string resp_data){ char* data = new char[resp_data.length()+1]; resp_data.copy(data,resp_data.length(),0); conn->AddToWriteBuffer(data, resp_data.length()); delete[] data; } void Device::handlerDeverInfo(Conn* &conn, Json::Value &request_data){ Json::Value root; Json::Value data; string sql = "select * from device where "; string name = request_data["name"].asString(); string mac = request_data["mac"].asString(); //获取fd并转string int fd = conn->GetFd(); char intToStr[12]; sprintf(intToStr,"%d",fd); string str_fd = string(intToStr); //检查设备是否存在 sql = sql+"name=\""+name+"\" and mac=\""+mac+"\""; MysqlHelper::MysqlData dataSet = this->mysql->queryRecord(sql); if (dataSet.size() == 0) { //不存在,新增 MysqlHelper::RECORD_DATA record; record.insert(make_pair("name",make_pair(MysqlHelper::DB_STR,name))); record.insert(make_pair("mac",make_pair(MysqlHelper::DB_STR,mac))); record.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"1"))); record.insert(make_pair("status",make_pair(MysqlHelper::DB_INT,"1"))); record.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,str_fd))); int insert_id = this->mysql->insertRecord("device",record); data["id"] = insert_id; }else{ //存在,更新状态 string up_sql = "where mac = \""+mac+"\""; MysqlHelper::RECORD_DATA recordChange; recordChange.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"1"))); recordChange.insert(make_pair("status",make_pair(MysqlHelper::DB_INT,"1"))); recordChange.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,str_fd))); this->mysql->updateRecord("device",recordChange,up_sql); data["id"] = dataSet[0]["id"]; } root["protocol"] = API_DEVICE_INFO; root["data"] = data; this->sendData(conn,root.toStyledString()); } void Device::start(const char* ip,unsigned int port){ this->AddSignalEvent(SIGINT, Device::QuitCb); this->SetPort(port); this->SetAddress(ip); this->StartRun(); } void Device::ReadEvent(Conn *conn){ Json::Reader reader; Json::Value data; //读取客户端数据 int len = conn->GetReadBufferLen(); char* str = new char[len+1]; conn->GetReadBuffer(str,len); //解析数据 if(reader.parse(str, data)){ string func = data["protocol"].asString(); this->call(conn,data["data"],func); }else{ Json::Value root; Json::Value data; root["protocol"] = API_NOT_FIND; root["data"] = data; this->sendData(conn,root.toStyledString()); } } void Device::WriteEvent(Conn *conn){ } void Device::ConnectionEvent(Conn *conn){ Device *me = (Device*)conn->GetThread()->tcpConnect; me->vec.push_back(conn); printf("new client fd: %d\n", conn->GetFd()); } void Device::CloseEvent(Conn *conn, short events){ char str_fd[12]; sprintf(str_fd,"%d",conn->GetFd()); string sql = "select * from device where sock_fd = "+string(str_fd); MysqlHelper::MysqlData dataSet = this->mysql->queryRecord(sql); if (dataSet.size() != 0) { string up_sql = "where mac = \""+dataSet[0]["mac"]+"\""; MysqlHelper::RECORD_DATA recordChange; recordChange.insert(make_pair("online",make_pair(MysqlHelper::DB_INT,"2"))); recordChange.insert(make_pair("sock_fd",make_pair(MysqlHelper::DB_INT,"0"))); this->mysql->updateRecord("device",recordChange,up_sql); }else{ printf("close sock_fd error,not find mysql socke_fd !!\n"); } printf("connection closed: %d\n", conn->GetFd()); vector<Conn*>::iterator it; for(it=this->vec.begin();it!=this->vec.end();){ if(*(it)->GetFd() == data[0]["id"]){ it=iVec.erase(it); }else{ it++; } } for(int i=0;i<vec.size();i++){ if(this->vec[i].GetFd() == dataSet[0]["sock_fd"]){ } } vector<Conn*>::iterator iter=find(this->vec.begin(),this->vec.end(),conn); if(iter!=this->vec.end())this->vec.erase(iter); } void Device::QuitCb(int sig, short events, void *data) { Device *me = (Device*)data; me->StopRun(NULL); }
test service
test service
C++
mpl-2.0
chuanshuo843/SmartCar,chuanshuo843/SmartCar,chuanshuo843/SmartCar,chuanshuo843/SmartCar
955401773abc504a9ce73e0dba853393c042b502
main/src/hadd.cxx
main/src/hadd.cxx
/* This program will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... Author: Sven A. Schmidt, [email protected] Date: 13.2.2001 This code is based on the hadd.C example by Rene Brun and Dirk Geppert, which had a problem with directories more than one level deep. (see macro hadd_old.C for this previous implementation). I have tested this macro on rootfiles with one and two dimensional histograms, and two levels of subdirectories. Feel free to send comments or bug reports to me. */ #include "TFile.h" #include "TH1.h" #include "TTree.h" #include "TKey.h" #include <string.h> #include <iostream.h> TList *FileList; TFile *Target; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { if (argc < 4) { printf("******Error in invoking hadd\n"); printf("===> hadd targetfile source1 source2 ...\n"); printf(" This program will add histograms from a list of root files and write them\n"); printf(" to a target root file. The target file is newly created and must not be\n"); printf(" identical to one of the source files.\n"); printf(" supply at least two source files for this to make sense... ;-)\n"); return 1; } FileList = new TList(); cout << "Target file: " << argv[1] << endl; Target = TFile::Open( argv[1], "RECREATE" ); for ( int i = 2; i < argc; i++ ) { cout << "Source file " << i-1 << ": " << argv[i] << endl; FileList->Add( TFile::Open( argv[i] ) ); } MergeRootfile( Target, FileList ); return 0; } void MergeRootfile( TDirectory *target, TList *sourcelist ) { // Merge all files from sourcelist into the target directory. // The directory level (depth) is determined by the target directory's // current level // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey() )) { // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() ); if ( h2 ) { h1->Add( h2 ); delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->Write(); }
/* This program will add histograms from a list of root files and write them to a target root file. The target file is newly created and must not be identical to one of the source files. Syntax: hadd targetfile source1 source2 ... Author: Sven A. Schmidt, [email protected] Date: 13.2.2001 This code is based on the hadd.C example by Rene Brun and Dirk Geppert, which had a problem with directories more than one level deep. (see macro hadd_old.C for this previous implementation). I have tested this macro on rootfiles with one and two dimensional histograms, and two levels of subdirectories. Feel free to send comments or bug reports to me. */ #include "TFile.h" #include "TH1.h" #include "TTree.h" #include "TKey.h" #include "Riostream.h" #include <string.h> TList *FileList; TFile *Target; void MergeRootfile( TDirectory *target, TList *sourcelist ); int main( int argc, char **argv ) { if (argc < 4) { printf("******Error in invoking hadd\n"); printf("===> hadd targetfile source1 source2 ...\n"); printf(" This program will add histograms from a list of root files and write them\n"); printf(" to a target root file. The target file is newly created and must not be\n"); printf(" identical to one of the source files.\n"); printf(" supply at least two source files for this to make sense... ;-)\n"); return 1; } FileList = new TList(); cout << "Target file: " << argv[1] << endl; Target = TFile::Open( argv[1], "RECREATE" ); for ( int i = 2; i < argc; i++ ) { cout << "Source file " << i-1 << ": " << argv[i] << endl; FileList->Add( TFile::Open( argv[i] ) ); } MergeRootfile( Target, FileList ); return 0; } void MergeRootfile( TDirectory *target, TList *sourcelist ) { // Merge all files from sourcelist into the target directory. // The directory level (depth) is determined by the target directory's // current level // cout << "Target path: " << target->GetPath() << endl; TString path( (char*)strstr( target->GetPath(), ":" ) ); path.Remove( 0, 2 ); TFile *first_source = (TFile*)sourcelist->First(); first_source->cd( path ); TDirectory *current_sourcedir = gDirectory; // loop over all keys in this directory TIter nextkey( current_sourcedir->GetListOfKeys() ); TKey *key; while ( (key = (TKey*)nextkey() )) { // read object from first source file first_source->cd( path ); TObject *obj = key->ReadObj(); if ( obj->IsA()->InheritsFrom( "TH1" ) ) { // descendant of TH1 -> merge it // cout << "Merging histogram " << obj->GetName() << endl; TH1 *h1 = (TH1*)obj; // loop over all source files and add the content of the // correspondant histogram to the one pointed to by "h1" TFile *nextsource = (TFile*)sourcelist->After( first_source ); while ( nextsource ) { // make sure we are at the correct directory level by cd'ing to path nextsource->cd( path ); TH1 *h2 = (TH1*)gDirectory->Get( h1->GetName() ); if ( h2 ) { h1->Add( h2 ); delete h2; // don't know if this is necessary, i.e. if // h2 is created by the call to gDirectory above. } nextsource = (TFile*)sourcelist->After( nextsource ); } } else if ( obj->IsA()->InheritsFrom( "TDirectory" ) ) { // it's a subdirectory cout << "Found subdirectory " << obj->GetName() << endl; // create a new subdir of same name and title in the target file target->cd(); TDirectory *newdir = target->mkdir( obj->GetName(), obj->GetTitle() ); // newdir is now the starting point of another round of merging // newdir still knows its depth within the target file via // GetPath(), so we can still figure out where we are in the recursion MergeRootfile( newdir, sourcelist ); } else { // object is of no type that we know or can handle cout << "Unknown object type, name: " << obj->GetName() << " title: " << obj->GetTitle() << endl; } // now write the merged histogram (which is "in" obj) to the target file // note that this will just store obj in the current directory level, // which is not persistent until the complete directory itself is stored // by "target->Write()" below if ( obj ) { target->cd(); obj->Write( key->GetName() ); } } // while ( ( TKey *key = (TKey*)nextkey() ) ) // save modifications to target file target->Write(); }
change iostream.h to Riostream.h.
change iostream.h to Riostream.h. git-svn-id: acec3fd5b7ea1eb9e79d6329d318e8118ee2e14f@4350 27541ba8-7e3a-0410-8455-c3a389f83636
C++
lgpl-2.1
Dr15Jones/root,evgeny-boger/root,cxx-hep/root-cern,omazapa/root,davidlt/root,georgtroska/root,satyarth934/root,olifre/root,Duraznos/root,zzxuanyuan/root,Y--/root,mhuwiler/rootauto,georgtroska/root,sbinet/cxx-root,olifre/root,sbinet/cxx-root,vukasinmilosevic/root,esakellari/my_root_for_test,simonpf/root,Dr15Jones/root,pspe/root,mattkretz/root,esakellari/root,karies/root,thomaskeck/root,esakellari/my_root_for_test,simonpf/root,krafczyk/root,strykejern/TTreeReader,kirbyherm/root-r-tools,esakellari/root,mattkretz/root,pspe/root,bbockelm/root,agarciamontoro/root,zzxuanyuan/root,abhinavmoudgil95/root,karies/root,bbockelm/root,lgiommi/root,karies/root,veprbl/root,sirinath/root,sbinet/cxx-root,zzxuanyuan/root,jrtomps/root,esakellari/root,nilqed/root,omazapa/root,gganis/root,buuck/root,bbockelm/root,beniz/root,tc3t/qoot,davidlt/root,kirbyherm/root-r-tools,jrtomps/root,davidlt/root,cxx-hep/root-cern,ffurano/root5,mhuwiler/rootauto,alexschlueter/cern-root,root-mirror/root,esakellari/my_root_for_test,olifre/root,satyarth934/root,omazapa/root,satyarth934/root,krafczyk/root,omazapa/root,smarinac/root,satyarth934/root,lgiommi/root,jrtomps/root,bbockelm/root,Duraznos/root,esakellari/root,krafczyk/root,lgiommi/root,esakellari/root,gbitzes/root,jrtomps/root,smarinac/root,sawenzel/root,perovic/root,pspe/root,BerserkerTroll/root,tc3t/qoot,beniz/root,karies/root,root-mirror/root,thomaskeck/root,gganis/root,agarciamontoro/root,evgeny-boger/root,kirbyherm/root-r-tools,zzxuanyuan/root-compressor-dummy,smarinac/root,satyarth934/root,satyarth934/root,smarinac/root,CristinaCristescu/root,vukasinmilosevic/root,satyarth934/root,Duraznos/root,0x0all/ROOT,nilqed/root,mkret2/root,Y--/root,esakellari/root,krafczyk/root,evgeny-boger/root,pspe/root,BerserkerTroll/root,Y--/root,omazapa/root,sawenzel/root,davidlt/root,simonpf/root,CristinaCristescu/root,krafczyk/root,sawenzel/root,BerserkerTroll/root,kirbyherm/root-r-tools,arch1tect0r/root,georgtroska/root,strykejern/TTreeReader,sirinath/root,davidlt/root,vukasinmilosevic/root,vukasinmilosevic/root,mhuwiler/rootauto,jrtomps/root,beniz/root,mattkretz/root,mhuwiler/rootauto,mkret2/root,bbockelm/root,kirbyherm/root-r-tools,davidlt/root,lgiommi/root,veprbl/root,omazapa/root,root-mirror/root,smarinac/root,jrtomps/root,esakellari/my_root_for_test,arch1tect0r/root,zzxuanyuan/root,jrtomps/root,esakellari/my_root_for_test,zzxuanyuan/root,cxx-hep/root-cern,agarciamontoro/root,BerserkerTroll/root,dfunke/root,smarinac/root,sirinath/root,beniz/root,bbockelm/root,georgtroska/root,Y--/root,evgeny-boger/root,mhuwiler/rootauto,beniz/root,veprbl/root,agarciamontoro/root,bbockelm/root,sawenzel/root,gganis/root,zzxuanyuan/root,zzxuanyuan/root-compressor-dummy,jrtomps/root,omazapa/root,mkret2/root,Y--/root,mhuwiler/rootauto,Dr15Jones/root,karies/root,evgeny-boger/root,Y--/root,abhinavmoudgil95/root,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root-compressor-dummy,zzxuanyuan/root,karies/root,veprbl/root,Dr15Jones/root,alexschlueter/cern-root,gganis/root,zzxuanyuan/root,arch1tect0r/root,arch1tect0r/root,strykejern/TTreeReader,omazapa/root-old,sirinath/root,satyarth934/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,Duraznos/root,veprbl/root,mkret2/root,perovic/root,vukasinmilosevic/root,gganis/root,CristinaCristescu/root,georgtroska/root,kirbyherm/root-r-tools,evgeny-boger/root,pspe/root,tc3t/qoot,BerserkerTroll/root,mkret2/root,nilqed/root,0x0all/ROOT,arch1tect0r/root,esakellari/my_root_for_test,mattkretz/root,abhinavmoudgil95/root,mattkretz/root,buuck/root,sawenzel/root,veprbl/root,mhuwiler/rootauto,ffurano/root5,beniz/root,omazapa/root-old,sirinath/root,jrtomps/root,0x0all/ROOT,vukasinmilosevic/root,omazapa/root,CristinaCristescu/root,BerserkerTroll/root,mattkretz/root,gganis/root,buuck/root,simonpf/root,CristinaCristescu/root,tc3t/qoot,agarciamontoro/root,tc3t/qoot,dfunke/root,mhuwiler/rootauto,mattkretz/root,mattkretz/root,olifre/root,georgtroska/root,arch1tect0r/root,perovic/root,dfunke/root,alexschlueter/cern-root,perovic/root,cxx-hep/root-cern,thomaskeck/root,root-mirror/root,esakellari/root,georgtroska/root,omazapa/root-old,nilqed/root,thomaskeck/root,thomaskeck/root,gganis/root,sbinet/cxx-root,gganis/root,sbinet/cxx-root,gbitzes/root,mkret2/root,BerserkerTroll/root,gbitzes/root,mhuwiler/rootauto,BerserkerTroll/root,zzxuanyuan/root,georgtroska/root,davidlt/root,veprbl/root,Duraznos/root,0x0all/ROOT,gganis/root,gganis/root,gganis/root,agarciamontoro/root,perovic/root,root-mirror/root,vukasinmilosevic/root,sirinath/root,abhinavmoudgil95/root,esakellari/my_root_for_test,simonpf/root,sawenzel/root,bbockelm/root,esakellari/my_root_for_test,cxx-hep/root-cern,georgtroska/root,perovic/root,thomaskeck/root,root-mirror/root,zzxuanyuan/root-compressor-dummy,strykejern/TTreeReader,pspe/root,zzxuanyuan/root,pspe/root,davidlt/root,lgiommi/root,pspe/root,simonpf/root,ffurano/root5,esakellari/root,zzxuanyuan/root-compressor-dummy,thomaskeck/root,krafczyk/root,Y--/root,0x0all/ROOT,krafczyk/root,beniz/root,0x0all/ROOT,perovic/root,sirinath/root,buuck/root,lgiommi/root,omazapa/root-old,esakellari/root,thomaskeck/root,davidlt/root,sbinet/cxx-root,omazapa/root-old,CristinaCristescu/root,nilqed/root,Duraznos/root,root-mirror/root,bbockelm/root,vukasinmilosevic/root,zzxuanyuan/root-compressor-dummy,Duraznos/root,olifre/root,0x0all/ROOT,krafczyk/root,sirinath/root,mattkretz/root,strykejern/TTreeReader,lgiommi/root,lgiommi/root,perovic/root,gbitzes/root,root-mirror/root,beniz/root,strykejern/TTreeReader,mkret2/root,veprbl/root,simonpf/root,sbinet/cxx-root,zzxuanyuan/root-compressor-dummy,Y--/root,karies/root,satyarth934/root,arch1tect0r/root,perovic/root,vukasinmilosevic/root,karies/root,Dr15Jones/root,gbitzes/root,simonpf/root,buuck/root,Duraznos/root,vukasinmilosevic/root,bbockelm/root,lgiommi/root,BerserkerTroll/root,buuck/root,jrtomps/root,simonpf/root,alexschlueter/cern-root,mkret2/root,mhuwiler/rootauto,0x0all/ROOT,kirbyherm/root-r-tools,tc3t/qoot,Y--/root,olifre/root,pspe/root,mkret2/root,tc3t/qoot,Duraznos/root,beniz/root,omazapa/root-old,beniz/root,Y--/root,smarinac/root,sawenzel/root,krafczyk/root,sawenzel/root,BerserkerTroll/root,sirinath/root,omazapa/root,abhinavmoudgil95/root,omazapa/root-old,BerserkerTroll/root,veprbl/root,ffurano/root5,dfunke/root,ffurano/root5,pspe/root,karies/root,0x0all/ROOT,smarinac/root,buuck/root,satyarth934/root,nilqed/root,arch1tect0r/root,esakellari/my_root_for_test,esakellari/root,sbinet/cxx-root,zzxuanyuan/root,dfunke/root,arch1tect0r/root,agarciamontoro/root,jrtomps/root,mattkretz/root,krafczyk/root,sawenzel/root,sawenzel/root,CristinaCristescu/root,olifre/root,tc3t/qoot,Duraznos/root,dfunke/root,evgeny-boger/root,olifre/root,abhinavmoudgil95/root,evgeny-boger/root,lgiommi/root,agarciamontoro/root,cxx-hep/root-cern,sbinet/cxx-root,mhuwiler/rootauto,dfunke/root,alexschlueter/cern-root,nilqed/root,dfunke/root,buuck/root,omazapa/root,evgeny-boger/root,nilqed/root,perovic/root,gbitzes/root,Dr15Jones/root,olifre/root,evgeny-boger/root,sbinet/cxx-root,georgtroska/root,buuck/root,evgeny-boger/root,georgtroska/root,bbockelm/root,karies/root,alexschlueter/cern-root,tc3t/qoot,esakellari/my_root_for_test,arch1tect0r/root,abhinavmoudgil95/root,gbitzes/root,tc3t/qoot,pspe/root,mattkretz/root,perovic/root,sirinath/root,abhinavmoudgil95/root,cxx-hep/root-cern,Dr15Jones/root,abhinavmoudgil95/root,nilqed/root,beniz/root,root-mirror/root,strykejern/TTreeReader,olifre/root,thomaskeck/root,zzxuanyuan/root-compressor-dummy,gbitzes/root,gbitzes/root,ffurano/root5,Duraznos/root,nilqed/root,zzxuanyuan/root-compressor-dummy,root-mirror/root,CristinaCristescu/root,buuck/root,omazapa/root-old,buuck/root,dfunke/root,CristinaCristescu/root,Y--/root,omazapa/root-old,arch1tect0r/root,CristinaCristescu/root,gbitzes/root,thomaskeck/root,sawenzel/root,smarinac/root,agarciamontoro/root,CristinaCristescu/root,davidlt/root,dfunke/root,olifre/root,ffurano/root5,agarciamontoro/root,lgiommi/root,agarciamontoro/root,abhinavmoudgil95/root,dfunke/root,karies/root,sbinet/cxx-root,smarinac/root,satyarth934/root,mkret2/root,sirinath/root,cxx-hep/root-cern,alexschlueter/cern-root,vukasinmilosevic/root,esakellari/root,davidlt/root,omazapa/root-old,veprbl/root,omazapa/root-old,krafczyk/root,veprbl/root,omazapa/root,simonpf/root,mkret2/root,nilqed/root,abhinavmoudgil95/root,zzxuanyuan/root,gbitzes/root,simonpf/root
f301f882768b20405e2385fe09bf42baafd64298
net/base/force_tls_state.cc
net/base/force_tls_state.cc
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/force_tls_state.h" #include "base/json_reader.h" #include "base/json_writer.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/values.h" #include "googleurl/src/gurl.h" #include "net/base/registry_controlled_domain.h" namespace net { ForceTLSState::ForceTLSState() : delegate_(NULL) { } void ForceTLSState::DidReceiveHeader(const GURL& url, const std::string& value) { int max_age; bool include_subdomains; if (!ParseHeader(value, &max_age, &include_subdomains)) return; base::Time current_time(base::Time::Now()); base::TimeDelta max_age_delta = base::TimeDelta::FromSeconds(max_age); base::Time expiry = current_time + max_age_delta; EnableHost(url.host(), expiry, include_subdomains); } void ForceTLSState::EnableHost(const std::string& host, base::Time expiry, bool include_subdomains) { // TODO(abarth): Canonicalize host. AutoLock lock(lock_); State state = {expiry, include_subdomains}; enabled_hosts_[host] = state; DirtyNotify(); } bool ForceTLSState::IsEnabledForHost(const std::string& host) { // TODO(abarth): Canonicalize host. // TODO: check for subdomains too. AutoLock lock(lock_); std::map<std::string, State>::iterator i = enabled_hosts_.find(host); if (i == enabled_hosts_.end()) return false; base::Time current_time(base::Time::Now()); if (current_time > i->second.expiry) { enabled_hosts_.erase(i); DirtyNotify(); return false; } return true; } // "X-Force-TLS" ":" "max-age" "=" delta-seconds *1INCLUDESUBDOMAINS // INCLUDESUBDOMAINS = [ " includeSubDomains" ] bool ForceTLSState::ParseHeader(const std::string& value, int* max_age, bool* include_subdomains) { DCHECK(max_age); DCHECK(include_subdomains); int max_age_candidate; enum ParserState { START, AFTER_MAX_AGE_LABEL, AFTER_MAX_AGE_EQUALS, AFTER_MAX_AGE, AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER, AFTER_INCLUDE_SUBDOMAINS, } state = START; StringTokenizer tokenizer(value, " ="); tokenizer.set_options(StringTokenizer::RETURN_DELIMS); while (tokenizer.GetNext()) { DCHECK(!tokenizer.token_is_delim() || tokenizer.token().length() == 1); DCHECK(tokenizer.token_is_delim() || *tokenizer.token_begin() != ' '); switch (state) { case START: if (*tokenizer.token_begin() == ' ') continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "max-age")) return false; state = AFTER_MAX_AGE_LABEL; break; case AFTER_MAX_AGE_LABEL: if (*tokenizer.token_begin() == ' ') continue; if (*tokenizer.token_begin() != '=') return false; DCHECK(tokenizer.token().length() == 1); state = AFTER_MAX_AGE_EQUALS; break; case AFTER_MAX_AGE_EQUALS: if (*tokenizer.token_begin() == ' ') continue; if (!StringToInt(tokenizer.token(), &max_age_candidate)) return false; if (max_age_candidate < 0) return false; state = AFTER_MAX_AGE; break; case AFTER_MAX_AGE: if (*tokenizer.token_begin() != ' ') return false; state = AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER; break; case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: if (*tokenizer.token_begin() == ' ') continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "includesubdomains")) return false; state = AFTER_INCLUDE_SUBDOMAINS; break; case AFTER_INCLUDE_SUBDOMAINS: if (*tokenizer.token_begin() != ' ') return false; break; default: NOTREACHED(); } } // We've consumed all the input. Let's see what state we ended up in. switch (state) { case START: case AFTER_MAX_AGE_LABEL: case AFTER_MAX_AGE_EQUALS: return false; case AFTER_MAX_AGE: case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: *max_age = max_age_candidate; *include_subdomains = false; return true; case AFTER_INCLUDE_SUBDOMAINS: *max_age = max_age_candidate; *include_subdomains = true; return true; default: NOTREACHED(); return false; } } void ForceTLSState::SetDelegate(ForceTLSState::Delegate* delegate) { AutoLock lock(lock_); delegate_ = delegate; } bool ForceTLSState::Serialise(std::string* output) { AutoLock lock(lock_); DictionaryValue toplevel; for (std::map<std::string, State>::const_iterator i = enabled_hosts_.begin(); i != enabled_hosts_.end(); ++i) { DictionaryValue* state = new DictionaryValue; state->SetBoolean(L"include_subdomains", i->second.include_subdomains); state->SetReal(L"expiry", i->second.expiry.ToDoubleT()); toplevel.Set(ASCIIToWide(i->first), state); } JSONWriter::Write(&toplevel, true /* pretty print */, output); return true; } bool ForceTLSState::Deserialise(const std::string& input) { AutoLock lock(lock_); enabled_hosts_.clear(); scoped_ptr<Value> value( JSONReader::Read(input, false /* do not allow trailing commas */)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) return false; DictionaryValue* dict_value = reinterpret_cast<DictionaryValue*>(value.get()); const base::Time current_time(base::Time::Now()); for (DictionaryValue::key_iterator i = dict_value->begin_keys(); i != dict_value->end_keys(); ++i) { DictionaryValue* state; if (!dict_value->GetDictionary(*i, &state)) continue; const std::string host = WideToASCII(*i); bool include_subdomains; double expiry; if (!state->GetBoolean(L"include_subdomains", &include_subdomains) || !state->GetReal(L"expiry", &expiry)) { continue; } base::Time expiry_time = base::Time::FromDoubleT(expiry); if (expiry_time <= current_time) continue; State new_state = { expiry_time, include_subdomains }; enabled_hosts_[host] = new_state; } return enabled_hosts_.size(); } void ForceTLSState::DirtyNotify() { if (delegate_) delegate_->StateIsDirty(this); } } // namespace
// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/base/force_tls_state.h" #include "base/json_reader.h" #include "base/json_writer.h" #include "base/logging.h" #include "base/scoped_ptr.h" #include "base/string_tokenizer.h" #include "base/string_util.h" #include "base/values.h" #include "googleurl/src/gurl.h" #include "net/base/registry_controlled_domain.h" namespace net { ForceTLSState::ForceTLSState() : delegate_(NULL) { } void ForceTLSState::DidReceiveHeader(const GURL& url, const std::string& value) { int max_age; bool include_subdomains; if (!ParseHeader(value, &max_age, &include_subdomains)) return; base::Time current_time(base::Time::Now()); base::TimeDelta max_age_delta = base::TimeDelta::FromSeconds(max_age); base::Time expiry = current_time + max_age_delta; EnableHost(url.host(), expiry, include_subdomains); } void ForceTLSState::EnableHost(const std::string& host, base::Time expiry, bool include_subdomains) { // TODO(abarth): Canonicalize host. AutoLock lock(lock_); State state = {expiry, include_subdomains}; enabled_hosts_[host] = state; DirtyNotify(); } bool ForceTLSState::IsEnabledForHost(const std::string& host) { // TODO(abarth): Canonicalize host. // TODO: check for subdomains too. AutoLock lock(lock_); std::map<std::string, State>::iterator i = enabled_hosts_.find(host); if (i == enabled_hosts_.end()) return false; base::Time current_time(base::Time::Now()); if (current_time > i->second.expiry) { enabled_hosts_.erase(i); DirtyNotify(); return false; } return true; } // "X-Force-TLS" ":" "max-age" "=" delta-seconds *1INCLUDESUBDOMAINS // INCLUDESUBDOMAINS = [ " includeSubDomains" ] bool ForceTLSState::ParseHeader(const std::string& value, int* max_age, bool* include_subdomains) { DCHECK(max_age); DCHECK(include_subdomains); int max_age_candidate; enum ParserState { START, AFTER_MAX_AGE_LABEL, AFTER_MAX_AGE_EQUALS, AFTER_MAX_AGE, AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER, AFTER_INCLUDE_SUBDOMAINS, } state = START; StringTokenizer tokenizer(value, " ="); tokenizer.set_options(StringTokenizer::RETURN_DELIMS); while (tokenizer.GetNext()) { DCHECK(!tokenizer.token_is_delim() || tokenizer.token().length() == 1); DCHECK(tokenizer.token_is_delim() || *tokenizer.token_begin() != ' '); switch (state) { case START: if (*tokenizer.token_begin() == ' ') continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "max-age")) return false; state = AFTER_MAX_AGE_LABEL; break; case AFTER_MAX_AGE_LABEL: if (*tokenizer.token_begin() == ' ') continue; if (*tokenizer.token_begin() != '=') return false; DCHECK(tokenizer.token().length() == 1); state = AFTER_MAX_AGE_EQUALS; break; case AFTER_MAX_AGE_EQUALS: if (*tokenizer.token_begin() == ' ') continue; if (!StringToInt(tokenizer.token(), &max_age_candidate)) return false; if (max_age_candidate < 0) return false; state = AFTER_MAX_AGE; break; case AFTER_MAX_AGE: if (*tokenizer.token_begin() != ' ') return false; state = AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER; break; case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: if (*tokenizer.token_begin() == ' ') continue; if (!LowerCaseEqualsASCII(tokenizer.token(), "includesubdomains")) return false; state = AFTER_INCLUDE_SUBDOMAINS; break; case AFTER_INCLUDE_SUBDOMAINS: if (*tokenizer.token_begin() != ' ') return false; break; default: NOTREACHED(); } } // We've consumed all the input. Let's see what state we ended up in. switch (state) { case START: case AFTER_MAX_AGE_LABEL: case AFTER_MAX_AGE_EQUALS: return false; case AFTER_MAX_AGE: case AFTER_MAX_AGE_INCLUDE_SUB_DOMAINS_DELIMITER: *max_age = max_age_candidate; *include_subdomains = false; return true; case AFTER_INCLUDE_SUBDOMAINS: *max_age = max_age_candidate; *include_subdomains = true; return true; default: NOTREACHED(); return false; } } void ForceTLSState::SetDelegate(ForceTLSState::Delegate* delegate) { AutoLock lock(lock_); delegate_ = delegate; } bool ForceTLSState::Serialise(std::string* output) { AutoLock lock(lock_); DictionaryValue toplevel; for (std::map<std::string, State>::const_iterator i = enabled_hosts_.begin(); i != enabled_hosts_.end(); ++i) { DictionaryValue* state = new DictionaryValue; state->SetBoolean(L"include_subdomains", i->second.include_subdomains); state->SetReal(L"expiry", i->second.expiry.ToDoubleT()); toplevel.Set(ASCIIToWide(i->first), state); } JSONWriter::Write(&toplevel, true /* pretty print */, output); return true; } bool ForceTLSState::Deserialise(const std::string& input) { AutoLock lock(lock_); enabled_hosts_.clear(); scoped_ptr<Value> value( JSONReader::Read(input, false /* do not allow trailing commas */)); if (!value.get() || !value->IsType(Value::TYPE_DICTIONARY)) return false; DictionaryValue* dict_value = reinterpret_cast<DictionaryValue*>(value.get()); const base::Time current_time(base::Time::Now()); for (DictionaryValue::key_iterator i = dict_value->begin_keys(); i != dict_value->end_keys(); ++i) { DictionaryValue* state; if (!dict_value->GetDictionary(*i, &state)) continue; const std::string host = WideToASCII(*i); bool include_subdomains; double expiry; if (!state->GetBoolean(L"include_subdomains", &include_subdomains) || !state->GetReal(L"expiry", &expiry)) { continue; } base::Time expiry_time = base::Time::FromDoubleT(expiry); if (expiry_time <= current_time) continue; State new_state = { expiry_time, include_subdomains }; enabled_hosts_[host] = new_state; } return enabled_hosts_.size() > 0; } void ForceTLSState::DirtyNotify() { if (delegate_) delegate_->StateIsDirty(this); } } // namespace
Build fix: VC warning
Build fix: VC warning git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@25385 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
C++
bsd-3-clause
wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser
06b24df513b701d5fabac8181dc421adea37ebed
network/epoll/tcpsocket.cpp
network/epoll/tcpsocket.cpp
/* * ZSUMMER License * ----------- * * ZSUMMER is licensed under the terms of the MIT license reproduced below. * This means that ZSUMMER is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2013 YaweiZhang <[email protected]>. * * 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. * * =============================================================================== * * (end of COPYRIGHT) */ #include "tcpsocket.h" #include "epoll.h" using namespace zsummer; zsummer::network::ITcpSocket * zsummer::network::CreateTcpSocket() { return new CTcpSocket; } void zsummer::network::DestroyTcpSocket(zsummer::network::ITcpSocket * s) { delete s; } CTcpSocket::CTcpSocket() { m_cb = NULL; m_ios = NULL; memset(&m_handle, 0, sizeof(m_handle)); m_bNeedDestroy = false; m_iRecvLen = 0; m_pRecvBuf = NULL; m_iSendLen = 0; m_pSendBuf = NULL; } CTcpSocket::~CTcpSocket() { } bool CTcpSocket::Initialize(IIOServer * ios, ITcpSocketCallback * cb) { m_ios = ios; m_cb = cb; if (m_handle._fd != 0) { m_handle._event.events = 0; if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_ADD, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::Initialize()" << this << " EPOLL_CTL_ADD error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); return false; } } return true; } bool CTcpSocket::DoConnect(const char *ip, unsigned short port) { if (m_cb == NULL) { LCE("CTcpSocket::DoConnect()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoConnect()" << this << " IIOServer not bind!"); return false; } if (m_handle._fd != 0) { LCE("CTcpSocket::DoConnect()" << this << " DoConnect ERR: fd aready used!"); return false; } m_handle._fd = socket(AF_INET, SOCK_STREAM, 0); if (m_handle._fd == -1) { LCE("CTcpSocket::DoConnect()" << this << " socket create err errno =" << strerror(errno)); return false; } SetNonBlock(m_handle._fd); SetNoDelay(m_handle._fd); m_handle._event.events = EPOLLOUT; m_handle._event.data.ptr = &m_handle; m_handle._ptr = this; m_handle._type = tagRegister::REG_CONNECT; m_addr.sin_family = AF_INET; m_addr.sin_addr.s_addr = inet_addr(ip); m_addr.sin_port = htons(port); if (connect(m_handle._fd, (sockaddr *) &m_addr, sizeof(m_addr))!=0) { LCE("CTcpSocket::DoConnect()" << this << " ::connect error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); } if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_ADD, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoConnect()" << this << " EPOLL_CTL_ADD error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); return false; } return true; } bool CTcpSocket::GetPeerInfo(unsigned int * addr, unsigned short *port) { *addr = (unsigned int)m_addr.sin_addr.s_addr; *port = ntohs(m_addr.sin_port); return true; } bool CTcpSocket::DoSend(char * buf, unsigned int len) { if (m_cb == NULL) { LCE("CTcpSocket::DoSend()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoSend()" << this << " IIOServer not bind!"); return false; } if (len == 0) { LCE("CTcpSocket::DoSend()" << this << " argument err! len ==0"); return false; } if (m_pSendBuf != NULL || m_iSendLen != 0) { LCE("CTcpSocket::DoSend()" << this << " (m_pSendBuf != NULL || m_iSendLen != 0) == TRUE"); return false; } if (m_handle._event.events & EPOLLOUT) { LCE("CTcpSocket::DoSend()" << this << " (m_handle._event.events & EPOLLOUT) == TRUE"); return false; } m_pSendBuf = buf; m_iSendLen = len; m_handle._event.events = m_handle._event.events|EPOLLOUT; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoSend()" << this << " EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } //LOGI("do send"); return true; } bool CTcpSocket::DoRecv(char * buf, unsigned int len) { if (m_cb == NULL) { LCE("CTcpSocket::DoRecv()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoRecv()" << this << " IIOServer not bind!"); return false; } if (len == 0 ) { LCE("CTcpSocket::DoRecv()" << this << " argument err !!! len==0"); return false; } if (m_pRecvBuf != NULL || m_iRecvLen != 0) { LCE("CTcpSocket::DoRecv()" << this << " (m_pRecvBuf != NULL || m_iRecvLen != 0) == TRUE"); return false; } if (m_handle._event.events & EPOLLIN) { LCE("CTcpSocket::DoRecv()" << this << " (m_handle._event.events & EPOLLIN) == TRUE"); return false; } m_pRecvBuf = buf; m_iRecvLen = len; m_handle._event.events = m_handle._event.events|EPOLLIN; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoRecv()" << this << " EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } return true; } bool CTcpSocket::OnEPOLLMessage(int type, int flag) { if (m_handle._type == tagRegister::REG_CONNECT) { if (flag & EPOLLOUT) { m_handle._event.events = /*EPOLLONESHOT*/ 0; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " connect true & EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); m_cb->OnConnect(false); return false; } m_handle._type = tagRegister::REG_ESTABLISHED; m_cb->OnConnect(true); } else { if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_DEL, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " connect false & EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); } close(m_handle._fd); m_handle._fd = 0; m_cb->OnConnect(false); } return true; } if (flag & EPOLLHUP || flag & EPOLLERR ) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " EPOLLHUP EPOLLERR error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } if (flag & EPOLLIN) { if (m_pRecvBuf == NULL || m_iRecvLen == 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " recv error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", m_pSendBuf=" <<(void*)m_pSendBuf << ", m_iSendLen=" << m_iSendLen); } else { int ret = recv(m_handle._fd, m_pRecvBuf, m_iRecvLen, 0); if (ret == 0 || (ret ==-1 && (errno !=EAGAIN && errno != EWOULDBLOCK)) ) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " recv error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", ret=" << ret << ", errno=" << strerror(errno)); Close(); return false; } if (ret != -1) { m_pRecvBuf = NULL; m_iRecvLen = 0; m_handle._event.events = m_handle._event.events& ~EPOLLIN; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << "recv EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } m_cb->OnRecv(ret); } } } if (flag & EPOLLOUT) { if (m_pSendBuf == NULL || m_iSendLen == 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " send error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", m_pSendBuf=" <<(void*)m_pSendBuf << ", m_iSendLen=" << m_iSendLen); } else { int ret = send(m_handle._fd, m_pSendBuf, m_iSendLen, 0); if (ret == -1 && (errno != EAGAIN && errno != EWOULDBLOCK)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " send error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", ret=" << ret << ", errno=" << strerror(errno)); Close(); return false; } if (ret != -1) { m_pSendBuf = NULL; m_iSendLen = 0; m_handle._event.events = m_handle._event.events& ~EPOLLOUT; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << "send EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } m_cb->OnSend(ret); } } } return true; } bool CTcpSocket::Close() { if (m_handle._type == tagRegister::REG_ESTABLISHED) { m_handle._type = tagRegister::REG_INVALIDE; if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_DEL, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::Close()" << this << " EPOLL_CTL_DEL error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); } shutdown(m_handle._fd, SHUT_RDWR); close(m_handle._fd); ((CIOServer*)m_ios)->PostMsg(PCK_SOCKET_CLOSE, this); } return true; } void CTcpSocket::OnPostClose() { m_cb->OnClose(); if (m_bNeedDestroy) { DestroyTcpSocket(this); } }
/* * ZSUMMER License * ----------- * * ZSUMMER is licensed under the terms of the MIT license reproduced below. * This means that ZSUMMER is free software and can be used for both academic * and commercial purposes at absolutely no cost. * * * =============================================================================== * * Copyright (C) 2010-2013 YaweiZhang <[email protected]>. * * 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. * * =============================================================================== * * (end of COPYRIGHT) */ #include "tcpsocket.h" #include "epoll.h" using namespace zsummer; zsummer::network::ITcpSocket * zsummer::network::CreateTcpSocket() { return new CTcpSocket; } void zsummer::network::DestroyTcpSocket(zsummer::network::ITcpSocket * s) { delete s; } CTcpSocket::CTcpSocket() { m_cb = NULL; m_ios = NULL; memset(&m_handle, 0, sizeof(m_handle)); m_bNeedDestroy = false; m_iRecvLen = 0; m_pRecvBuf = NULL; m_iSendLen = 0; m_pSendBuf = NULL; } CTcpSocket::~CTcpSocket() { } bool CTcpSocket::Initialize(IIOServer * ios, ITcpSocketCallback * cb) { m_ios = ios; m_cb = cb; if (m_handle._fd != 0) { m_handle._event.events = 0; if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_ADD, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::Initialize()" << this << " EPOLL_CTL_ADD error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); return false; } } return true; } bool CTcpSocket::DoConnect(const char *ip, unsigned short port) { if (m_cb == NULL) { LCE("CTcpSocket::DoConnect()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoConnect()" << this << " IIOServer not bind!"); return false; } if (m_handle._fd != 0) { LCE("CTcpSocket::DoConnect()" << this << " DoConnect ERR: fd aready used!"); return false; } m_handle._fd = socket(AF_INET, SOCK_STREAM, 0); if (m_handle._fd == -1) { LCE("CTcpSocket::DoConnect()" << this << " socket create err errno =" << strerror(errno)); return false; } SetNonBlock(m_handle._fd); SetNoDelay(m_handle._fd); m_handle._event.events = EPOLLOUT; m_handle._event.data.ptr = &m_handle; m_handle._ptr = this; m_handle._type = tagRegister::REG_CONNECT; m_addr.sin_family = AF_INET; m_addr.sin_addr.s_addr = inet_addr(ip); m_addr.sin_port = htons(port); int ret = connect(m_handle._fd, (sockaddr *) &m_addr, sizeof(m_addr)); if (ret!=0 && errno != EINPROGRESS) { LCE("CTcpSocket::DoConnect()" << this << " ::connect error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); return false; } if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_ADD, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoConnect()" << this << " EPOLL_CTL_ADD error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); return false; } return true; } bool CTcpSocket::GetPeerInfo(unsigned int * addr, unsigned short *port) { *addr = (unsigned int)m_addr.sin_addr.s_addr; *port = ntohs(m_addr.sin_port); return true; } bool CTcpSocket::DoSend(char * buf, unsigned int len) { if (m_cb == NULL) { LCE("CTcpSocket::DoSend()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoSend()" << this << " IIOServer not bind!"); return false; } if (len == 0) { LCE("CTcpSocket::DoSend()" << this << " argument err! len ==0"); return false; } if (m_pSendBuf != NULL || m_iSendLen != 0) { LCE("CTcpSocket::DoSend()" << this << " (m_pSendBuf != NULL || m_iSendLen != 0) == TRUE"); return false; } if (m_handle._event.events & EPOLLOUT) { LCE("CTcpSocket::DoSend()" << this << " (m_handle._event.events & EPOLLOUT) == TRUE"); return false; } m_pSendBuf = buf; m_iSendLen = len; m_handle._event.events = m_handle._event.events|EPOLLOUT; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoSend()" << this << " EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } //LOGI("do send"); return true; } bool CTcpSocket::DoRecv(char * buf, unsigned int len) { if (m_cb == NULL) { LCE("CTcpSocket::DoRecv()" << this << " callback not set!"); return false; } if (m_ios == NULL) { LCE("CTcpSocket::DoRecv()" << this << " IIOServer not bind!"); return false; } if (len == 0 ) { LCE("CTcpSocket::DoRecv()" << this << " argument err !!! len==0"); return false; } if (m_pRecvBuf != NULL || m_iRecvLen != 0) { LCE("CTcpSocket::DoRecv()" << this << " (m_pRecvBuf != NULL || m_iRecvLen != 0) == TRUE"); return false; } if (m_handle._event.events & EPOLLIN) { LCE("CTcpSocket::DoRecv()" << this << " (m_handle._event.events & EPOLLIN) == TRUE"); return false; } m_pRecvBuf = buf; m_iRecvLen = len; m_handle._event.events = m_handle._event.events|EPOLLIN; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::DoRecv()" << this << " EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } return true; } bool CTcpSocket::OnEPOLLMessage(int type, int flag) { if (m_handle._type == tagRegister::REG_CONNECT) { if (flag & EPOLLOUT) { m_handle._event.events = /*EPOLLONESHOT*/ 0; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " connect true & EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); m_cb->OnConnect(false); return false; } m_handle._type = tagRegister::REG_ESTABLISHED; m_cb->OnConnect(true); } else { if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_DEL, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " connect false & EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); } close(m_handle._fd); m_handle._fd = 0; m_cb->OnConnect(false); } return true; } if (flag & EPOLLHUP) { //LCI("CTcpSocket::OnEPOLLMessage()" << this << " EPOLLHUP error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", events=" << flag); Close(); return false; } if (flag & EPOLLERR) { //LCI("CTcpSocket::OnEPOLLMessage()" << this << " EPOLLERR error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", events=" << flag); Close(); return false; } if (flag & EPOLLIN) { if (m_pRecvBuf == NULL || m_iRecvLen == 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " recv error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", m_pSendBuf=" <<(void*)m_pSendBuf << ", m_iSendLen=" << m_iSendLen); } else { int ret = recv(m_handle._fd, m_pRecvBuf, m_iRecvLen, 0); if (ret == 0 || (ret ==-1 && (errno !=EAGAIN && errno != EWOULDBLOCK)) ) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " recv error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", ret=" << ret << ", errno=" << strerror(errno)); Close(); return false; } if (ret != -1) { m_pRecvBuf = NULL; m_iRecvLen = 0; m_handle._event.events = m_handle._event.events& ~EPOLLIN; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << "recv EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } m_cb->OnRecv(ret); } } } if (flag & EPOLLOUT) { if (m_pSendBuf == NULL || m_iSendLen == 0) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " send error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", m_pSendBuf=" <<(void*)m_pSendBuf << ", m_iSendLen=" << m_iSendLen); } else { int ret = send(m_handle._fd, m_pSendBuf, m_iSendLen, 0); if (ret == -1 && (errno != EAGAIN && errno != EWOULDBLOCK)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << " send error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", ret=" << ret << ", errno=" << strerror(errno)); Close(); return false; } if (ret != -1) { m_pSendBuf = NULL; m_iSendLen = 0; m_handle._event.events = m_handle._event.events& ~EPOLLOUT; if (!EPOLLMod(((CIOServer *)m_ios)->m_epoll, m_handle._fd, &m_handle._event)) { LCE("CTcpSocket::OnEPOLLMessage()" << this << "send EPOLLMod error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); Close(); return false; } m_cb->OnSend(ret); } } } return true; } bool CTcpSocket::Close() { if (m_handle._type == tagRegister::REG_ESTABLISHED) { m_handle._type = tagRegister::REG_INVALIDE; if (epoll_ctl(((CIOServer *)m_ios)->m_epoll, EPOLL_CTL_DEL, m_handle._fd, &m_handle._event) != 0) { LCE("CTcpSocket::Close()" << this << " EPOLL_CTL_DEL error. epfd="<<((CIOServer *)m_ios)->m_epoll << ", handle fd=" << m_handle._fd << ", errno=" << strerror(errno)); } shutdown(m_handle._fd, SHUT_RDWR); close(m_handle._fd); ((CIOServer*)m_ios)->PostMsg(PCK_SOCKET_CLOSE, this); } return true; } void CTcpSocket::OnPostClose() { m_cb->OnClose(); if (m_bNeedDestroy) { DestroyTcpSocket(this); } }
clear warning
clear warning
C++
mit
matinJ/zsummer,zsummer/zsummer,matinJ/zsummer,DavadDi/zsummer,nestle1998/zsummer,DavadDi/zsummer,matinJ/zsummer,nestle1998/zsummer,zsummer/zsummer,nestle1998/zsummer,ashimidashajia/zsummer,ashimidashajia/zsummer,DavadDi/zsummer,zsummer/zsummer,ashimidashajia/zsummer
22cb8776c3cee2295ff907404677edee999ac454
Sources/CardSets/BasicCardsGen.cpp
Sources/CardSets/BasicCardsGen.cpp
/************************************************************************* > File Name: BasicCardsGen.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: BasicCardsGen class that stores the power of basic cards. > Created Time: 2018/06/23 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #include <CardSets/BasicCardsGen.h> #include <Enchants/Effects.h> #include <Tasks/PowerTasks/AddEnchantmentTask.h> #include <Tasks/PowerTasks/DestroyTask.h> #include <Tasks/PowerTasks/HealFullTask.h> namespace Hearthstonepp { void BasicCardsGen::AddHeroes(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHeroPowers(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddDruid(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddDruidNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHunter(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHunterNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddMage(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddMageNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPaladin(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPaladinNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPriest(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPriestNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddRogue(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddRogueNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddShaman(std::map<std::string, Power*>& cards) { // ----------------------------------------- SPELL - SHAMAN // [CS2_041] Ancestral Healing - COST:0 // - Faction: Neutral, Set: Basic, Rarity: Free // -------------------------------------------------------- // Text: Restore a minion // to full Health and // give it <b>Taunt</b>. // -------------------------------------------------------- // PlayReq: // - REQ_TARGET_TO_PLAY = 0 // - REQ_MINION_TARGET = 0 // -------------------------------------------------------- // Tag: // - TAUNT = 1 // -------------------------------------------------------- Power* p = new Power; p->powerTask.emplace_back(new PowerTask::HealFullTask(EntityType::TARGET)); p->powerTask.emplace_back(new PowerTask::AddEnchantmentTask("CS2_041e", EntityType::TARGET)); cards.emplace("CS2_041", p); } void BasicCardsGen::AddShamanNonCollect(std::map<std::string, Power*>& cards) { // ----------------------------------- ENCHANTMENT - SHAMAN // [CS2_041e] Ancestral Infusion (*) - COST:0 // - Set: core, // -------------------------------------------------------- // Text: Taunt. // -------------------------------------------------------- // GameTag: // - TAUNT = 1 // -------------------------------------------------------- Power* p = new Power; p->enchant = new Enchant(Effects::Taunt); cards.emplace("CS2_041e", p); } void BasicCardsGen::AddWarlock(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarlockNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarrior(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarriorNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddNeutral(std::map<std::string, Power*>& cards) { // --------------------------------------- MINION - NEUTRAL // [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3/HP:2] // - Fac: alliance, Set: core, Rarity: free // -------------------------------------------------------- // Text: <b>Battlecry:</b> Destroy your opponent's weapon. // -------------------------------------------------------- // GameTag: // - BATTLECRY = 1 // -------------------------------------------------------- Power* p = new Power; p->powerTask.emplace_back( new PowerTask::DestroyTask(EntityType::OPPONENT_WEAPON)); cards.emplace("EX1_066", p); // --------------------------------------- MINION - NEUTRAL // [CS2_171] Stonetusk Boar - COST:1 [ATK:1/HP:1] // - Race: beast, Fac: neutral, Set: core, Rarity: free // -------------------------------------------------------- // Text: <b>Charge</b> // -------------------------------------------------------- // GameTag: // - CHARGE = 1 // -------------------------------------------------------- cards.emplace("CS2_171", nullptr); } void BasicCardsGen::AddNeutralNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddAll(std::map<std::string, Power*>& cards) { AddHeroes(cards); AddHeroPowers(cards); AddDruid(cards); AddDruidNonCollect(cards); AddHunter(cards); AddHunterNonCollect(cards); AddMage(cards); AddMageNonCollect(cards); AddPaladin(cards); AddPaladinNonCollect(cards); AddPriest(cards); AddPriestNonCollect(cards); AddRogue(cards); AddRogueNonCollect(cards); AddShaman(cards); AddShamanNonCollect(cards); AddWarlock(cards); AddWarlockNonCollect(cards); AddWarrior(cards); AddWarriorNonCollect(cards); AddNeutral(cards); AddNeutralNonCollect(cards); } }
/************************************************************************* > File Name: BasicCardsGen.cpp > Project Name: Hearthstone++ > Author: Chan-Ho Chris Ohk > Purpose: BasicCardsGen class that stores the power of basic cards. > Created Time: 2018/06/23 > Copyright (c) 2018, Chan-Ho Chris Ohk *************************************************************************/ #include <CardSets/BasicCardsGen.h> #include <Enchants/Effects.h> #include <Tasks/PowerTasks/AddEnchantmentTask.h> #include <Tasks/PowerTasks/DestroyTask.h> #include <Tasks/PowerTasks/HealFullTask.h> namespace Hearthstonepp { void BasicCardsGen::AddHeroes(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHeroPowers(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddDruid(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddDruidNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHunter(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddHunterNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddMage(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddMageNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPaladin(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPaladinNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPriest(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddPriestNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddRogue(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddRogueNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddShaman(std::map<std::string, Power*>& cards) { // ----------------------------------------- SPELL - SHAMAN // [CS2_041] Ancestral Healing - COST:0 // - Faction: Neutral, Set: Basic, Rarity: Free // -------------------------------------------------------- // Text: Restore a minion // to full Health and // give it <b>Taunt</b>. // -------------------------------------------------------- // PlayReq: // - REQ_TARGET_TO_PLAY = 0 // - REQ_MINION_TARGET = 0 // -------------------------------------------------------- // Tag: // - TAUNT = 1 // -------------------------------------------------------- Power* p = new Power; p->powerTask.emplace_back(new PowerTask::HealFullTask(EntityType::TARGET)); p->powerTask.emplace_back(new PowerTask::AddEnchantmentTask("CS2_041e", EntityType::TARGET)); cards.emplace("CS2_041", p); } void BasicCardsGen::AddShamanNonCollect(std::map<std::string, Power*>& cards) { // ----------------------------------- ENCHANTMENT - SHAMAN // [CS2_041e] Ancestral Infusion (*) - COST:0 // - Set: core, // -------------------------------------------------------- // Text: Taunt. // -------------------------------------------------------- // GameTag: // - TAUNT = 1 // -------------------------------------------------------- Power* p = new Power; p->enchant = new Enchant(Effects::Taunt); cards.emplace("CS2_041e", p); } void BasicCardsGen::AddWarlock(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarlockNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarrior(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddWarriorNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddNeutral(std::map<std::string, Power*>& cards) { // --------------------------------------- MINION - NEUTRAL // [EX1_066] Acidic Swamp Ooze - COST:2 [ATK:3/HP:2] // - Fac: alliance, Set: core, Rarity: free // -------------------------------------------------------- // Text: <b>Battlecry:</b> Destroy your opponent's weapon. // -------------------------------------------------------- // GameTag: // - BATTLECRY = 1 // -------------------------------------------------------- Power* p = new Power; p->powerTask.emplace_back( new PowerTask::DestroyTask(EntityType::OPPONENT_WEAPON)); cards.emplace("EX1_066", p); // --------------------------------------- MINION - NEUTRAL // [CS2_171] Stonetusk Boar - COST:1 [ATK:1/HP:1] // - Race: beast, Fac: neutral, Set: core, Rarity: free // -------------------------------------------------------- // Text: <b>Charge</b> // -------------------------------------------------------- // GameTag: // - CHARGE = 1 // -------------------------------------------------------- cards.emplace("CS2_171", nullptr); // --------------------------------------- MINION - NEUTRAL // [CS2_179] Sen'jin Shieldmasta - COST:4 [ATK:3/HP:5] // - Race: troll, Fac: HORDE, Set: core, Rarity: free // -------------------------------------------------------- // Text: <b>Taunt</b> // -------------------------------------------------------- // GameTag: // - Taunt = 1 // -------------------------------------------------------- cards.emplace("CS2_179", nullptr); } void BasicCardsGen::AddNeutralNonCollect(std::map<std::string, Power*>& cards) { (void)cards; } void BasicCardsGen::AddAll(std::map<std::string, Power*>& cards) { AddHeroes(cards); AddHeroPowers(cards); AddDruid(cards); AddDruidNonCollect(cards); AddHunter(cards); AddHunterNonCollect(cards); AddMage(cards); AddMageNonCollect(cards); AddPaladin(cards); AddPaladinNonCollect(cards); AddPriest(cards); AddPriestNonCollect(cards); AddRogue(cards); AddRogueNonCollect(cards); AddShaman(cards); AddShamanNonCollect(cards); AddWarlock(cards); AddWarlockNonCollect(cards); AddWarrior(cards); AddWarriorNonCollect(cards); AddNeutral(cards); AddNeutralNonCollect(cards); } }
Add missing Shildmasta init codes
Add missing Shildmasta init codes
C++
mit
Hearthstonepp/Hearthstonepp,Hearthstonepp/Hearthstonepp
e4736778c5cd8a6201ced53b3419ac62d9dc6f62
Source/Application.cpp
Source/Application.cpp
#include "Application.h" #include <iostream> #include <chrono> #include <thread> #include <SFML/System/Clock.hpp> #include <SFML/Graphics.hpp> #include "ResourceManagers/ResourceHolder.h" #include "Display.h" #include "States/MainMenu.h" Application::Application() { pushState<State::MainMenu>(*this); } void Application::runMainGameLoop() { constexpr uint32_t TICKS_PER_FRAME = 30; const sf::Time MS_PER_TICK = sf::seconds((float)1 / (float)TICKS_PER_FRAME); uint32_t tickCount = 0; sf::Clock timer; auto lastTime = timer.getElapsedTime(); auto tickLag = sf::Time::Zero; while (Display::get().isOpen() || !m_states.empty()) { auto& state = currentState(); auto currentTime = timer.getElapsedTime(); auto elapsed = currentTime - lastTime; lastTime = currentTime; tickLag += elapsed; state.input (m_camera); while (tickLag >= MS_PER_TICK) { tickCount++; state.fixedUpdate (m_camera, elapsed.asSeconds()); musicPlayer.update(); tickLag -= MS_PER_TICK; } m_camera.update(); state.update(m_camera, elapsed.asSeconds()); m_renderer.clear(); state.draw(m_renderer); m_renderer.update(m_camera); handleEvents(); } } void Application::handleEvents() { sf::Event e; while (Display::get().getRaw().pollEvent(e)) { currentState().input(e); switch(e.type) { case sf::Event::Closed: Display::get().close(); break; default: break; } } } void Application::popState() { m_states.pop_back(); if (!m_states.empty()) { currentState().onOpen(); } } State::Base& Application::currentState() { return *m_states.back(); } Camera& Application::getCamera() { return m_camera; }
#include "Application.h" #include <iostream> #include <chrono> #include <thread> #include <SFML/System/Clock.hpp> #include <SFML/Graphics.hpp> #include "ResourceManagers/ResourceHolder.h" #include "Display.h" #include "States/MainMenu.h" Application::Application() { pushState<State::MainMenu>(*this); } void Application::runMainGameLoop() { constexpr uint32_t TICKS_PER_FRAME = 30; const sf::Time MS_PER_TICK = sf::seconds((float)1 / (float)TICKS_PER_FRAME); uint32_t tickCount = 0; sf::Clock timer; auto lastTime = timer.getElapsedTime(); auto tickLag = sf::Time::Zero; while (Display::get().isOpen()) { if (m_states.empty()) break; auto& state = currentState(); auto currentTime = timer.getElapsedTime(); auto elapsed = currentTime - lastTime; lastTime = currentTime; tickLag += elapsed; state.input (m_camera); while (tickLag >= MS_PER_TICK) { tickCount++; state.fixedUpdate (m_camera, elapsed.asSeconds()); musicPlayer.update(); tickLag -= MS_PER_TICK; } m_camera.update(); state.update(m_camera, elapsed.asSeconds()); m_renderer.clear(); state.draw(m_renderer); m_renderer.update(m_camera); handleEvents(); } } void Application::handleEvents() { sf::Event e; while (Display::get().getRaw().pollEvent(e)) { currentState().input(e); switch(e.type) { case sf::Event::Closed: Display::get().close(); break; default: break; } } } void Application::popState() { m_states.pop_back(); if (!m_states.empty()) { currentState().onOpen(); } } State::Base& Application::currentState() { return *m_states.back(); } Camera& Application::getCamera() { return m_camera; }
Fix crash in main loop
Fix crash in main loop
C++
mit
Hopson97/HopsonCraft,Hopson97/HopsonCraft
33b801a0ca7dd39237e8db019fe8d03b296e9398
test/views.cpp
test/views.cpp
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" ///{{{ Dim TEST_CASE( "dim/fast_matrix_1", "dim<1>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::dim<1>(a, 0)); etl::fast_vector<double, 3> c(etl::dim<1>(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_2", "dim<2>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::dim<2>(a, 0)); etl::fast_vector<double, 2> c(etl::dim<2>(a, 1)); etl::fast_vector<double, 2> d(etl::dim<2>(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/fast_matrix_3", "row" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::row(a, 0)); etl::fast_vector<double, 3> c(etl::row(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_4", "col" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::col(a, 0)); etl::fast_vector<double, 2> c(etl::col(a, 1)); etl::fast_vector<double, 2> d(etl::col(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/dyn_matrix_1", "dim<1>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<1>(a, 0)); etl::dyn_vector<double> c(etl::dim<1>(a, 1)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/dyn_matrix_2", "dim<2>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<2>(a, 0)); etl::dyn_vector<double> c(etl::dim<2>(a, 1)); etl::dyn_vector<double> d(etl::dim<2>(a, 2)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/mix", "dim" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b({0.1, 0.2, 0.3}); etl::fast_vector<double, 3> c(b * row(a,1)); REQUIRE(c[0] == Approx(0.3)); REQUIRE(c[1] == Approx(0.1)); REQUIRE(c[2] == Approx(-0.03)); } ///}}} //{{{ reshape TEST_CASE( "reshape/fast_vector_1", "reshape<2,2>" ) { etl::fast_vector<double, 4> a({1,2,3,4}); etl::fast_matrix<double, 2, 2> b(etl::reshape<2,2>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/fast_vector_2", "reshape<2,3>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); etl::fast_matrix<double, 2, 3> b(etl::reshape<2,3>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/traits", "traits<reshape<2,3>>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape<2,3>(a)); expr_type expr((etl::fast_matrix_view<etl::fast_vector<double, 6>, 2, 3>(a))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); constexpr const auto size_1 = etl::etl_traits<expr_type>::size(); constexpr const auto rows_1 = etl::etl_traits<expr_type>::rows(); constexpr const auto columns_1 = etl::etl_traits<expr_type>::columns(); REQUIRE(size_1 == 6); REQUIRE(rows_1 == 2); REQUIRE(columns_1 == 3); constexpr const auto size_2 = etl::size(expr); constexpr const auto rows_2 = etl::rows(expr); constexpr const auto columns_2 = etl::columns(expr); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 2); REQUIRE(columns_2 == 3); } TEST_CASE( "reshape/dyn_vector_1", "reshape(2,2)" ) { etl::dyn_vector<double> a({1,2,3,4}); etl::dyn_matrix<double> b(etl::reshape(a,2,2)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/dyn_vector_2", "reshape(2,3)" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); etl::dyn_matrix<double> b(etl::reshape(a,2,3)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/dyn_traits", "traits<reshape<2,3>>" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape(a,2,3)); expr_type expr((etl::dyn_matrix_view<etl::dyn_vector<double>>(a,2,3))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(!etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); } //}}}
//======================================================================= // Copyright (c) 2014 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include "catch.hpp" #include "etl/fast_matrix.hpp" #include "etl/fast_vector.hpp" #include "etl/dyn_matrix.hpp" #include "etl/dyn_vector.hpp" ///{{{ Dim TEST_CASE( "dim/fast_matrix_1", "dim<1>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::dim<1>(a, 0)); etl::fast_vector<double, 3> c(etl::dim<1>(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_2", "dim<2>" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::dim<2>(a, 0)); etl::fast_vector<double, 2> c(etl::dim<2>(a, 1)); etl::fast_vector<double, 2> d(etl::dim<2>(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/fast_matrix_3", "row" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b(etl::row(a, 0)); etl::fast_vector<double, 3> c(etl::row(a, 1)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/fast_matrix_4", "col" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 2> b(etl::col(a, 0)); etl::fast_vector<double, 2> c(etl::col(a, 1)); etl::fast_vector<double, 2> d(etl::col(a, 2)); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/dyn_matrix_1", "dim<1>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<1>(a, 0)); etl::dyn_vector<double> c(etl::dim<1>(a, 1)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == -2.0); REQUIRE(b[2] == 4.0); REQUIRE(c[0] == 3.0); REQUIRE(c[1] == 0.5); REQUIRE(c[2] == -0.1); } TEST_CASE( "dim/dyn_matrix_2", "dim<2>" ) { etl::dyn_matrix<double> a(2, 3, {1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::dyn_vector<double> b(etl::dim<2>(a, 0)); etl::dyn_vector<double> c(etl::dim<2>(a, 1)); etl::dyn_vector<double> d(etl::dim<2>(a, 2)); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(b)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(c)>>>::is_fast); REQUIRE(!etl::etl_traits<remove_cv_t<remove_reference_t<decltype(d)>>>::is_fast); REQUIRE(b[0] == 1.0); REQUIRE(b[1] == 3.0); REQUIRE(c[0] == -2.0); REQUIRE(c[1] == 0.5); REQUIRE(d[0] == 4.0); REQUIRE(d[1] == -0.1); } TEST_CASE( "dim/mix", "dim" ) { etl::fast_matrix<double, 2, 3> a({1.0, -2.0, 4.0, 3.0, 0.5, -0.1}); etl::fast_vector<double, 3> b({0.1, 0.2, 0.3}); etl::fast_vector<double, 3> c(b * row(a,1)); REQUIRE(c[0] == Approx(0.3)); REQUIRE(c[1] == Approx(0.1)); REQUIRE(c[2] == Approx(-0.03)); } ///}}} //{{{ reshape TEST_CASE( "reshape/fast_vector_1", "reshape<2,2>" ) { etl::fast_vector<double, 4> a({1,2,3,4}); etl::fast_matrix<double, 2, 2> b(etl::reshape<2,2>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/fast_vector_2", "reshape<2,3>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); etl::fast_matrix<double, 2, 3> b(etl::reshape<2,3>(a)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/traits", "traits<reshape<2,3>>" ) { etl::fast_vector<double, 6> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape<2,3>(a)); expr_type expr((etl::fast_matrix_view<etl::fast_vector<double, 6>, 2, 3>(a))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); constexpr const auto size_1 = etl::etl_traits<expr_type>::size(); constexpr const auto rows_1 = etl::etl_traits<expr_type>::rows(); constexpr const auto columns_1 = etl::etl_traits<expr_type>::columns(); REQUIRE(size_1 == 6); REQUIRE(rows_1 == 2); REQUIRE(columns_1 == 3); constexpr const auto size_2 = etl::size(expr); constexpr const auto rows_2 = etl::rows(expr); constexpr const auto columns_2 = etl::columns(expr); REQUIRE(size_2 == 6); REQUIRE(rows_2 == 2); REQUIRE(columns_2 == 3); } TEST_CASE( "reshape/dyn_vector_1", "reshape(2,2)" ) { etl::dyn_vector<double> a({1,2,3,4}); etl::dyn_matrix<double> b(etl::reshape(a,2,2)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(1,0) == 3.0); REQUIRE(b(1,1) == 4.0); } TEST_CASE( "reshape/dyn_vector_2", "reshape(2,3)" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); etl::dyn_matrix<double> b(etl::reshape(a,2,3)); REQUIRE(b(0,0) == 1.0); REQUIRE(b(0,1) == 2.0); REQUIRE(b(0,2) == 3.0); REQUIRE(b(1,0) == 4.0); REQUIRE(b(1,1) == 5.0); REQUIRE(b(1,2) == 6.0); } TEST_CASE( "reshape/dyn_traits", "traits<reshape<2,3>>" ) { etl::dyn_vector<double> a({1,2,3,4,5,6}); using expr_type = decltype(etl::reshape(a,2,3)); expr_type expr((etl::dyn_matrix_view<etl::dyn_vector<double>>(a,2,3))); REQUIRE(etl::etl_traits<expr_type>::size(expr) == 6); REQUIRE(etl::size(expr) == 6); REQUIRE(etl::etl_traits<expr_type>::rows(expr) == 2); REQUIRE(etl::rows(expr) == 2); REQUIRE(etl::etl_traits<expr_type>::columns(expr) == 3); REQUIRE(etl::columns(expr) == 3); REQUIRE(etl::etl_traits<expr_type>::is_matrix); REQUIRE(!etl::etl_traits<expr_type>::is_value); REQUIRE(!etl::etl_traits<expr_type>::is_fast); REQUIRE(!etl::etl_traits<expr_type>::is_vector); } //}}} //{{{ sub TEST_CASE( "fast_matrix/sub_view_1", "fast_matrix::sub" ) { etl::fast_matrix<double, 2, 2, 2> a = {1.1, 2.0, 5.0, 1.0, 1.1, 2.0, 5.0, 1.0}; REQUIRE(etl::sub(a, 0)(0, 0) == 1.1); REQUIRE(etl::sub(a, 0)(0, 1) == 2.0); REQUIRE(etl::sub(a, 1)(0, 0) == 1.1); REQUIRE(etl::sub(a, 1)(0, 1) == 2.0); } //}}}
Test for sub matrix access
Test for sub matrix access
C++
mit
wichtounet/etl,wichtounet/etl
9fe3e8636803779f9dda0c4dd356357ed555f592
query.cc
query.cc
/* * Copyright (C) 2015-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <limits> #include "query-request.hh" #include "query-result.hh" #include "query-result-writer.hh" #include "query-result-set.hh" #include "to_string.hh" #include "bytes.hh" #include "mutation_partition_serializer.hh" #include "query-result-reader.hh" #include "query_result_merger.hh" namespace query { constexpr size_t result_memory_limiter::minimum_result_size; constexpr size_t result_memory_limiter::maximum_result_size; constexpr size_t result_memory_limiter::unlimited_result_size; thread_local semaphore result_memory_tracker::_dummy { 0 }; const dht::partition_range full_partition_range = dht::partition_range::make_open_ended_both_sides(); const clustering_range full_clustering_range = clustering_range::make_open_ended_both_sides(); std::ostream& operator<<(std::ostream& out, const specific_ranges& s); std::ostream& operator<<(std::ostream& out, const partition_slice& ps) { out << "{" << "regular_cols=[" << join(", ", ps.regular_columns) << "]" << ", static_cols=[" << join(", ", ps.static_columns) << "]" << ", rows=[" << join(", ", ps._row_ranges) << "]" ; if (ps._specific_ranges) { out << ", specific=[" << *ps._specific_ranges << "]"; } out << ", options=" << format("{:x}", ps.options.mask()); // FIXME: pretty print options out << ", cql_format=" << ps.cql_format(); out << ", partition_row_limit=" << ps._partition_row_limit_low_bits; return out << "}"; } std::ostream& operator<<(std::ostream& out, const read_command& r) { return out << "read_command{" << "cf_id=" << r.cf_id << ", version=" << r.schema_version << ", slice=" << r.slice << "" << ", limit=" << r.get_row_limit() << ", timestamp=" << r.timestamp.time_since_epoch().count() << ", partition_limit=" << r.partition_limit << "}"; } std::ostream& operator<<(std::ostream& out, const specific_ranges& s) { return out << "{" << s._pk << " : " << join(", ", s._ranges) << "}"; } void trim_clustering_row_ranges_to(const schema& s, clustering_row_ranges& ranges, position_in_partition_view pos, bool reversed) { auto cmp = [reversed, cmp = position_in_partition::composite_tri_compare(s)] (const auto& a, const auto& b) { return reversed ? cmp(b, a) : cmp(a, b); }; auto start_bound = [reversed] (const auto& range) -> position_in_partition_view { return reversed ? position_in_partition_view::for_range_end(range) : position_in_partition_view::for_range_start(range); }; auto end_bound = [reversed] (const auto& range) -> position_in_partition_view { return reversed ? position_in_partition_view::for_range_start(range) : position_in_partition_view::for_range_end(range); }; auto it = ranges.begin(); while (it != ranges.end()) { if (cmp(end_bound(*it), pos) <= 0) { it = ranges.erase(it); continue; } else if (cmp(start_bound(*it), pos) <= 0) { assert(cmp(pos, end_bound(*it)) < 0); auto r = reversed ? clustering_range(it->start(), clustering_range::bound(pos.key(), pos.get_bound_weight() != bound_weight::before_all_prefixed)) : clustering_range(clustering_range::bound(pos.key(), pos.get_bound_weight() != bound_weight::after_all_prefixed), it->end()); *it = std::move(r); } ++it; } } void trim_clustering_row_ranges_to(const schema& s, clustering_row_ranges& ranges, const clustering_key& key, bool reversed) { if (key.is_full(s)) { return trim_clustering_row_ranges_to(s, ranges, reversed ? position_in_partition_view::before_key(key) : position_in_partition_view::after_key(key), reversed); } auto full_key = key; clustering_key::make_full(s, full_key); return trim_clustering_row_ranges_to(s, ranges, reversed ? position_in_partition_view::after_key(full_key) : position_in_partition_view::before_key(full_key), reversed); } partition_slice::partition_slice(clustering_row_ranges row_ranges, query::column_id_vector static_columns, query::column_id_vector regular_columns, option_set options, std::unique_ptr<specific_ranges> specific_ranges, cql_serialization_format cql_format, uint32_t partition_row_limit_low_bits, uint32_t partition_row_limit_high_bits) : _row_ranges(std::move(row_ranges)) , static_columns(std::move(static_columns)) , regular_columns(std::move(regular_columns)) , options(options) , _specific_ranges(std::move(specific_ranges)) , _cql_format(std::move(cql_format)) , _partition_row_limit_low_bits(partition_row_limit_low_bits) , _partition_row_limit_high_bits(partition_row_limit_high_bits) {} partition_slice::partition_slice(clustering_row_ranges row_ranges, query::column_id_vector static_columns, query::column_id_vector regular_columns, option_set options, std::unique_ptr<specific_ranges> specific_ranges, cql_serialization_format cql_format, uint64_t partition_row_limit) : partition_slice(std::move(row_ranges), std::move(static_columns), std::move(regular_columns), options, std::move(specific_ranges), std::move(cql_format), static_cast<uint32_t>(partition_row_limit), static_cast<uint32_t>(partition_row_limit >> 32)) {} partition_slice::partition_slice(clustering_row_ranges ranges, const schema& s, const column_set& columns, option_set options) : partition_slice(ranges, query::column_id_vector{}, query::column_id_vector{}, options) { regular_columns.reserve(columns.count()); for (ordinal_column_id id = columns.find_first(); id != column_set::npos; id = columns.find_next(id)) { const column_definition& def = s.column_at(id); if (def.is_static()) { static_columns.push_back(def.id); } else if (def.is_regular()) { regular_columns.push_back(def.id); } // else clustering or partition key column - skip, these are controlled by options } } partition_slice::partition_slice(partition_slice&&) = default; partition_slice& partition_slice::operator=(partition_slice&& other) noexcept = default; // Only needed because selection_statement::execute does copies of its read_command // in the map-reduce op. partition_slice::partition_slice(const partition_slice& s) : _row_ranges(s._row_ranges) , static_columns(s.static_columns) , regular_columns(s.regular_columns) , options(s.options) , _specific_ranges(s._specific_ranges ? std::make_unique<specific_ranges>(*s._specific_ranges) : nullptr) , _cql_format(s._cql_format) , _partition_row_limit_low_bits(s._partition_row_limit_low_bits) {} partition_slice::~partition_slice() {} const clustering_row_ranges& partition_slice::row_ranges(const schema& s, const partition_key& k) const { auto* r = _specific_ranges ? _specific_ranges->range_for(s, k) : nullptr; return r ? *r : _row_ranges; } void partition_slice::set_range(const schema& s, const partition_key& k, clustering_row_ranges range) { if (!_specific_ranges) { _specific_ranges = std::make_unique<specific_ranges>(k, std::move(range)); } else { _specific_ranges->add(s, k, std::move(range)); } } void partition_slice::clear_range(const schema& s, const partition_key& k) { if (_specific_ranges && _specific_ranges->contains(s, k)) { // just in case someone changes the impl above, // we should do actual remove if specific_ranges suddenly // becomes an actual map assert(_specific_ranges->size() == 1); _specific_ranges = nullptr; } } clustering_row_ranges partition_slice::get_all_ranges() const { auto all_ranges = default_row_ranges(); const auto& specific_ranges = get_specific_ranges(); if (specific_ranges) { all_ranges.insert(all_ranges.end(), specific_ranges->ranges().begin(), specific_ranges->ranges().end()); } return all_ranges; } sstring result::pretty_print(schema_ptr s, const query::partition_slice& slice) const { std::ostringstream out; out << "{ result: " << result_set::from_raw_result(s, slice, *this); out << " digest: "; if (_digest) { out << std::hex << std::setw(2); for (auto&& c : _digest->get()) { out << unsigned(c) << " "; } } else { out << "{}"; } out << ", short_read=" << is_short_read() << " }"; return out.str(); } query::result::printer result::pretty_printer(schema_ptr s, const query::partition_slice& slice) const { return query::result::printer{s, slice, *this}; } std::ostream& operator<<(std::ostream& os, const query::result::printer& p) { os << p.res.pretty_print(p.s, p.slice); return os; } void result::ensure_counts() { if (!_partition_count || !row_count()) { uint64_t row_count; std::tie(_partition_count, row_count) = result_view::do_with(*this, [this] (auto&& view) { return view.count_partitions_and_rows(); }); set_row_count(row_count); } } result::result() : result([] { bytes_ostream out; ser::writer_of_query_result<bytes_ostream>(out).skip_partitions().end_query_result(); return out; }(), short_read::no, 0, 0) { } static void write_partial_partition(ser::writer_of_qr_partition<bytes_ostream>&& pw, const ser::qr_partition_view& pv, uint64_t rows_to_include) { auto key = pv.key(); auto static_cells_wr = (key ? std::move(pw).write_key(*key) : std::move(pw).skip_key()) .start_static_row() .start_cells(); for (auto&& cell : pv.static_row().cells()) { static_cells_wr.add(cell); } auto rows_wr = std::move(static_cells_wr) .end_cells() .end_static_row() .start_rows(); auto rows = pv.rows(); // rows.size() can be 0 is there's a single static row auto it = rows.begin(); for (uint64_t i = 0; i < std::min(rows.size(), rows_to_include); ++i) { rows_wr.add(*it++); } std::move(rows_wr).end_rows().end_qr_partition(); } foreign_ptr<lw_shared_ptr<query::result>> result_merger::get() { if (_partial.size() == 1) { return std::move(_partial[0]); } bytes_ostream w; auto partitions = ser::writer_of_query_result<bytes_ostream>(w).start_partitions(); uint64_t row_count = 0; short_read is_short_read; uint32_t partition_count = 0; for (auto&& r : _partial) { result_view::do_with(*r, [&] (result_view rv) { for (auto&& pv : rv._v.partitions()) { auto rows = pv.rows(); // If rows.empty(), then there's a static row, or there wouldn't be a partition const uint64_t rows_in_partition = rows.size() ? : 1; const uint64_t rows_to_include = std::min(_max_rows - row_count, rows_in_partition); row_count += rows_to_include; if (rows_to_include >= rows_in_partition) { partitions.add(pv); if (++partition_count >= _max_partitions) { return; } } else if (rows_to_include > 0) { ++partition_count; write_partial_partition(partitions.add(), pv, rows_to_include); return; } else { return; } } }); if (r->is_short_read()) { is_short_read = short_read::yes; break; } if (row_count >= _max_rows || partition_count >= _max_partitions) { break; } } std::move(partitions).end_partitions().end_query_result(); return make_foreign(make_lw_shared<query::result>(std::move(w), is_short_read, row_count, partition_count)); } }
/* * Copyright (C) 2015-present ScyllaDB */ /* * This file is part of Scylla. * * Scylla is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Scylla is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Scylla. If not, see <http://www.gnu.org/licenses/>. */ #include <limits> #include "query-request.hh" #include "query-result.hh" #include "query-result-writer.hh" #include "query-result-set.hh" #include "to_string.hh" #include "bytes.hh" #include "mutation_partition_serializer.hh" #include "query-result-reader.hh" #include "query_result_merger.hh" namespace query { constexpr size_t result_memory_limiter::minimum_result_size; constexpr size_t result_memory_limiter::maximum_result_size; constexpr size_t result_memory_limiter::unlimited_result_size; thread_local semaphore result_memory_tracker::_dummy { 0 }; const dht::partition_range full_partition_range = dht::partition_range::make_open_ended_both_sides(); const clustering_range full_clustering_range = clustering_range::make_open_ended_both_sides(); std::ostream& operator<<(std::ostream& out, const specific_ranges& s); std::ostream& operator<<(std::ostream& out, const partition_slice& ps) { out << "{" << "regular_cols=[" << join(", ", ps.regular_columns) << "]" << ", static_cols=[" << join(", ", ps.static_columns) << "]" << ", rows=[" << join(", ", ps._row_ranges) << "]" ; if (ps._specific_ranges) { out << ", specific=[" << *ps._specific_ranges << "]"; } out << ", options=" << format("{:x}", ps.options.mask()); // FIXME: pretty print options out << ", cql_format=" << ps.cql_format(); out << ", partition_row_limit=" << ps._partition_row_limit_low_bits; return out << "}"; } std::ostream& operator<<(std::ostream& out, const read_command& r) { return out << "read_command{" << "cf_id=" << r.cf_id << ", version=" << r.schema_version << ", slice=" << r.slice << "" << ", limit=" << r.get_row_limit() << ", timestamp=" << r.timestamp.time_since_epoch().count() << ", partition_limit=" << r.partition_limit << ", query_uuid=" << r.query_uuid << ", is_first_page=" << r.is_first_page << ", read_timestamp=" << r.read_timestamp << "}"; } std::ostream& operator<<(std::ostream& out, const specific_ranges& s) { return out << "{" << s._pk << " : " << join(", ", s._ranges) << "}"; } void trim_clustering_row_ranges_to(const schema& s, clustering_row_ranges& ranges, position_in_partition_view pos, bool reversed) { auto cmp = [reversed, cmp = position_in_partition::composite_tri_compare(s)] (const auto& a, const auto& b) { return reversed ? cmp(b, a) : cmp(a, b); }; auto start_bound = [reversed] (const auto& range) -> position_in_partition_view { return reversed ? position_in_partition_view::for_range_end(range) : position_in_partition_view::for_range_start(range); }; auto end_bound = [reversed] (const auto& range) -> position_in_partition_view { return reversed ? position_in_partition_view::for_range_start(range) : position_in_partition_view::for_range_end(range); }; auto it = ranges.begin(); while (it != ranges.end()) { if (cmp(end_bound(*it), pos) <= 0) { it = ranges.erase(it); continue; } else if (cmp(start_bound(*it), pos) <= 0) { assert(cmp(pos, end_bound(*it)) < 0); auto r = reversed ? clustering_range(it->start(), clustering_range::bound(pos.key(), pos.get_bound_weight() != bound_weight::before_all_prefixed)) : clustering_range(clustering_range::bound(pos.key(), pos.get_bound_weight() != bound_weight::after_all_prefixed), it->end()); *it = std::move(r); } ++it; } } void trim_clustering_row_ranges_to(const schema& s, clustering_row_ranges& ranges, const clustering_key& key, bool reversed) { if (key.is_full(s)) { return trim_clustering_row_ranges_to(s, ranges, reversed ? position_in_partition_view::before_key(key) : position_in_partition_view::after_key(key), reversed); } auto full_key = key; clustering_key::make_full(s, full_key); return trim_clustering_row_ranges_to(s, ranges, reversed ? position_in_partition_view::after_key(full_key) : position_in_partition_view::before_key(full_key), reversed); } partition_slice::partition_slice(clustering_row_ranges row_ranges, query::column_id_vector static_columns, query::column_id_vector regular_columns, option_set options, std::unique_ptr<specific_ranges> specific_ranges, cql_serialization_format cql_format, uint32_t partition_row_limit_low_bits, uint32_t partition_row_limit_high_bits) : _row_ranges(std::move(row_ranges)) , static_columns(std::move(static_columns)) , regular_columns(std::move(regular_columns)) , options(options) , _specific_ranges(std::move(specific_ranges)) , _cql_format(std::move(cql_format)) , _partition_row_limit_low_bits(partition_row_limit_low_bits) , _partition_row_limit_high_bits(partition_row_limit_high_bits) {} partition_slice::partition_slice(clustering_row_ranges row_ranges, query::column_id_vector static_columns, query::column_id_vector regular_columns, option_set options, std::unique_ptr<specific_ranges> specific_ranges, cql_serialization_format cql_format, uint64_t partition_row_limit) : partition_slice(std::move(row_ranges), std::move(static_columns), std::move(regular_columns), options, std::move(specific_ranges), std::move(cql_format), static_cast<uint32_t>(partition_row_limit), static_cast<uint32_t>(partition_row_limit >> 32)) {} partition_slice::partition_slice(clustering_row_ranges ranges, const schema& s, const column_set& columns, option_set options) : partition_slice(ranges, query::column_id_vector{}, query::column_id_vector{}, options) { regular_columns.reserve(columns.count()); for (ordinal_column_id id = columns.find_first(); id != column_set::npos; id = columns.find_next(id)) { const column_definition& def = s.column_at(id); if (def.is_static()) { static_columns.push_back(def.id); } else if (def.is_regular()) { regular_columns.push_back(def.id); } // else clustering or partition key column - skip, these are controlled by options } } partition_slice::partition_slice(partition_slice&&) = default; partition_slice& partition_slice::operator=(partition_slice&& other) noexcept = default; // Only needed because selection_statement::execute does copies of its read_command // in the map-reduce op. partition_slice::partition_slice(const partition_slice& s) : _row_ranges(s._row_ranges) , static_columns(s.static_columns) , regular_columns(s.regular_columns) , options(s.options) , _specific_ranges(s._specific_ranges ? std::make_unique<specific_ranges>(*s._specific_ranges) : nullptr) , _cql_format(s._cql_format) , _partition_row_limit_low_bits(s._partition_row_limit_low_bits) {} partition_slice::~partition_slice() {} const clustering_row_ranges& partition_slice::row_ranges(const schema& s, const partition_key& k) const { auto* r = _specific_ranges ? _specific_ranges->range_for(s, k) : nullptr; return r ? *r : _row_ranges; } void partition_slice::set_range(const schema& s, const partition_key& k, clustering_row_ranges range) { if (!_specific_ranges) { _specific_ranges = std::make_unique<specific_ranges>(k, std::move(range)); } else { _specific_ranges->add(s, k, std::move(range)); } } void partition_slice::clear_range(const schema& s, const partition_key& k) { if (_specific_ranges && _specific_ranges->contains(s, k)) { // just in case someone changes the impl above, // we should do actual remove if specific_ranges suddenly // becomes an actual map assert(_specific_ranges->size() == 1); _specific_ranges = nullptr; } } clustering_row_ranges partition_slice::get_all_ranges() const { auto all_ranges = default_row_ranges(); const auto& specific_ranges = get_specific_ranges(); if (specific_ranges) { all_ranges.insert(all_ranges.end(), specific_ranges->ranges().begin(), specific_ranges->ranges().end()); } return all_ranges; } sstring result::pretty_print(schema_ptr s, const query::partition_slice& slice) const { std::ostringstream out; out << "{ result: " << result_set::from_raw_result(s, slice, *this); out << " digest: "; if (_digest) { out << std::hex << std::setw(2); for (auto&& c : _digest->get()) { out << unsigned(c) << " "; } } else { out << "{}"; } out << ", short_read=" << is_short_read() << " }"; return out.str(); } query::result::printer result::pretty_printer(schema_ptr s, const query::partition_slice& slice) const { return query::result::printer{s, slice, *this}; } std::ostream& operator<<(std::ostream& os, const query::result::printer& p) { os << p.res.pretty_print(p.s, p.slice); return os; } void result::ensure_counts() { if (!_partition_count || !row_count()) { uint64_t row_count; std::tie(_partition_count, row_count) = result_view::do_with(*this, [this] (auto&& view) { return view.count_partitions_and_rows(); }); set_row_count(row_count); } } result::result() : result([] { bytes_ostream out; ser::writer_of_query_result<bytes_ostream>(out).skip_partitions().end_query_result(); return out; }(), short_read::no, 0, 0) { } static void write_partial_partition(ser::writer_of_qr_partition<bytes_ostream>&& pw, const ser::qr_partition_view& pv, uint64_t rows_to_include) { auto key = pv.key(); auto static_cells_wr = (key ? std::move(pw).write_key(*key) : std::move(pw).skip_key()) .start_static_row() .start_cells(); for (auto&& cell : pv.static_row().cells()) { static_cells_wr.add(cell); } auto rows_wr = std::move(static_cells_wr) .end_cells() .end_static_row() .start_rows(); auto rows = pv.rows(); // rows.size() can be 0 is there's a single static row auto it = rows.begin(); for (uint64_t i = 0; i < std::min(rows.size(), rows_to_include); ++i) { rows_wr.add(*it++); } std::move(rows_wr).end_rows().end_qr_partition(); } foreign_ptr<lw_shared_ptr<query::result>> result_merger::get() { if (_partial.size() == 1) { return std::move(_partial[0]); } bytes_ostream w; auto partitions = ser::writer_of_query_result<bytes_ostream>(w).start_partitions(); uint64_t row_count = 0; short_read is_short_read; uint32_t partition_count = 0; for (auto&& r : _partial) { result_view::do_with(*r, [&] (result_view rv) { for (auto&& pv : rv._v.partitions()) { auto rows = pv.rows(); // If rows.empty(), then there's a static row, or there wouldn't be a partition const uint64_t rows_in_partition = rows.size() ? : 1; const uint64_t rows_to_include = std::min(_max_rows - row_count, rows_in_partition); row_count += rows_to_include; if (rows_to_include >= rows_in_partition) { partitions.add(pv); if (++partition_count >= _max_partitions) { return; } } else if (rows_to_include > 0) { ++partition_count; write_partial_partition(partitions.add(), pv, rows_to_include); return; } else { return; } } }); if (r->is_short_read()) { is_short_read = short_read::yes; break; } if (row_count >= _max_rows || partition_count >= _max_partitions) { break; } } std::move(partitions).end_partitions().end_query_result(); return make_foreign(make_lw_shared<query::result>(std::move(w), is_short_read, row_count, partition_count)); } }
Print more fields of read_command
db: Print more fields of read_command Message-Id: <[email protected]>
C++
agpl-3.0
scylladb/scylla,scylladb/scylla,scylladb/scylla,scylladb/scylla
40da4e7f023a915c2da57ee04f42a9a3dae90104
test/trans.cpp
test/trans.cpp
#include <gtest/gtest.h> #include <gmock/gmock.h> extern "C" { #include "../src/mssql.h" } using ::testing::StartsWith; TEST(SetConstructTest, ConstructFromArray) { char * testquery = (char *)malloc(2048); char * resquery = (char *)malloc(2048); sprintf(testquery, "show tables;"); resquery = trans_dialect(testquery); printf("%s¥n", resquery); } TEST(SetConstructTest2, ConstructFromArray2) { EXPECT_THAT("Helle", StartsWith("Hello")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
#include <gtest/gtest.h> #include <gmock/gmock.h> extern "C" { #include "../src/mssql.h" } using ::testing::StartsWith; TEST(QueryTranslateTest, ShowTables) { char * testquery = (char *)malloc(2048); char * resquery = (char *)malloc(2048); sprintf(testquery, "show tables;"); resquery = trans_dialect(testquery); EXPECT_THAT(resquery, StartsWith("SELECT name AS Tables FROM sysobjects")); } TEST(SetConstructTest2, ConstructFromArray2) { EXPECT_THAT("Hello", StartsWith("Hello")); } int main(int argc, char **argv) { ::testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
add test for show tables
add test for show tables
C++
bsd-3-clause
hanhan1978/mssql,hanhan1978/mssql,hanhan1978/mssql
3ea978737c4dac5118fc83a746cf84d8585f6c2c
tests/init.cpp
tests/init.cpp
#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { Node<int> n; REQUIRE(n.root() == nullptr); REQUIRE(n.count() == 0); } SCENARIO("insertElement") { Node<int> n; n.insert(7); REQUIRE(n.findElement() == 7); REQUIRE(n.count() == 1); } SCENARIO("findElement") { Node<int> n; bool a; tree.insert(7); a = tree.isFound(7); REQUIRE(a == true); } SCENARIO("out") { Node<int> n1; n.out("file3.txt"); Node<int> n2; n2.out("file3.txt"); REQUIRE(n1.count() == n2.count()); }
#include <binary_search_tree.hpp> #include <catch.hpp> SCENARIO("default constructor") { BinarySearchTree<int> bst; REQUIRE(bst.root() == nullptr); REQUIRE(bst.count() == 0); } SCENARIO("insertElement") { BinarySearchTree<int> bst; bst.insert(7); REQUIRE(bst.findElement() == 7); REQUIRE(bst.count() == 1); } SCENARIO("findElement") { BinarySearchTree<int> bst; bool a; bst.insert(7); a = bst.isFound(7); REQUIRE(a == true); } SCENARIO("out") { BinarySearchTree<int> bst1; bst1.out("file3.txt"); BinarySearchTree<int> bst2; bst2.out("file3.txt"); REQUIRE(bst1.count() == bst2.count()); }
Update init.cpp
Update init.cpp
C++
mit
yanaxgrishkova/binary_search_tree
64534b155b3113ffe2d89af6ae83e2cb63c0dbde
lib/socket_helpers.cpp
lib/socket_helpers.cpp
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include "socket_helpers.hpp" #include <cppcoro/net/ip_endpoint.hpp> #if CPPCORO_OS_WINNT #include <cstring> #include <cassert> #include <WinSock2.h> #include <WS2tcpip.h> #include <MSWSock.h> #include <Windows.h> cppcoro::net::ip_endpoint cppcoro::net::detail::sockaddr_to_ip_endpoint(const sockaddr& address) noexcept { if (address.sa_family == AF_INET) { SOCKADDR_IN ipv4Address; std::memcpy(&ipv4Address, &address, sizeof(ipv4Address)); std::uint8_t addressBytes[4]; std::memcpy(addressBytes, &ipv4Address.sin_addr, 4); return ipv4_endpoint{ ipv4_address{ addressBytes }, ipv4Address.sin_port }; } else { assert(address.sa_family == AF_INET6); SOCKADDR_IN6 ipv6Address; std::memcpy(&ipv6Address, &address, sizeof(ipv6Address)); return ipv6_endpoint{ ipv6_address{ ipv6Address.sin6_addr.u.Byte }, ipv6Address.sin6_port }; } } int cppcoro::net::detail::ip_endpoint_to_sockaddr( const ip_endpoint& endPoint, std::reference_wrapper<sockaddr_storage> address) noexcept { if (endPoint.is_ipv4()) { const auto& ipv4EndPoint = endPoint.to_ipv4(); SOCKADDR_IN ipv4Address; ipv4Address.sin_family = AF_INET; std::memcpy(&ipv4Address.sin_addr, ipv4EndPoint.address().bytes(), 4); ipv4Address.sin_port = ipv4EndPoint.port(); std::memset(&ipv4Address.sin_zero, 0, sizeof(ipv4Address.sin_zero)); std::memcpy(&address.get(), &ipv4Address, sizeof(ipv4Address)); return sizeof(SOCKADDR_IN); } else { const auto& ipv6EndPoint = endPoint.to_ipv6(); SOCKADDR_IN6 ipv6Address; ipv6Address.sin6_family = AF_INET6; std::memcpy(&ipv6Address.sin6_addr, ipv6EndPoint.address().bytes(), 16); ipv6Address.sin6_port = ipv6EndPoint.port(); ipv6Address.sin6_flowinfo = 0; ipv6Address.sin6_scope_struct = SCOPEID_UNSPECIFIED_INIT; std::memcpy(&address.get(), &ipv6Address, sizeof(ipv6Address)); return sizeof(SOCKADDR_IN6); } } #endif // CPPCORO_OS_WINNT
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include "socket_helpers.hpp" #include <cppcoro/net/ip_endpoint.hpp> #if CPPCORO_OS_WINNT #include <cstring> #include <cassert> #include <WinSock2.h> #include <WS2tcpip.h> #include <MSWSock.h> #include <Windows.h> cppcoro::net::ip_endpoint cppcoro::net::detail::sockaddr_to_ip_endpoint(const sockaddr& address) noexcept { if (address.sa_family == AF_INET) { SOCKADDR_IN ipv4Address; std::memcpy(&ipv4Address, &address, sizeof(ipv4Address)); std::uint8_t addressBytes[4]; std::memcpy(addressBytes, &ipv4Address.sin_addr, 4); return ipv4_endpoint{ ipv4_address{ addressBytes }, ntohs(ipv4Address.sin_port) }; } else { assert(address.sa_family == AF_INET6); SOCKADDR_IN6 ipv6Address; std::memcpy(&ipv6Address, &address, sizeof(ipv6Address)); return ipv6_endpoint{ ipv6_address{ ipv6Address.sin6_addr.u.Byte }, ntohs(ipv6Address.sin6_port) }; } } int cppcoro::net::detail::ip_endpoint_to_sockaddr( const ip_endpoint& endPoint, std::reference_wrapper<sockaddr_storage> address) noexcept { if (endPoint.is_ipv4()) { const auto& ipv4EndPoint = endPoint.to_ipv4(); SOCKADDR_IN ipv4Address; ipv4Address.sin_family = AF_INET; std::memcpy(&ipv4Address.sin_addr, ipv4EndPoint.address().bytes(), 4); ipv4Address.sin_port = htons(ipv4EndPoint.port()); std::memset(&ipv4Address.sin_zero, 0, sizeof(ipv4Address.sin_zero)); std::memcpy(&address.get(), &ipv4Address, sizeof(ipv4Address)); return sizeof(SOCKADDR_IN); } else { const auto& ipv6EndPoint = endPoint.to_ipv6(); SOCKADDR_IN6 ipv6Address; ipv6Address.sin6_family = AF_INET6; std::memcpy(&ipv6Address.sin6_addr, ipv6EndPoint.address().bytes(), 16); ipv6Address.sin6_port = htons(ipv6EndPoint.port()); ipv6Address.sin6_flowinfo = 0; ipv6Address.sin6_scope_struct = SCOPEID_UNSPECIFIED_INIT; std::memcpy(&address.get(), &ipv6Address, sizeof(ipv6Address)); return sizeof(SOCKADDR_IN6); } } #endif // CPPCORO_OS_WINNT
Fix byte-swapping of sockaddr.sin_port (#94)
Fix byte-swapping of sockaddr.sin_port (#94) Thanks to @vinniefalco for finding this one.
C++
mit
lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro,lewissbaker/cppcoro
7160bc7da7eaf4058bad87068458822b0886bfdc
game/ui/base/aliencontainmentscreen.cpp
game/ui/base/aliencontainmentscreen.cpp
#include "game/ui/base/aliencontainmentscreen.h" #include "forms/form.h" #include "forms/graphic.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/radiobutton.h" #include "forms/scrollbar.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/event.h" #include "framework/framework.h" #include "framework/logger.h" #include "framework/renderer.h" #include "game/state/city/base.h" #include "game/state/city/building.h" #include "game/state/gamestate.h" #include "game/ui/base/basestage.h" #include "game/ui/general/messagebox.h" #include "game/ui/general/transactioncontrol.h" #include <array> namespace OpenApoc { AlienContainmentScreen::AlienContainmentScreen(sp<GameState> state, bool forceLimits) : TransactionScreen(state, forceLimits) { form->findControlTyped<Label>("TITLE")->setText(tr("ALIEN CONTAINMENT")); form->findControlTyped<Graphic>("BG")->setImage( fw().data->loadImage("xcom3/ufodata/aliencon.pcx")); form->findControlTyped<Graphic>("DOLLAR_ICON")->setVisible(false); form->findControlTyped<Graphic>("DELTA_UNDERPANTS")->setVisible(false); form->findControlTyped<Label>("TEXT_FUNDS_DELTA")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_SOLDIERS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_BIOSCIS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_PHYSCIS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_ENGINRS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_ALIENS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_VEHICLES")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_AGENTS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_FLYING")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_GROUND")->setVisible(false); confirmClosureText = tr("Confirm Alien Containment Orders"); type = Type::Aliens; form->findControlTyped<RadioButton>("BUTTON_ALIENS")->setChecked(true); } void AlienContainmentScreen::closeScreen() { // Step 01: Check accommodation of different sorts { std::array<int, MAX_BASES> vecBioDelta; std::array<bool, MAX_BASES> vecChanged; vecBioDelta.fill(0); vecChanged.fill(false); // Find all delta and mark all that have any changes std::set<sp<TransactionControl>> linkedControls; for (auto &c : transactionControls[Type::Aliens]) { if (linkedControls.find(c) != linkedControls.end()) { continue; } int i = 0; for (auto &b : state->player_bases) { int bioDelta = c->getBioDelta(i); if (bioDelta) { vecBioDelta[i] += bioDelta; vecChanged[i] = true; } i++; } if (c->getLinked()) { for (auto &l : *c->getLinked()) { linkedControls.insert(l.lock()); } } } // Check every base, find first bad one int i = 0; StateRef<Base> bad_base; for (auto &b : state->player_bases) { if ((vecChanged[i] || forceLimits) && b.second->getUsage(*state, FacilityType::Capacity::Aliens, vecBioDelta[i]) > 100) { bad_base = b.second->building->base; break; } i++; } // Found bad base if (bad_base) { UString title(tr("Alien Containment space exceeded")); UString message(tr("Alien Containment space exceeded. Destroy more Aliens!")); fw().stageQueueCommand( {StageCmd::Command::PUSH, mksp<MessageBox>(title, message, MessageBox::ButtonOptions::Ok)}); if (bad_base != state->current_base) { for (auto &view : miniViews) { if (bad_base == view->getData<Base>()) { currentView = view; changeBase(bad_base); break; } } } return; } } // Step 02: If we reached this then go! executeOrders(); fw().stageQueueCommand({StageCmd::Command::POP}); return; } void AlienContainmentScreen::executeOrders() { int rightIdx = getRightIndex(); // AlienContainment: Simply apply for (auto &c : transactionControls[Type::Aliens]) { int i = 0; for (auto &b : state->player_bases) { if (c->tradeState.shipmentsFrom(i) > 0) { b.second->inventoryBioEquipment[c->itemId] = c->tradeState.getStock(i, rightIdx, true); } i++; } } } }; // namespace OpenApoc
#include "game/ui/base/aliencontainmentscreen.h" #include "forms/form.h" #include "forms/graphic.h" #include "forms/graphicbutton.h" #include "forms/label.h" #include "forms/radiobutton.h" #include "forms/scrollbar.h" #include "forms/ui.h" #include "framework/data.h" #include "framework/event.h" #include "framework/framework.h" #include "framework/logger.h" #include "framework/renderer.h" #include "game/state/city/base.h" #include "game/state/city/building.h" #include "game/state/gamestate.h" #include "game/ui/base/basestage.h" #include "game/ui/general/messagebox.h" #include "game/ui/general/transactioncontrol.h" #include <array> namespace OpenApoc { AlienContainmentScreen::AlienContainmentScreen(sp<GameState> state, bool forceLimits) : TransactionScreen(state, forceLimits) { form->findControlTyped<Label>("TITLE")->setText(tr("ALIEN CONTAINMENT")); form->findControlTyped<Graphic>("BG")->setImage( fw().data->loadImage("xcom3/ufodata/aliencon.pcx")); form->findControlTyped<Graphic>("DOLLAR_ICON")->setVisible(false); form->findControlTyped<Graphic>("DELTA_UNDERPANTS")->setVisible(false); form->findControlTyped<Label>("TEXT_FUNDS_DELTA")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_SOLDIERS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_BIOSCIS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_PHYSCIS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_ENGINRS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_ALIENS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_VEHICLES")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_AGENTS")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_FLYING")->setVisible(false); form->findControlTyped<RadioButton>("BUTTON_GROUND")->setVisible(false); confirmClosureText = tr("Confirm Alien Containment Orders"); type = Type::Aliens; form->findControlTyped<RadioButton>("BUTTON_ALIENS")->setChecked(true); } void AlienContainmentScreen::closeScreen() { // Step 01: Check accommodation of different sorts { std::array<int, MAX_BASES> vecBioDelta; std::array<bool, MAX_BASES> vecChanged; vecBioDelta.fill(0); vecChanged.fill(false); // Find all delta and mark all that have any changes std::set<sp<TransactionControl>> linkedControls; for (auto &c : transactionControls[Type::Aliens]) { if (linkedControls.find(c) != linkedControls.end()) { continue; } int i = 0; for ([[maybe_unused]] const auto &b : state->player_bases) { int bioDelta = c->getBioDelta(i); if (bioDelta) { vecBioDelta[i] += bioDelta; vecChanged[i] = true; } i++; } if (c->getLinked()) { for (auto &l : *c->getLinked()) { linkedControls.insert(l.lock()); } } } // Check every base, find first bad one int i = 0; StateRef<Base> bad_base; for (auto &b : state->player_bases) { if ((vecChanged[i] || forceLimits) && b.second->getUsage(*state, FacilityType::Capacity::Aliens, vecBioDelta[i]) > 100) { bad_base = b.second->building->base; break; } i++; } // Found bad base if (bad_base) { UString title(tr("Alien Containment space exceeded")); UString message(tr("Alien Containment space exceeded. Destroy more Aliens!")); fw().stageQueueCommand( {StageCmd::Command::PUSH, mksp<MessageBox>(title, message, MessageBox::ButtonOptions::Ok)}); if (bad_base != state->current_base) { for (auto &view : miniViews) { if (bad_base == view->getData<Base>()) { currentView = view; changeBase(bad_base); break; } } } return; } } // Step 02: If we reached this then go! executeOrders(); fw().stageQueueCommand({StageCmd::Command::POP}); return; } void AlienContainmentScreen::executeOrders() { int rightIdx = getRightIndex(); // AlienContainment: Simply apply for (auto &c : transactionControls[Type::Aliens]) { int i = 0; for (auto &b : state->player_bases) { if (c->tradeState.shipmentsFrom(i) > 0) { b.second->inventoryBioEquipment[c->itemId] = c->tradeState.getStock(i, rightIdx, true); } i++; } } } }; // namespace OpenApoc
Mark unused variable in AlienContainmentScreen::closeScreen
Mark unused variable in AlienContainmentScreen::closeScreen
C++
mit
Istrebitel/OpenApoc,steveschnepp/OpenApoc,pmprog/OpenApoc,steveschnepp/OpenApoc,pmprog/OpenApoc,Istrebitel/OpenApoc
4e2a8b32b43a0ebd4bcf2ffe319c85e447093b6c
tests/init.cpp
tests/init.cpp
#include <matrix.hpp> #include <catch.hpp> SCENARIO("copy constructor") { Matrix matrix; Matrix copy(matrix); REQUIRE(copy.strings() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("operator +") { Matrix matrix (2, 2); Matrix matrix1 = Matrix (2, 2); REQUIRE(matrix + matrix == matrix1); } SCENARIO("operator *") { Matrix matrix (2,2); Matrix matrix3 = Matrix (2,2); REQUIRE(matrix * matrix == matrix3); } SCENARIO("operator =") { Matrix matrix (2,2); Matrix matrix2 = matrix; REQUIRE(matrix == matrix2); } SCENARIO("operator ==") { Matrix matrix (2,2); Matrix matrix2 = Matrix (2,2); REQUIRE(matrix == matrix2); }
#include <matrix.hpp> #include <catch.hpp> SCENARIO("copy constructor") { Matrix matrix; Matrix copy(matrix); REQUIRE(copy.strings() == 2); REQUIRE(copy.columns() == 2); } SCENARIO("operator +") { Matrix matrix (2, 2); Matrix matrix2 (2, 2); Matrix matrix3 (2, 2); std::ifstream("matrix.txt") >> matrix 1; std::ifstream("matrix2.txt") >> matrix 2; std::ifstream("sum.txt") >> matrix 3; REQUIRE(matrix1 + matrix2 == matrix3); } SCENARIO("operator *") { Matrix matrix (2,2); Matrix matrix2 (2,2); Matrix matrix3 (2,2); std::ifstream("matrix.txt") >> matrix 1; std::ifstream("matrix2.txt") >> matrix 2; std::ifstream("multi.txt") >> matrix 3; REQUIRE(matrix1 * matrix2 == matrix3); } SCENARIO("operator =") { Matrix matrix (2,2); Matrix matrix2 = matrix; REQUIRE(matrix == matrix2); } SCENARIO("operator ==") { Matrix matrix (2,2); Matrix matrix2 = Matrix (2,2); REQUIRE(matrix == matrix2); }
Update init.cpp
Update init.cpp
C++
mit
elinagabitova/matrix
3b52d1305d46dbd3f9953bb7c086037bee49fec5
test/main.cpp
test/main.cpp
#define CATCH_CONFIG_RUNNER #include "./catch.hpp" #include "./ReQL.hpp" #include <string> #include <vector> int main(int argc, char **argv) { int result = Catch::Session().run(argc, argv); try { ReQL::Connection conn; ReQL::db_list(std::vector<ReQL::Query>()) .filter(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(1.0)})), ReQL::var(std::vector<ReQL::Query>({ReQL::Query(1.0)})) .ne(std::vector<ReQL::Query>({ ReQL::Query(std::wstring(L"rethinkdb")) })) })) })) .for_each(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(2.0)})), ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>()), ReQL::db_drop(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) })) .funcall(std::vector<ReQL::Query>({ ReQL::db(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) .wait(std::vector<ReQL::Query>()) })) })) })) .no_reply(conn); conn.close(); } catch (ReQL::ReQLError &e) { (void)e; } return result; }
#include <winsock2.h> #define CATCH_CONFIG_RUNNER #include "./catch.hpp" #include "./ReQL.hpp" #include <string> #include <vector> int main(int argc, char **argv) { int result = Catch::Session().run(argc, argv); try { ReQL::Connection conn; ReQL::db_list(std::vector<ReQL::Query>()) .filter(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(1.0)})), ReQL::var(std::vector<ReQL::Query>({ReQL::Query(1.0)})) .ne(std::vector<ReQL::Query>({ ReQL::Query(std::wstring(L"rethinkdb")) })) })) })) .for_each(std::vector<ReQL::Query>({ ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>({ReQL::Query(2.0)})), ReQL::func(std::vector<ReQL::Query>({ ReQL::Query(std::vector<ReQL::Query>()), ReQL::db_drop(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) })) .funcall(std::vector<ReQL::Query>({ ReQL::db(std::vector<ReQL::Query>({ ReQL::var(std::vector<ReQL::Query>({ReQL::Query(2.0)})) })) .wait(std::vector<ReQL::Query>()) })) })) })) .no_reply(conn); conn.close(); } catch (ReQL::ReQLError &e) { (void)e; } return result; }
Fix windows include warning.
Fix windows include warning.
C++
apache-2.0
grandquista/ReQL-Core,grandquista/ReQL-Core,grandquista/ReQL-Core,grandquista/ReQL-Core
36fa833982d86ad4de9810e1ae63ec98604f5765
ode/ode/test/test_buggy.cpp
ode/ode/test/test_buggy.cpp
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ /* buggy with suspension. this also shows you how to use geom groups. */ #include <ode/ode.h> #include <drawstuff/drawstuff.h> #ifdef MSVC #pragma warning(disable:4244 4305) // for VC++, no precision loss complaints #endif // select correct drawing functions #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #define dsDrawSphere dsDrawSphereD #define dsDrawCylinder dsDrawCylinderD #define dsDrawCappedCylinder dsDrawCappedCylinderD #endif // some constants #define LENGTH 0.7 // chassis length #define WIDTH 0.5 // chassis width #define HEIGHT 0.2 // chassis height #define RADIUS 0.18 // wheel radius #define STARTZ 0.5 // starting height of chassis #define CMASS 1 // chassis mass #define WMASS 0.2 // wheel mass // dynamics and collision objects (chassis, 3 wheels, environment) static dWorldID world; static dSpaceID space; static dBodyID body[4]; static dJointID joint[3]; // joint[0] is the front wheel static dJointGroupID contactgroup; static dGeomID ground,geom_group; static dGeomID box[1]; static dGeomID sphere[3]; static dGeomID ground_box; // things that the user controls static dReal speed=0,steer=0; // user commands // this is called by dSpaceCollide when two objects in space are // potentially colliding. static void nearCallback (void *data, dGeomID o1, dGeomID o2) { int i,n; // only collide things with the ground int g1 = (o1 == ground || o1 == ground_box); int g2 = (o2 == ground || o2 == ground_box); if (!(g1 ^ g2)) return; const int N = 10; dContact contact[N]; n = dCollide (o1,o2,N,&contact[0].geom,sizeof(dContact)); if (n > 0) { for (i=0; i<n; i++) { contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactSoftCFM; contact[i].surface.mu = dInfinity; contact[i].surface.slip1 = 0.1; contact[i].surface.slip2 = 0.1; contact[i].surface.soft_erp = 0.5; contact[i].surface.soft_cfm = 0.3; dJointID c = dJointCreateContact (world,contactgroup,&contact[i]); dJointAttach (c, dGeomGetBody(contact[i].geom.g1), dGeomGetBody(contact[i].geom.g2)); } } } // start simulation - set viewpoint static void start() { static float xyz[3] = {0.8317f,-0.9817f,0.8000f}; static float hpr[3] = {121.0000f,-27.5000f,0.0000f}; dsSetViewpoint (xyz,hpr); printf ("Press:\t'a' to increase speed.\n" "\t'z' to decrease speed.\n" "\t',' to steer left.\n" "\t'.' to steer right.\n" "\t' ' to reset speed and steering.\n"); } // called when a key pressed static void command (int cmd) { switch (cmd) { case 'a': case 'A': speed += 0.3; break; case 'z': case 'Z': speed -= 0.3; break; case ',': steer -= 0.5; break; case '.': steer += 0.5; break; case ' ': speed = 0; steer = 0; break; } } // simulation loop static void simLoop (int pause) { int i; if (!pause) { // motor dJointSetHinge2Param (joint[0],dParamVel2,-speed); dJointSetHinge2Param (joint[0],dParamFMax2,0.1); // steering dReal v = steer - dJointGetHinge2Angle1 (joint[0]); if (v > 0.1) v = 0.1; if (v < -0.1) v = -0.1; v *= 10.0; dJointSetHinge2Param (joint[0],dParamVel,v); dJointSetHinge2Param (joint[0],dParamFMax,0.2); dJointSetHinge2Param (joint[0],dParamLoStop,-0.75); dJointSetHinge2Param (joint[0],dParamHiStop,0.75); dJointSetHinge2Param (joint[0],dParamFudgeFactor,0.1); dSpaceCollide (space,0,&nearCallback); dWorldStep (world,0.05); // remove all contact joints dJointGroupEmpty (contactgroup); } dsSetColor (0,1,1); dsSetTexture (DS_WOOD); dReal sides[3] = {LENGTH,WIDTH,HEIGHT}; dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides); dsSetColor (1,1,1); for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]), dBodyGetRotation(body[i]),0.02f,RADIUS); dVector3 ss; dGeomBoxGetLengths (ground_box,ss); dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss); /* printf ("%.10f %.10f %.10f %.10f\n", dJointGetHingeAngle (joint[1]), dJointGetHingeAngle (joint[2]), dJointGetHingeAngleRate (joint[1]), dJointGetHingeAngleRate (joint[2])); */ } int main (int argc, char **argv) { int i; dMass m; // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = &start; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = "../../drawstuff/textures"; // create world world = dWorldCreate(); space = dHashSpaceCreate(); contactgroup = dJointGroupCreate (0); dWorldSetGravity (world,0,0,-0.5); ground = dCreatePlane (space,0,0,1,0); // chassis body body[0] = dBodyCreate (world); dBodySetPosition (body[0],0,0,STARTZ); dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT); dMassAdjust (&m,CMASS); dBodySetMass (body[0],&m); box[0] = dCreateBox (0,LENGTH,WIDTH,HEIGHT); dGeomSetBody (box[0],body[0]); // wheel bodies for (i=1; i<=3; i++) { body[i] = dBodyCreate (world); dQuaternion q; dQFromAxisAndAngle (q,1,0,0,M_PI*0.5); dBodySetQuaternion (body[i],q); dMassSetSphere (&m,1,RADIUS); dMassAdjust (&m,WMASS); dBodySetMass (body[i],&m); sphere[i-1] = dCreateSphere (0,RADIUS); dGeomSetBody (sphere[i-1],body[i]); } dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5); dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5); dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5); // front wheel hinge /* joint[0] = dJointCreateHinge2 (world,0); dJointAttach (joint[0],body[0],body[1]); const dReal *a = dBodyGetPosition (body[1]); dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]); dJointSetHinge2Axis1 (joint[0],0,0,1); dJointSetHinge2Axis2 (joint[0],0,1,0); */ // front and back wheel hinges for (i=0; i<3; i++) { joint[i] = dJointCreateHinge2 (world,0); dJointAttach (joint[i],body[0],body[i+1]); const dReal *a = dBodyGetPosition (body[i+1]); dJointSetHinge2Anchor (joint[i],a[0],a[1],a[2]); dJointSetHinge2Axis1 (joint[i],0,0,1); dJointSetHinge2Axis2 (joint[i],0,1,0); } // set joint suspension for (i=0; i<3; i++) { dJointSetHinge2Param (joint[i],dParamSuspensionERP,0.4); dJointSetHinge2Param (joint[i],dParamSuspensionCFM,0.8); } // lock back wheels along the steering axis for (i=1; i<3; i++) { // set stops to make sure wheels always stay in alignment dJointSetHinge2Param (joint[i],dParamLoStop,0); dJointSetHinge2Param (joint[i],dParamHiStop,0); // the following alternative method is no good as the wheels may get out // of alignment: // dJointSetHinge2Param (joint[i],dParamVel,0); // dJointSetHinge2Param (joint[i],dParamFMax,dInfinity); } // create geometry group and add it to the space geom_group = dCreateGeomGroup (space); dGeomGroupAdd (geom_group,box[0]); dGeomGroupAdd (geom_group,sphere[0]); dGeomGroupAdd (geom_group,sphere[1]); dGeomGroupAdd (geom_group,sphere[2]); // environment ground_box = dCreateBox (space,2,1.5,1); dMatrix3 R; dRFromAxisAndAngle (R,0,1,0,-0.15); dGeomSetPosition (ground_box,2,0,-0.34); dGeomSetRotation (ground_box,R); // run simulation dsSimulationLoop (argc,argv,352,288,&fn); dJointGroupDestroy (contactgroup); dSpaceDestroy (space); dWorldDestroy (world); dGeomDestroy (box[0]); dGeomDestroy (sphere[0]); dGeomDestroy (sphere[1]); dGeomDestroy (sphere[2]); return 0; }
/************************************************************************* * * * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. * * All rights reserved. Email: [email protected] Web: www.q12.org * * * * This library is free software; you can redistribute it and/or * * modify it under the terms of EITHER: * * (1) The GNU Lesser General Public License as published by the Free * * Software Foundation; either version 2.1 of the License, or (at * * your option) any later version. The text of the GNU Lesser * * General Public License is included with this library in the * * file LICENSE.TXT. * * (2) The BSD-style license that is included with this library in * * the file LICENSE-BSD.TXT. * * * * This library is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files * * LICENSE.TXT and LICENSE-BSD.TXT for more details. * * * *************************************************************************/ /* buggy with suspension. this also shows you how to use geom groups. */ #include <ode/ode.h> #include <drawstuff/drawstuff.h> #ifdef MSVC #pragma warning(disable:4244 4305) // for VC++, no precision loss complaints #endif // select correct drawing functions #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #define dsDrawSphere dsDrawSphereD #define dsDrawCylinder dsDrawCylinderD #define dsDrawCappedCylinder dsDrawCappedCylinderD #endif // some constants #define LENGTH 0.7 // chassis length #define WIDTH 0.5 // chassis width #define HEIGHT 0.2 // chassis height #define RADIUS 0.18 // wheel radius #define STARTZ 0.5 // starting height of chassis #define CMASS 1 // chassis mass #define WMASS 0.2 // wheel mass // dynamics and collision objects (chassis, 3 wheels, environment) static dWorldID world; static dSpaceID space; static dBodyID body[4]; static dJointID joint[3]; // joint[0] is the front wheel static dJointGroupID contactgroup; static dGeomID ground,geom_group; static dGeomID box[1]; static dGeomID sphere[3]; static dGeomID ground_box; // things that the user controls static dReal speed=0,steer=0; // user commands // this is called by dSpaceCollide when two objects in space are // potentially colliding. static void nearCallback (void *data, dGeomID o1, dGeomID o2) { int i,n; // only collide things with the ground int g1 = (o1 == ground || o1 == ground_box); int g2 = (o2 == ground || o2 == ground_box); if (!(g1 ^ g2)) return; const int N = 10; dContact contact[N]; n = dCollide (o1,o2,N,&contact[0].geom,sizeof(dContact)); if (n > 0) { for (i=0; i<n; i++) { contact[i].surface.mode = dContactSlip1 | dContactSlip2 | dContactSoftERP | dContactSoftCFM | dContactApprox1; contact[i].surface.mu = dInfinity; contact[i].surface.slip1 = 0.1; contact[i].surface.slip2 = 0.1; contact[i].surface.soft_erp = 0.5; contact[i].surface.soft_cfm = 0.3; dJointID c = dJointCreateContact (world,contactgroup,&contact[i]); dJointAttach (c, dGeomGetBody(contact[i].geom.g1), dGeomGetBody(contact[i].geom.g2)); } } } // start simulation - set viewpoint static void start() { static float xyz[3] = {0.8317f,-0.9817f,0.8000f}; static float hpr[3] = {121.0000f,-27.5000f,0.0000f}; dsSetViewpoint (xyz,hpr); printf ("Press:\t'a' to increase speed.\n" "\t'z' to decrease speed.\n" "\t',' to steer left.\n" "\t'.' to steer right.\n" "\t' ' to reset speed and steering.\n"); } // called when a key pressed static void command (int cmd) { switch (cmd) { case 'a': case 'A': speed += 0.3; break; case 'z': case 'Z': speed -= 0.3; break; case ',': steer -= 0.5; break; case '.': steer += 0.5; break; case ' ': speed = 0; steer = 0; break; } } // simulation loop static void simLoop (int pause) { int i; if (!pause) { // motor dJointSetHinge2Param (joint[0],dParamVel2,-speed); dJointSetHinge2Param (joint[0],dParamFMax2,0.1); // steering dReal v = steer - dJointGetHinge2Angle1 (joint[0]); if (v > 0.1) v = 0.1; if (v < -0.1) v = -0.1; v *= 10.0; dJointSetHinge2Param (joint[0],dParamVel,v); dJointSetHinge2Param (joint[0],dParamFMax,0.2); dJointSetHinge2Param (joint[0],dParamLoStop,-0.75); dJointSetHinge2Param (joint[0],dParamHiStop,0.75); dJointSetHinge2Param (joint[0],dParamFudgeFactor,0.1); dSpaceCollide (space,0,&nearCallback); dWorldStep (world,0.05); // remove all contact joints dJointGroupEmpty (contactgroup); } dsSetColor (0,1,1); dsSetTexture (DS_WOOD); dReal sides[3] = {LENGTH,WIDTH,HEIGHT}; dsDrawBox (dBodyGetPosition(body[0]),dBodyGetRotation(body[0]),sides); dsSetColor (1,1,1); for (i=1; i<=3; i++) dsDrawCylinder (dBodyGetPosition(body[i]), dBodyGetRotation(body[i]),0.02f,RADIUS); dVector3 ss; dGeomBoxGetLengths (ground_box,ss); dsDrawBox (dGeomGetPosition(ground_box),dGeomGetRotation(ground_box),ss); /* printf ("%.10f %.10f %.10f %.10f\n", dJointGetHingeAngle (joint[1]), dJointGetHingeAngle (joint[2]), dJointGetHingeAngleRate (joint[1]), dJointGetHingeAngleRate (joint[2])); */ } int main (int argc, char **argv) { int i; dMass m; // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = &start; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = "../../drawstuff/textures"; // create world world = dWorldCreate(); space = dHashSpaceCreate(); contactgroup = dJointGroupCreate (0); dWorldSetGravity (world,0,0,-0.5); ground = dCreatePlane (space,0,0,1,0); // chassis body body[0] = dBodyCreate (world); dBodySetPosition (body[0],0,0,STARTZ); dMassSetBox (&m,1,LENGTH,WIDTH,HEIGHT); dMassAdjust (&m,CMASS); dBodySetMass (body[0],&m); box[0] = dCreateBox (0,LENGTH,WIDTH,HEIGHT); dGeomSetBody (box[0],body[0]); // wheel bodies for (i=1; i<=3; i++) { body[i] = dBodyCreate (world); dQuaternion q; dQFromAxisAndAngle (q,1,0,0,M_PI*0.5); dBodySetQuaternion (body[i],q); dMassSetSphere (&m,1,RADIUS); dMassAdjust (&m,WMASS); dBodySetMass (body[i],&m); sphere[i-1] = dCreateSphere (0,RADIUS); dGeomSetBody (sphere[i-1],body[i]); } dBodySetPosition (body[1],0.5*LENGTH,0,STARTZ-HEIGHT*0.5); dBodySetPosition (body[2],-0.5*LENGTH, WIDTH*0.5,STARTZ-HEIGHT*0.5); dBodySetPosition (body[3],-0.5*LENGTH,-WIDTH*0.5,STARTZ-HEIGHT*0.5); // front wheel hinge /* joint[0] = dJointCreateHinge2 (world,0); dJointAttach (joint[0],body[0],body[1]); const dReal *a = dBodyGetPosition (body[1]); dJointSetHinge2Anchor (joint[0],a[0],a[1],a[2]); dJointSetHinge2Axis1 (joint[0],0,0,1); dJointSetHinge2Axis2 (joint[0],0,1,0); */ // front and back wheel hinges for (i=0; i<3; i++) { joint[i] = dJointCreateHinge2 (world,0); dJointAttach (joint[i],body[0],body[i+1]); const dReal *a = dBodyGetPosition (body[i+1]); dJointSetHinge2Anchor (joint[i],a[0],a[1],a[2]); dJointSetHinge2Axis1 (joint[i],0,0,1); dJointSetHinge2Axis2 (joint[i],0,1,0); } // set joint suspension for (i=0; i<3; i++) { dJointSetHinge2Param (joint[i],dParamSuspensionERP,0.4); dJointSetHinge2Param (joint[i],dParamSuspensionCFM,0.8); } // lock back wheels along the steering axis for (i=1; i<3; i++) { // set stops to make sure wheels always stay in alignment dJointSetHinge2Param (joint[i],dParamLoStop,0); dJointSetHinge2Param (joint[i],dParamHiStop,0); // the following alternative method is no good as the wheels may get out // of alignment: // dJointSetHinge2Param (joint[i],dParamVel,0); // dJointSetHinge2Param (joint[i],dParamFMax,dInfinity); } // create geometry group and add it to the space geom_group = dCreateGeomGroup (space); dGeomGroupAdd (geom_group,box[0]); dGeomGroupAdd (geom_group,sphere[0]); dGeomGroupAdd (geom_group,sphere[1]); dGeomGroupAdd (geom_group,sphere[2]); // environment ground_box = dCreateBox (space,2,1.5,1); dMatrix3 R; dRFromAxisAndAngle (R,0,1,0,-0.15); dGeomSetPosition (ground_box,2,0,-0.34); dGeomSetRotation (ground_box,R); // run simulation dsSimulationLoop (argc,argv,352,288,&fn); dJointGroupDestroy (contactgroup); dSpaceDestroy (space); dWorldDestroy (world); dGeomDestroy (box[0]); dGeomDestroy (sphere[0]); dGeomDestroy (sphere[1]); dGeomDestroy (sphere[2]); return 0; }
use the dContactApprox1 contact mode to prevent multi-contact strickness on the wheels.
use the dContactApprox1 contact mode to prevent multi-contact strickness on the wheels.
C++
lgpl-2.1
keletskiy/ode,keletskiy/ode,nabijaczleweli/ODE,nabijaczleweli/ODE,nabijaczleweli/ODE,nabijaczleweli/ODE,nabijaczleweli/ODE,keletskiy/ode,keletskiy/ode,nabijaczleweli/ODE,keletskiy/ode,keletskiy/ode
c3d7dcc3fbdb890fb32d6c0595f93f0d5b69a3cd
test/test.cpp
test/test.cpp
#include "../libply++/libply++.h" struct Vertex { Vertex(double x, double y, double z) : x(x), y(y), z(z) {}; double x, y, z; }; struct Mesh { typedef unsigned int VertexIndex; typedef std::array<VertexIndex, 3> TriangleIndices; typedef std::vector<Vertex> VertexList; typedef std::vector<TriangleIndices> TriangleIndicesList; Mesh(const VertexList& vertices, const TriangleIndicesList& triangles) : vertices(vertices), triangles(triangles) {}; Mesh(VertexList&& vertices, TriangleIndicesList&& triangles) : vertices(std::move(vertices)), triangles(std::move(triangles)) {}; VertexList vertices; TriangleIndicesList triangles; }; class VertexInserter : public libply::IElementInserter { public: VertexInserter(Mesh::VertexList& vertices); // Implements IElementInserter. virtual libply::PropertyMap properties() override; virtual void insert() override; private: libply::ScalarProperty<double> x; libply::ScalarProperty<double> y; libply::ScalarProperty<double> z; Mesh::VertexList& m_vertices; }; class TriangleInserter : public libply::IElementInserter { public: TriangleInserter(Mesh::TriangleIndicesList& vertices); // Implements IElementInserter. virtual libply::PropertyMap properties() override; virtual void insert() override; private: libply::ScalarProperty<unsigned int> v0; libply::ScalarProperty<unsigned int> v1; libply::ScalarProperty<unsigned int> v2; Mesh::TriangleIndicesList& m_triangles; }; VertexInserter::VertexInserter(Mesh::VertexList& vertices) : m_vertices(vertices) { } libply::PropertyMap VertexInserter::properties() { libply::PropertyMap pm{{ 0, &x },{ 1, &y },{ 2, &z }}; return pm; } void VertexInserter::insert() { m_vertices.emplace_back(x.value(), y.value(), z.value()); } TriangleInserter::TriangleInserter(Mesh::TriangleIndicesList& triangles) : m_triangles(triangles) { } libply::PropertyMap TriangleInserter::properties() { libply::PropertyMap pm{{0, &v0},{1, &v1},{2, &v2}}; return pm; } void TriangleInserter::insert() { // Must construct and move temporary object, because std::array doesn't have an initializer list constructor. m_triangles.emplace_back(std::move(Mesh::TriangleIndices{ v0.value(), v1.value(), v2.value() })); } void readply(std::wstring filename, Mesh::VertexList& vertices, Mesh::TriangleIndicesList& triangles) { libply::File file(filename); const auto& definitions = file.definitions(); const auto vertexDefinition = definitions.at(0); const size_t vertexCount = vertexDefinition.size; vertices.reserve(vertexCount); VertexInserter vertexInserter(vertices); const auto triangleDefinition = definitions.at(1); const size_t triangleCount = triangleDefinition.size; triangles.reserve(triangleCount); TriangleInserter triangleInserter(triangles); libply::InserterMap inserters = { { "vertex" , &vertexInserter }, { "face" , &triangleInserter } }; file.readElements(inserters); } int main() { Mesh::VertexList ascii_vertices; Mesh::TriangleIndicesList ascii_triangles; readply(L"../test/data/test.ply", ascii_vertices, ascii_triangles); Mesh::VertexList bin_vertices; Mesh::TriangleIndicesList bin_triangles; readply(L"../test/data/test_bin.ply", bin_vertices, bin_triangles); }
#include <iostream> #include "../libply++/libply++.h" bool areClose(double a, double b) { const double EPSILON = 1.0e-1; return abs(a - b) < EPSILON; } struct Vertex { Vertex(double x, double y, double z) : x(x), y(y), z(z) {}; bool operator==(const Vertex& other) const { return areClose(x, other.x) && areClose(y, other.y) && areClose(z, other.z); }; double x, y, z; }; struct Mesh { typedef unsigned int VertexIndex; typedef std::array<VertexIndex, 3> TriangleIndices; typedef std::vector<Vertex> VertexList; typedef std::vector<TriangleIndices> TriangleIndicesList; Mesh(const VertexList& vertices, const TriangleIndicesList& triangles) : vertices(vertices), triangles(triangles) {}; Mesh(VertexList&& vertices, TriangleIndicesList&& triangles) : vertices(std::move(vertices)), triangles(std::move(triangles)) {}; VertexList vertices; TriangleIndicesList triangles; }; class VertexInserter : public libply::IElementInserter { public: VertexInserter(Mesh::VertexList& vertices); // Implements IElementInserter. virtual libply::PropertyMap properties() override; virtual void insert() override; private: libply::ScalarProperty<double> x; libply::ScalarProperty<double> y; libply::ScalarProperty<double> z; Mesh::VertexList& m_vertices; }; class TriangleInserter : public libply::IElementInserter { public: TriangleInserter(Mesh::TriangleIndicesList& vertices); // Implements IElementInserter. virtual libply::PropertyMap properties() override; virtual void insert() override; private: libply::ScalarProperty<unsigned int> v0; libply::ScalarProperty<unsigned int> v1; libply::ScalarProperty<unsigned int> v2; Mesh::TriangleIndicesList& m_triangles; }; VertexInserter::VertexInserter(Mesh::VertexList& vertices) : m_vertices(vertices) { } libply::PropertyMap VertexInserter::properties() { libply::PropertyMap pm{{ 0, &x },{ 1, &y },{ 2, &z }}; return pm; } void VertexInserter::insert() { m_vertices.emplace_back(x.value(), y.value(), z.value()); } TriangleInserter::TriangleInserter(Mesh::TriangleIndicesList& triangles) : m_triangles(triangles) { } libply::PropertyMap TriangleInserter::properties() { libply::PropertyMap pm{{0, &v0},{1, &v1},{2, &v2}}; return pm; } void TriangleInserter::insert() { // Must construct and move temporary object, because std::array doesn't have an initializer list constructor. m_triangles.emplace_back(std::move(Mesh::TriangleIndices{ v0.value(), v1.value(), v2.value() })); } void readply(std::wstring filename, Mesh::VertexList& vertices, Mesh::TriangleIndicesList& triangles) { libply::File file(filename); const auto& definitions = file.definitions(); const auto vertexDefinition = definitions.at(0); const size_t vertexCount = vertexDefinition.size; vertices.reserve(vertexCount); VertexInserter vertexInserter(vertices); const auto triangleDefinition = definitions.at(1); const size_t triangleCount = triangleDefinition.size; triangles.reserve(triangleCount); TriangleInserter triangleInserter(triangles); libply::InserterMap inserters = { { "vertex" , &vertexInserter }, { "face" , &triangleInserter } }; file.readElements(inserters); } bool compare_vertices(const Mesh::VertexList& left, const Mesh::VertexList& right) { if (left.size() != right.size()) { std::cout << "Length mismatch" << std::endl; return false; } for (unsigned int i = 0; i < left.size(); ++i) { if (!(left[i] == right[i])) { std::cout << "vertex " << i << " are different" << std::endl; } } return true; } int main() { Mesh::VertexList ascii_vertices; Mesh::TriangleIndicesList ascii_triangles; readply(L"../test/data/test.ply", ascii_vertices, ascii_triangles); Mesh::VertexList bin_vertices; Mesh::TriangleIndicesList bin_triangles; readply(L"../test/data/test_bin.ply", bin_vertices, bin_triangles); compare_vertices(ascii_vertices, bin_vertices); }
Add vertices comparison test.
Add vertices comparison test.
C++
mit
srajotte/libplyxx
f4141032a8719db55cfbd544ce349eedc48b532e
libgo/block_object.cpp
libgo/block_object.cpp
#include "block_object.h" #include "scheduler.h" #include "error.h" #include <unistd.h> #include <mutex> #include <limits> namespace co { BlockObject::BlockObject(std::size_t init_wakeup, std::size_t max_wakeup) : wakeup_(init_wakeup), max_wakeup_(max_wakeup) { DebugPrint(dbg_syncblock, "BlockObject::BlockObject this=%p", this); } BlockObject::~BlockObject() { if (!lock_.try_lock()) { ThrowError(eCoErrorCode::ec_block_object_locked); } if (!wait_queue_.empty()) { ThrowError(eCoErrorCode::ec_block_object_waiting); } DebugPrint(dbg_syncblock, "BlockObject::~BlockObject this=%p", this); } void BlockObject::CoBlockWait() { if (!g_Scheduler.IsCoroutine()) { while (!TryBlockWait()) usleep(10 * 1000); return ; } std::unique_lock<LFLock> lock(lock_); if (wakeup_ > 0) { DebugPrint(dbg_syncblock, "wait immedaitely done."); --wakeup_; return ; } lock.unlock(); Task* tk = g_Scheduler.GetCurrentTask(); tk->block_ = this; tk->state_ = TaskState::sys_block; tk->block_timeout_ = MininumTimeDurationType::zero(); tk->is_block_timeout_ = false; ++ tk->block_sequence_; DebugPrint(dbg_syncblock, "wait to switch. task(%s)", tk->DebugInfo()); g_Scheduler.CoYield(); } bool BlockObject::CoBlockWaitTimed(MininumTimeDurationType timeo) { auto begin = std::chrono::high_resolution_clock::now(); if (!g_Scheduler.IsCoroutine()) { while (!TryBlockWait() && std::chrono::duration_cast<MininumTimeDurationType> (std::chrono::high_resolution_clock::now() - begin) < timeo) usleep(10 * 1000); return false; } std::unique_lock<LFLock> lock(lock_); if (wakeup_ > 0) { DebugPrint(dbg_syncblock, "wait immedaitely done."); --wakeup_; return true; } lock.unlock(); Task* tk = g_Scheduler.GetCurrentTask(); tk->block_ = this; tk->state_ = TaskState::sys_block; ++tk->block_sequence_; tk->block_timeout_ = timeo; tk->is_block_timeout_ = false; DebugPrint(dbg_syncblock, "wait to switch. task(%s)", tk->DebugInfo()); g_Scheduler.CoYield(); return !tk->is_block_timeout_; } bool BlockObject::TryBlockWait() { std::unique_lock<LFLock> lock(lock_); if (wakeup_ == 0) return false; --wakeup_; DebugPrint(dbg_syncblock, "try wait success."); return true; } bool BlockObject::Wakeup() { std::unique_lock<LFLock> lock(lock_); Task* tk = wait_queue_.pop(); if (!tk) { if (wakeup_ >= max_wakeup_) { DebugPrint(dbg_syncblock, "wakeup failed."); return false; } ++wakeup_; DebugPrint(dbg_syncblock, "wakeup to %lu.", (long unsigned)wakeup_); return true; } lock.unlock(); tk->block_ = nullptr; if (tk->block_timer_) { // block cancel timer必须在lock之外, 因为里面会lock g_Scheduler.BlockCancelTimer(tk->block_timer_); tk->block_timer_.reset(); } DebugPrint(dbg_syncblock, "wakeup task(%s).", tk->DebugInfo()); g_Scheduler.AddTaskRunnable(tk); return true; } void BlockObject::CancelWait(Task* tk, uint32_t block_sequence, bool in_timer) { std::unique_lock<LFLock> lock(lock_); if (tk->block_ != this) { DebugPrint(dbg_syncblock, "cancelwait task(%s) failed. tk->block_ is not this!", tk->DebugInfo()); return; } if (tk->block_sequence_ != block_sequence) { DebugPrint(dbg_syncblock, "cancelwait task(%s) failed. tk->block_sequence_ = %u, block_sequence = %u.", tk->DebugInfo(), tk->block_sequence_, block_sequence); return; } if (!wait_queue_.erase(tk)) { DebugPrint(dbg_syncblock, "cancelwait task(%s) erase failed.", tk->DebugInfo()); return; } lock.unlock(); tk->block_ = nullptr; if (!in_timer && tk->block_timer_) { // block cancel timer必须在lock之外, 因为里面会lock g_Scheduler.BlockCancelTimer(tk->block_timer_); tk->block_timer_.reset(); } tk->is_block_timeout_ = true; DebugPrint(dbg_syncblock, "cancelwait task(%s).", tk->DebugInfo()); g_Scheduler.AddTaskRunnable(tk); } bool BlockObject::IsWakeup() { std::unique_lock<LFLock> lock(lock_); return wakeup_ > 0; } bool BlockObject::AddWaitTask(Task* tk) { std::unique_lock<LFLock> lock(lock_); if (wakeup_) { --wakeup_; return false; } wait_queue_.push(tk); DebugPrint(dbg_syncblock, "add wait task(%s). timeout=%ld", tk->DebugInfo(), (long int)std::chrono::duration_cast<std::chrono::milliseconds>(tk->block_timeout_).count()); // 带超时的, 增加定时器 if (MininumTimeDurationType::zero() != tk->block_timeout_) { uint32_t seq = tk->block_sequence_; tk->IncrementRef(); tk->block_timer_ = g_Scheduler.ExpireAt(tk->block_timeout_, [=]{ // 此定时器超过block_object生命期时会crash或死锁, // 所以wakeup或cancelwait时一定要kill此定时器 if (tk->block_sequence_ == seq) { DebugPrint(dbg_syncblock, "wait timeout, will cancelwait task(%s). this=%p, tk->block_=%p, seq=%u, timeout=%ld", tk->DebugInfo(), this, tk->block_, seq, (long int)std::chrono::duration_cast<std::chrono::milliseconds>(tk->block_timeout_).count()); this->CancelWait(tk, seq, true); } tk->DecrementRef(); }); } return true; } } //namespace co
#include "block_object.h" #include "scheduler.h" #include "error.h" #include <unistd.h> #include <mutex> #include <limits> namespace co { BlockObject::BlockObject(std::size_t init_wakeup, std::size_t max_wakeup) : wakeup_(init_wakeup), max_wakeup_(max_wakeup) { DebugPrint(dbg_syncblock, "BlockObject::BlockObject this=%p", this); } BlockObject::~BlockObject() { if (!lock_.try_lock()) { ThrowError(eCoErrorCode::ec_block_object_locked); } if (!wait_queue_.empty()) { ThrowError(eCoErrorCode::ec_block_object_waiting); } DebugPrint(dbg_syncblock, "BlockObject::~BlockObject this=%p", this); } void BlockObject::CoBlockWait() { if (!g_Scheduler.IsCoroutine()) { while (!TryBlockWait()) usleep(10 * 1000); return ; } std::unique_lock<LFLock> lock(lock_); if (wakeup_ > 0) { DebugPrint(dbg_syncblock, "wait immedaitely done."); --wakeup_; return ; } lock.unlock(); Task* tk = g_Scheduler.GetCurrentTask(); tk->block_ = this; tk->state_ = TaskState::sys_block; tk->block_timeout_ = MininumTimeDurationType::zero(); tk->is_block_timeout_ = false; ++ tk->block_sequence_; DebugPrint(dbg_syncblock, "wait to switch. task(%s)", tk->DebugInfo()); g_Scheduler.CoYield(); } bool BlockObject::CoBlockWaitTimed(MininumTimeDurationType timeo) { auto begin = std::chrono::high_resolution_clock::now(); if (!g_Scheduler.IsCoroutine()) { while (!TryBlockWait() && std::chrono::duration_cast<MininumTimeDurationType> (std::chrono::high_resolution_clock::now() - begin) < timeo) usleep(10 * 1000); return false; } std::unique_lock<LFLock> lock(lock_); if (wakeup_ > 0) { DebugPrint(dbg_syncblock, "wait immedaitely done."); --wakeup_; return true; } lock.unlock(); Task* tk = g_Scheduler.GetCurrentTask(); tk->block_ = this; tk->state_ = TaskState::sys_block; ++tk->block_sequence_; tk->block_timeout_ = timeo; tk->is_block_timeout_ = false; DebugPrint(dbg_syncblock, "wait to switch. task(%s)", tk->DebugInfo()); g_Scheduler.CoYield(); return !tk->is_block_timeout_; } bool BlockObject::TryBlockWait() { std::unique_lock<LFLock> lock(lock_); if (wakeup_ == 0) return false; --wakeup_; DebugPrint(dbg_syncblock, "try wait success."); return true; } bool BlockObject::Wakeup() { std::unique_lock<LFLock> lock(lock_); Task* tk = wait_queue_.pop(); if (!tk) { if (wakeup_ >= max_wakeup_) { DebugPrint(dbg_syncblock, "wakeup failed."); return false; } ++wakeup_; DebugPrint(dbg_syncblock, "wakeup to %lu.", (long unsigned)wakeup_); return true; } lock.unlock(); tk->block_ = nullptr; if (tk->block_timer_) { // block cancel timer必须在lock之外, 因为里面会lock if (g_Scheduler.BlockCancelTimer(tk->block_timer_)) tk->DecrementRef(); tk->block_timer_.reset(); } DebugPrint(dbg_syncblock, "wakeup task(%s).", tk->DebugInfo()); g_Scheduler.AddTaskRunnable(tk); return true; } void BlockObject::CancelWait(Task* tk, uint32_t block_sequence, bool in_timer) { std::unique_lock<LFLock> lock(lock_); if (tk->block_ != this) { DebugPrint(dbg_syncblock, "cancelwait task(%s) failed. tk->block_ is not this!", tk->DebugInfo()); return; } if (tk->block_sequence_ != block_sequence) { DebugPrint(dbg_syncblock, "cancelwait task(%s) failed. tk->block_sequence_ = %u, block_sequence = %u.", tk->DebugInfo(), tk->block_sequence_, block_sequence); return; } if (!wait_queue_.erase(tk)) { DebugPrint(dbg_syncblock, "cancelwait task(%s) erase failed.", tk->DebugInfo()); return; } lock.unlock(); tk->block_ = nullptr; if (!in_timer && tk->block_timer_) { // block cancel timer必须在lock之外, 因为里面会lock g_Scheduler.BlockCancelTimer(tk->block_timer_); tk->block_timer_.reset(); } tk->is_block_timeout_ = true; DebugPrint(dbg_syncblock, "cancelwait task(%s).", tk->DebugInfo()); g_Scheduler.AddTaskRunnable(tk); } bool BlockObject::IsWakeup() { std::unique_lock<LFLock> lock(lock_); return wakeup_ > 0; } bool BlockObject::AddWaitTask(Task* tk) { std::unique_lock<LFLock> lock(lock_); if (wakeup_) { --wakeup_; return false; } wait_queue_.push(tk); DebugPrint(dbg_syncblock, "add wait task(%s). timeout=%ld", tk->DebugInfo(), (long int)std::chrono::duration_cast<std::chrono::milliseconds>(tk->block_timeout_).count()); // 带超时的, 增加定时器 if (MininumTimeDurationType::zero() != tk->block_timeout_) { uint32_t seq = tk->block_sequence_; tk->IncrementRef(); tk->block_timer_ = g_Scheduler.ExpireAt(tk->block_timeout_, [=]{ // 此定时器超过block_object生命期时会crash或死锁, // 所以wakeup或cancelwait时一定要kill此定时器 if (tk->block_sequence_ == seq) { DebugPrint(dbg_syncblock, "wait timeout, will cancelwait task(%s). this=%p, tk->block_=%p, seq=%u, timeout=%ld", tk->DebugInfo(), this, tk->block_, seq, (long int)std::chrono::duration_cast<std::chrono::milliseconds>(tk->block_timeout_).count()); this->CancelWait(tk, seq, true); } tk->DecrementRef(); }); } return true; } } //namespace co
修复block_object导致Task引用计数会无法归0的bug
修复block_object导致Task引用计数会无法归0的bug
C++
mit
bpxeax/libgo,yyzybb537/libgo,yyzybb537/libgo,bpxeax/libgo,bpxeax/libgo,yyzybb537/libgo,yyzybb537/libgo
4dede000ed9c92b222ac90d7edc327f3062abab7
libredex/ClassUtil.cpp
libredex/ClassUtil.cpp
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ClassUtil.h" #include "DexAsm.h" #include "IRCode.h" #include "TypeUtil.h" namespace klass { Serdes get_serdes(const DexClass* cls) { std::string name = cls->get_name()->str(); name.pop_back(); std::string flatbuf_name = name; std::replace(flatbuf_name.begin(), flatbuf_name.end(), '$', '_'); std::string desername = name + "$Deserializer;"; DexType* deser = DexType::get_type(desername.c_str()); std::string flatbuf_desername = flatbuf_name + "Deserializer;"; DexType* flatbuf_deser = DexType::get_type(flatbuf_desername.c_str()); std::string sername = name + "$Serializer;"; DexType* ser = DexType::get_type(sername); std::string flatbuf_sername = flatbuf_name + "Serializer;"; DexType* flatbuf_ser = DexType::get_type(flatbuf_sername); return Serdes(deser, flatbuf_deser, ser, flatbuf_ser); } DexMethod* get_or_create_clinit(DexClass* cls) { using namespace dex_asm; DexMethod* clinit = cls->get_clinit(); if (clinit) { return clinit; } auto clinit_name = DexString::make_string("<clinit>"); auto clinit_proto = DexProto::make_proto(type::_void(), DexTypeList::make_type_list({})); // clinit does not exist, create one clinit = DexMethod::make_method(cls->get_type(), clinit_name, clinit_proto) ->make_concrete(ACC_PUBLIC | ACC_STATIC | ACC_CONSTRUCTOR, false); auto ir_code = std::make_unique<IRCode>(clinit, 1); ir_code->push_back(dasm(OPCODE_RETURN_VOID)); clinit->set_code(std::move(ir_code)); cls->add_method(clinit); return clinit; } bool has_hierarchy_in_scope(DexClass* cls) { DexType* super = nullptr; const DexClass* super_cls = cls; while (super_cls) { super = super_cls->get_super_class(); super_cls = type_class_internal(super); } return super == type::java_lang_Object(); } }; // namespace klass
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "ClassUtil.h" #include "DexAsm.h" #include "IRCode.h" #include "TypeUtil.h" namespace klass { Serdes get_serdes(const DexClass* cls) { std::string name = cls->get_name()->str(); name.pop_back(); std::string flatbuf_name = name; std::replace(flatbuf_name.begin(), flatbuf_name.end(), '$', '_'); std::string desername = name + "$Deserializer;"; DexType* deser = DexType::get_type(desername.c_str()); std::string flatbuf_desername = flatbuf_name + "Deserializer;"; DexType* flatbuf_deser = DexType::get_type(flatbuf_desername.c_str()); std::string sername = name + "$Serializer;"; DexType* ser = DexType::get_type(sername); std::string flatbuf_sername = flatbuf_name + "Serializer;"; DexType* flatbuf_ser = DexType::get_type(flatbuf_sername); return Serdes(deser, flatbuf_deser, ser, flatbuf_ser); } DexMethod* get_or_create_clinit(DexClass* cls) { using namespace dex_asm; DexMethod* clinit = cls->get_clinit(); if (clinit) { return clinit; } auto clinit_name = DexString::make_string("<clinit>"); auto clinit_proto = DexProto::make_proto(type::_void(), DexTypeList::make_type_list({})); // clinit does not exist, create one clinit = DexMethod::make_method(cls->get_type(), clinit_name, clinit_proto) ->make_concrete(ACC_PUBLIC | ACC_STATIC | ACC_CONSTRUCTOR, false); std::string cls_deobfuscated_name = cls->get_deobfuscated_name(); if (!cls_deobfuscated_name.empty()) { // Set deobfuscated name for the just created <clinit> if a deobfuscated // name is present for the class. clinit->set_deobfuscated_name(cls_deobfuscated_name + ".<clinit>:()V"); } auto ir_code = std::make_unique<IRCode>(clinit, 1); ir_code->push_back(dasm(OPCODE_RETURN_VOID)); clinit->set_code(std::move(ir_code)); cls->add_method(clinit); return clinit; } bool has_hierarchy_in_scope(DexClass* cls) { DexType* super = nullptr; const DexClass* super_cls = cls; while (super_cls) { super = super_cls->get_super_class(); super_cls = type_class_internal(super); } return super == type::java_lang_Object(); } }; // namespace klass
set deobfuscated name for clinits if such name is present for the class
set deobfuscated name for clinits if such name is present for the class Reviewed By: minjang Differential Revision: D22002141 fbshipit-source-id: 227e677165509e32228d2500d4a385bda3c3153e
C++
mit
facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex,facebook/redex
d4215de852cf06b879ad51803283c42746843302
kalarm/lib/colourcombo.cpp
kalarm/lib/colourcombo.cpp
/* * colourcombo.cpp - colour selection combo box * Program: kalarm * Copyright (c) 2001-2003,2005-2007 by David Jarvie <[email protected]> * * Some code taken from kdelibs/kdeui/kcolorcombo.cpp in the KDE libraries: * Copyright (C) 1997 Martin Jones ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <QMouseEvent> #include <QKeyEvent> #include <kdebug.h> #include "preferences.h" #include "colourcombo.moc" ColourCombo::ColourCombo(QWidget* parent, const QColor& defaultColour) : KColorCombo(parent), mReadOnly(false) { setColours(Preferences::messageColours()); kDebug()<<"prefcolours="<<Preferences::messageColours().count()<<endl; setColor(defaultColour); kDebug()<<"ColourCombo(): colours="<<colors().count()<<endl; Preferences::connect(SIGNAL(messageColoursChanged()), this, SLOT(slotPreferencesChanged())); } /****************************************************************************** * Set a new colour selection. */ void ColourCombo::setColours(const ColourList& colours) { kDebug()<<"setColours("<<colours.count()<<")"<<endl; setColors(colours.qcolorList()); } /****************************************************************************** * Called when the user changes the colour list in the preference settings. */ void ColourCombo::slotPreferencesChanged() { setColors(Preferences::messageColours().qcolorList()); } void ColourCombo::setReadOnly(bool ro) { mReadOnly = ro; } void ColourCombo::mousePressEvent(QMouseEvent* e) { if (mReadOnly) { // Swallow up the event if it's the left button if (e->button() == Qt::LeftButton) return; } KColorCombo::mousePressEvent(e); } void ColourCombo::mouseReleaseEvent(QMouseEvent* e) { if (!mReadOnly) KColorCombo::mouseReleaseEvent(e); } void ColourCombo::mouseMoveEvent(QMouseEvent* e) { if (!mReadOnly) KColorCombo::mouseMoveEvent(e); } void ColourCombo::keyPressEvent(QKeyEvent* e) { if (!mReadOnly || e->key() == Qt::Key_Escape) KColorCombo::keyPressEvent(e); } void ColourCombo::keyReleaseEvent(QKeyEvent* e) { if (!mReadOnly) KColorCombo::keyReleaseEvent(e); }
/* * colourcombo.cpp - colour selection combo box * Program: kalarm * Copyright (c) 2001-2003,2005-2007 by David Jarvie <[email protected]> * * Some code taken from kdelibs/kdeui/kcolorcombo.cpp in the KDE libraries: * Copyright (C) 1997 Martin Jones ([email protected]) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <QMouseEvent> #include <QKeyEvent> #include "preferences.h" #include "colourcombo.moc" ColourCombo::ColourCombo(QWidget* parent, const QColor& defaultColour) : KColorCombo(parent), mReadOnly(false) { setColours(Preferences::messageColours()); setColor(defaultColour); Preferences::connect(SIGNAL(messageColoursChanged()), this, SLOT(slotPreferencesChanged())); } /****************************************************************************** * Set a new colour selection. */ void ColourCombo::setColours(const ColourList& colours) { setColors(colours.qcolorList()); } /****************************************************************************** * Called when the user changes the colour list in the preference settings. */ void ColourCombo::slotPreferencesChanged() { setColors(Preferences::messageColours().qcolorList()); } void ColourCombo::setReadOnly(bool ro) { mReadOnly = ro; } void ColourCombo::mousePressEvent(QMouseEvent* e) { if (mReadOnly) { // Swallow up the event if it's the left button if (e->button() == Qt::LeftButton) return; } KColorCombo::mousePressEvent(e); } void ColourCombo::mouseReleaseEvent(QMouseEvent* e) { if (!mReadOnly) KColorCombo::mouseReleaseEvent(e); } void ColourCombo::mouseMoveEvent(QMouseEvent* e) { if (!mReadOnly) KColorCombo::mouseMoveEvent(e); } void ColourCombo::keyPressEvent(QKeyEvent* e) { if (!mReadOnly || e->key() == Qt::Key_Escape) KColorCombo::keyPressEvent(e); } void ColourCombo::keyReleaseEvent(QKeyEvent* e) { if (!mReadOnly) KColorCombo::keyReleaseEvent(e); }
Remove debug statements
Remove debug statements svn path=/trunk/KDE/kdepim/kalarm/lib/; revision=655881
C++
lgpl-2.1
lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi,lefou/kdepim-noakonadi
03ca1411333d3387416547316264c2f63cd810de
Vln-2016/consoleui.cpp
Vln-2016/consoleui.cpp
#include "consoleui.h" #include <iostream> #include <iomanip> using namespace std; consoleUI::consoleUI() { } consoleUI::consoleUI(int chooseNumber) { _chooseNumber = chooseNumber; } void consoleUI::run() { int chooseNumber = 0; cout << "---------------------------------------" << endl; cout << "------- Database for Scientist --------" << endl; cout << "1: Display entire list. *" << endl; cout << "2: Search by name. *" << endl; cout << "3: Search if alive. *" << endl; cout << "4: Sort by award year. *" << endl; cout << "5: Add new scientist. *" << endl; cout << "6: Search for birth year. *" << endl; cout << "7: Enter Function. *" << endl; cout << "8: Sort by birthyear. *" << endl; cout << "9: Search for Turing award winner. *" << endl; cout << "10: Chuck Norris. *" << endl; cout << "---------------------------------------" << endl; cout << "Enter number: "; cin >> chooseNumber; switch (chooseNumber) { case 1: { listServices scientists; cout << "***List of all scientists***" << endl; print(); printNames(scientists); } break; case 2: //Searching from first or last name { listServices scientists; //listServices searchName2; string searchTerm; cout << "Enter a single name to search: "; cin >> searchTerm; scientists.changeTo(_scientist.searchName(searchTerm)); print(); printNames(scientists); } break; case 3: //sortAlive { listServices scientists; string searchTerm; scientists.changeTo(_scientist.searchAlive()); cout << "An organized list starting with the oldest living scientist" << endl; print(); printNames(scientists); } break; case 4: //sortAward { listServices scientistsByAward; scientistsByAward.changeTo(_scientist.sortByAward()); cout << "An organized list of scientists in order of when they received the Turing award." << endl; print(); printNames(scientistsByAward); } break; case 5: { //addNew string firstName; string lastName; char gender; int birthYear; char isAlive; int deathYear; char isWinner; int awardYear; cout << "Please enter the scientist's first name: "; cin >> firstName; cout << "Please enter the scientist's last name: "; cin >> lastName; cout << "Enter the scientist's gender (m/f) : "; cin >> gender; cout << "Enter the scientist's birth year: "; cin >> birthYear; cout << "Is the scientist still alive? (y/n) "; cin >> isAlive; if(isAlive == 'n') { cout << "Enter the scientist's year of death: "; cin >> deathYear; } else if(isAlive == 'y') { deathYear = 0; } else { cout << "Invalid entry. Please enter either y (yes) or n (no)"; } cout << "Did the scientist win a Turing award? (y/n)"; cin >> isWinner; if(isWinner == 'y') { cout << "Enter the year the scientist won: "; cin >> awardYear; } else if(isWinner == 'n') { awardYear = 0; } else { cout << "Invalid entry. Please enter either y (yes) or n (no)"; } _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear); } break; case 6: //searchBirth { int year; cout << "Enter year: "; cin >> year; listServices scientistsBirth; scientistsBirth.changeTo(scientistsBirth.searchBirth(year)); cout << "A list of scientists born in your year of choice" << endl; print(); printNames(scientistsBirth); } break; case 8: //sortByBirth _scientist.changeTo(_scientist.sortByBirth()); cout << "An organized list starting with the oldest scientist" << endl; print(); printNames(_scientist); break; case 9: //sortByAward _scientist.changeTo(_scientist.sortByAward()); cout << "An organized list of scientists in order of when they received a Turing award." << endl; print(); printNames(_scientist); break; case 10: { listServices norris; /* for(int i = 0; i < _scientist.chuckNorris(); i++){ _scientist.chu }*/ norris.changeTo(_scientist.chuckNorris()); //print(); printNames(norris); break; } } } void consoleUI::print() { listServices scientists; cout.width(4); cout << left << "No."; cout.width(scientists.searchLongestName()); cout << "Firstname" << left; cout.width(10); cout << "Lastname" << left; cout.width(10); cout << "gender" << left; cout.width(10); cout << "D.O.B" << left; cout.width(10); cout << "D.O.D" << left; cout.width(scientists.searchLongestName()); cout << "Y.O.A." << left << endl; for(int i = 0 ; i < 9 ; i++) { cout << "--------"; } cout << endl; } void consoleUI::printNames (listServices scientistsToPrint) { int counter = 1; for(int i = 0; i < scientistsToPrint.getSize() ; i++) { string sex; string isDead; if(scientistsToPrint.getSexFromList(i) == 'm') { sex = "male"; } else { sex = "female"; } cout.width(5); cout << left << counter; counter++; cout.width(10); cout << scientistsToPrint.getFirstNameFromList(i) << left; cout.width(10); cout << scientistsToPrint.getLastNameFromList(i) << left; cout.width(10); cout << sex << left; cout.width(10); cout << scientistsToPrint.dobFromList(i) << left; if(scientistsToPrint.dodFromList(i) == 0) { isDead = "Alive"; cout.width(10); cout << isDead << left; } else { cout.width(10); cout << scientistsToPrint.dodFromList(i) << left; } cout.width(10); cout << scientistsToPrint.getAwardsFromList(i) << left;; cout << " *" << endl; } for(int i = 0 ; i < 9 ; i++) { cout << "--------"; } cout << endl; }
#include "consoleui.h" #include <iostream> #include <iomanip> using namespace std; consoleUI::consoleUI() { } consoleUI::consoleUI(int chooseNumber) { _chooseNumber = chooseNumber; } void consoleUI::run() { int chooseNumber = 0; cout << "-----------------------------------------------------------------" << endl; cout << "*------ Database for Scientist ----------*--------Glosary-------*" << endl; cout << "* 1: Display entire list. * D.O.D = date of death*" << endl; cout << "* 2: Search by name. * D.O.B = date of birth*" << endl; cout << "* 3: Search if alive. * Y.O.A = year of award*" << endl; cout << "* 4: Sort by award year. * *" << endl; cout << "* 5: Add new scientist. * *" << endl; cout << "* 6: Search for birth year. * *" << endl; cout << "* 7: Enter Function. * *" << endl; cout << "* 8: Sort by birthyear. * *" << endl; cout << "* 9: Search for Turing award winner. * *" << endl; cout << "* 10: Chuck Norris. * *" << endl; cout << "*----------------------------------------*----------------------*" << endl; cout << "-----------------------------------------------------------------" << endl; cout << "Enter number: "; cin >> chooseNumber; switch (chooseNumber) { case 1: { listServices scientists; cout << "***List of all scientists***" << endl; print(); printNames(scientists); } break; case 2: //Searching from first or last name { listServices scientists; //listServices searchName2; string searchTerm; cout << "Enter a single name to search: "; cin >> searchTerm; scientists.changeTo(_scientist.searchName(searchTerm)); print(); printNames(scientists); } break; case 3: //sortAlive { listServices scientists; string searchTerm; scientists.changeTo(_scientist.searchAlive()); cout << "An organized list starting with the oldest living scientist" << endl; print(); printNames(scientists); } break; case 4: //sortAward { listServices scientistsByAward; scientistsByAward.changeTo(_scientist.sortByAward()); cout << "An organized list of scientists in order of when they received the Turing award." << endl; print(); printNames(scientistsByAward); } break; case 5: { //addNew string firstName; string lastName; char gender; int birthYear; char isAlive; int deathYear; char isWinner; int awardYear; cout << "Please enter the scientist's first name: "; cin >> firstName; cout << "Please enter the scientist's last name: "; cin >> lastName; cout << "Enter the scientist's gender (m/f) : "; cin >> gender; cout << "Enter the scientist's birth year: "; cin >> birthYear; cout << "Is the scientist still alive? (y/n) "; cin >> isAlive; if(isAlive == 'n') { cout << "Enter the scientist's year of death: "; cin >> deathYear; } else if(isAlive == 'y') { deathYear = 0; } else { cout << "Invalid entry. Please enter either y (yes) or n (no)"; } cout << "Did the scientist win a Turing award? (y/n)"; cin >> isWinner; if(isWinner == 'y') { cout << "Enter the year the scientist won: "; cin >> awardYear; } else if(isWinner == 'n') { awardYear = 0; } else { cout << "Invalid entry. Please enter either y (yes) or n (no)"; } _scientist.addNew(firstName, lastName, gender, birthYear, deathYear, awardYear); } break; case 6: //searchBirth { int year; cout << "Enter year: "; cin >> year; listServices scientistsBirth; scientistsBirth.changeTo(scientistsBirth.searchBirth(year)); cout << "A list of scientists born in your year of choice" << endl; print(); printNames(scientistsBirth); } break; case 8: //sortByBirth _scientist.changeTo(_scientist.sortByBirth()); cout << "An organized list starting with the oldest scientist" << endl; print(); printNames(_scientist); break; case 9: //sortByAward _scientist.changeTo(_scientist.sortByAward()); cout << "An organized list of scientists in order of when they received a Turing award." << endl; print(); printNames(_scientist); break; case 10: { listServices norris; /* for(int i = 0; i < _scientist.chuckNorris(); i++){ _scientist.chu }*/ norris.changeTo(_scientist.chuckNorris()); //print(); printNames(norris); break; } } } void consoleUI::print() { listServices scientists; cout.width(4); cout << left << "No."; cout.width(scientists.searchLongestName()); cout << "Firstname" << left; cout.width(10); cout << "Lastname" << left; cout.width(10); cout << "gender" << left; cout.width(10); cout << "D.O.B" << left; cout.width(10); cout << "D.O.D" << left; cout.width(scientists.searchLongestName()); cout << "Y.O.A." << left << endl; for(int i = 0 ; i < 9 ; i++) { cout << "--------"; } cout << endl; } void consoleUI::printNames (listServices scientistsToPrint) { int counter = 1; for(int i = 0; i < scientistsToPrint.getSize() ; i++) { string sex; string isDead; if(scientistsToPrint.getSexFromList(i) == 'm') { sex = "male"; } else { sex = "female"; } cout.width(5); cout << left << counter; counter++; cout.width(10); cout << scientistsToPrint.getFirstNameFromList(i) << left; cout.width(10); cout << scientistsToPrint.getLastNameFromList(i) << left; cout.width(10); cout << sex << left; cout.width(10); cout << scientistsToPrint.dobFromList(i) << left; if(scientistsToPrint.dodFromList(i) == 0) { isDead = "Alive"; cout.width(10); cout << isDead << left; } else { cout.width(10); cout << scientistsToPrint.dodFromList(i) << left; } cout.width(10); cout << scientistsToPrint.getAwardsFromList(i) << left;; cout << " *" << endl; } for(int i = 0 ; i < 9 ; i++) { cout << "--------"; } cout << endl; }
delete search and gui
delete search and gui
C++
mit
ivark16/Vln-2016,ivark16/Vln-2016
af9404e3db3d536f20ad194a75ffb3abbc336454
Workloads/tracking.cpp
Workloads/tracking.cpp
/***************************************************************** ****************************************************************** * * Copyright (C) 2017 Trinity Robotics Research Group. * * * FILENAME: haar.cpp * * * DESCRIPTION: program to detect faces. * * * DATE: 12/03/2017 * * * AUTHOR: Andrew Murtagh, * Trinity Robotics Research Group, Trinity College Dublin. * * * NOTES: -uses Viola-Jones algorithm to detect faces. * -has opencv3.2.0 as a required dependency. * -images taken from ImageNet. * -uses haarcascade_frontalface_alt.xml as detector. * -metric is frame rate [Hz] * * * VERSION: v1 * * ******************************************************************* ******************************************************************/ #include <iostream> #include <stdio.h> #include <string.h> #include <time.h> #include <iomanip> #include <opencv2/opencv.hpp> #include "opencv2/video/tracking.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "botmark.h" #define NUMFRAMES 38 #define REDTHRESHOLD 217 #define GREENTHRESHOLD 191 #define BLUETHRESHOLD 204 using namespace std; using namespace cv; struct timespec starttime, endtime; double time_accumulator = 0.0f; void proessFrame(Mat frame); int main(int argc, const char** argv) { Mat frame; for(int i=0; i<NUMFRAMES; i++) { // start timer if(!DEBUG) { clock_gettime(CLOCK_MONOTONIC_RAW, &starttime); } if(DEBUG) { printf("Processing image: %i \n", i+1); } std::stringstream ss; ss << std::setw(4) << std::setfill('0') << i; std::string s = ss.str(); s = "../Data/object_tracking_images/" + s + ".png"; frame = imread(s); if(!frame.empty()) { proessFrame(frame); } else { printf("Error: no frame detected\n"); break; } // stop timer if(!DEBUG) { clock_gettime(CLOCK_MONOTONIC_RAW, &endtime); double microseconds = (endtime.tv_sec - starttime.tv_sec) * 1000000 + (endtime.tv_nsec - starttime.tv_nsec) / 1000; double ms = microseconds/1000; time_accumulator += ms; } } if(!DEBUG) { printf ("Total time in milliseconds: %f \n", time_accumulator); double mean = time_accumulator/NUMFRAMES; printf ("Mean time per frame: %f \n", mean); float framerate = NUMFRAMES/(time_accumulator/1000.0f); printf ("Mean frame rate: %f \n", framerate); } return 0; } void proessFrame( Mat frame ) { Mat colour_planes[3]; //OpenCV uses BGR color order Mat redbinary, greenbinary, bluebinary; split(frame, colour_planes); int rows = frame.rows; int cols = frame.cols; threshold(colour_planes[2], redbinary, REDTHRESHOLD, 255, 0); threshold(colour_planes[1], greenbinary, GREENTHRESHOLD, 1, 0); threshold(colour_planes[0], bluebinary, BLUETHRESHOLD, 1, 0); Mat combinedBinary = Mat::zeros(rows, cols, CV_8U); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { int thisvalue = (int)redbinary.at<uchar>(i, j) || (int)greenbinary.at<uchar>(i, j) || (int)bluebinary.at<uchar>(i, j); combinedBinary.at<uchar>(i, j) = thisvalue*1; } } Mat blurredImage; medianBlur(combinedBinary, blurredImage, 9); int blobarea = 0; int sumi = 0; int sumj = 0; for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { int thisvalue = (int)blurredImage.at<uchar>(i, j); blobarea += thisvalue; sumi += i*thisvalue; sumj += j*thisvalue; } } int centroidi = sumi/blobarea; int centroidj = sumj/blobarea; circle(frame, Point(centroidj, centroidi), 6, CV_RGB(0,0,255), 1, 8, 0); if(DEBUG) { imshow("Display window", frame); waitKey(0); } }
/***************************************************************** ****************************************************************** * * Copyright (C) 2017 Trinity Robotics Research Group. * * * FILENAME: tracking.cpp * * * DESCRIPTION: program to track object. * * * DATE: 25/03/2017 * * * AUTHOR: Andrew Murtagh, * Trinity Robotics Research Group, Trinity College Dublin. * * * NOTES: -splits rgb into each plane, applies threshold on each, * -applies bitwise OR, median blur, image moments, blob centroid. * -has opencv3.2.0 as a required dependency. * -images taken from camear phone * -metric is frame rate [Hz] * * * VERSION: v1 * * ******************************************************************* ******************************************************************/ #include <iostream> #include <stdio.h> #include <string.h> #include <time.h> #include <iomanip> #include <opencv2/opencv.hpp> #include "opencv2/video/tracking.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/features2d/features2d.hpp" #include "opencv2/calib3d/calib3d.hpp" #include "botmark.h" #define NUMFRAMES 38 #define REDTHRESHOLD 217 #define GREENTHRESHOLD 191 #define BLUETHRESHOLD 204 using namespace std; using namespace cv; struct timespec starttime, endtime; double time_accumulator = 0.0f; void proessFrame(Mat frame); int main(int argc, const char** argv) { Mat frame; for(int i=0; i<NUMFRAMES; i++) { // start timer if(!DEBUG) { clock_gettime(CLOCK_MONOTONIC_RAW, &starttime); } if(DEBUG) { printf("Processing image: %i \n", i+1); } std::stringstream ss; ss << std::setw(4) << std::setfill('0') << i; std::string s = ss.str(); s = "../Data/object_tracking_images/" + s + ".png"; frame = imread(s); if(!frame.empty()) { proessFrame(frame); } else { printf("Error: no frame detected\n"); break; } // stop timer if(!DEBUG) { clock_gettime(CLOCK_MONOTONIC_RAW, &endtime); double microseconds = (endtime.tv_sec - starttime.tv_sec) * 1000000 + (endtime.tv_nsec - starttime.tv_nsec) / 1000; double ms = microseconds/1000; time_accumulator += ms; } } if(!DEBUG) { printf ("Total time in milliseconds: %f \n", time_accumulator); double mean = time_accumulator/NUMFRAMES; printf ("Mean time per frame: %f \n", mean); float framerate = NUMFRAMES/(time_accumulator/1000.0f); printf ("Mean frame rate: %f \n", framerate); } return 0; } void proessFrame( Mat frame ) { Mat colour_planes[3]; //OpenCV uses BGR color order Mat redbinary, greenbinary, bluebinary; split(frame, colour_planes); int rows = frame.rows; int cols = frame.cols; threshold(colour_planes[2], redbinary, REDTHRESHOLD, 255, 0); threshold(colour_planes[1], greenbinary, GREENTHRESHOLD, 1, 0); threshold(colour_planes[0], bluebinary, BLUETHRESHOLD, 1, 0); Mat combinedBinary = Mat::zeros(rows, cols, CV_8U); for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { int thisvalue = (int)redbinary.at<uchar>(i, j) || (int)greenbinary.at<uchar>(i, j) || (int)bluebinary.at<uchar>(i, j); combinedBinary.at<uchar>(i, j) = thisvalue*1; } } Mat blurredImage; medianBlur(combinedBinary, blurredImage, 9); int blobarea = 0; int sumi = 0; int sumj = 0; for(int i=0; i<rows; i++) { for(int j=0; j<cols; j++) { int thisvalue = (int)blurredImage.at<uchar>(i, j); blobarea += thisvalue; sumi += i*thisvalue; sumj += j*thisvalue; } } int centroidi = sumi/blobarea; int centroidj = sumj/blobarea; circle(frame, Point(centroidj, centroidi), 6, CV_RGB(0,0,255), 1, 8, 0); if(DEBUG) { imshow("Display window", frame); waitKey(0); } }
Update tracking.cpp
Update tracking.cpp
C++
mit
AndrewMurtagh/Botmark,AndrewMurtagh/Botmark,AndrewMurtagh/Botmark
87b81d7056f7a40fcd12a7a4a4fd17f4330bdacd
loader/ptrace_base.cpp
loader/ptrace_base.cpp
/* * nt loader * * Copyright 2006-2008 Mike McCormack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/time.h> #include <assert.h> #include <sys/wait.h> #include <sched.h> #include <sys/ptrace.h> #ifdef HAVE_ASM_PTRACE_H #include <asm/ptrace.h> #endif #include "windef.h" #include "winnt.h" #include "mem.h" #include "thread.h" #include "ptrace_if.h" #include "debug.h" #include "platform.h" #include "ptrace_base.h" #define CTX_HAS_CONTROL(flags) ((flags)&1) #define CTX_HAS_INTEGER(flags) ((flags)&2) #define CTX_HAS_SEGMENTS(flags) ((flags)&4) #define CTX_HAS_FLOAT(flags) ((flags)&8) #define CTX_HAS_DEBUG(flags) ((flags)&0x10) #define CTX_HAS_INTEGER_CONTROL_OR_SEGMENTS(flags) ((flags)&7) int ptrace_address_space_impl::set_context( PCONTEXT ctx ) { long regs[FRAME_SIZE]; memset( regs, 0, sizeof regs ); regs[EBX] = ctx->Ebx; regs[ECX] = ctx->Ecx; regs[EDX] = ctx->Edx; regs[ESI] = ctx->Esi; regs[EDI] = ctx->Edi; regs[EAX] = ctx->Eax; regs[DS] = ctx->SegDs; regs[ES] = ctx->SegEs; regs[FS] = ctx->SegFs; regs[GS] = ctx->SegGs; regs[SS] = ctx->SegSs; regs[CS] = ctx->SegCs; regs[SS] = ctx->SegSs; regs[UESP] = ctx->Esp; regs[EIP] = ctx->Eip; regs[EBP] = ctx->Ebp; regs[EFL] = ctx->EFlags; // hack - ignore the data and code segments passed from userspace // ntdll uses values that disagree with what Linux supports regs[DS] = get_userspace_data_seg(); regs[ES] = get_userspace_data_seg(); regs[SS] = get_userspace_data_seg(); regs[SS] = get_userspace_data_seg(); regs[CS] = get_userspace_code_seg(); return ptrace_set_regs( get_child_pid(), regs ); } int ptrace_address_space_impl::get_context( PCONTEXT ctx ) { long regs[FRAME_SIZE]; int r; memset( ctx, 0, sizeof *ctx ); r = ptrace_get_regs( get_child_pid(), regs ); if (r < 0) return r; ctx->ContextFlags = CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_CONTROL; // CONTEXT_INTEGER ctx->Ebx = regs[EBX]; ctx->Ecx = regs[ECX]; ctx->Edx = regs[EDX]; ctx->Esi = regs[ESI]; ctx->Edi = regs[EDI]; ctx->Eax = regs[EAX]; // CONTEXT_SEGMENTS ctx->SegDs = regs[DS]; ctx->SegEs = regs[ES]; ctx->SegFs = regs[FS]; ctx->SegGs = regs[GS]; // CONTEXT_CONTROL ctx->SegSs = regs[SS]; ctx->Esp = regs[UESP]; ctx->SegCs = regs[CS]; ctx->Eip = regs[EIP]; ctx->Ebp = regs[EBP]; ctx->EFlags = regs[EFL]; #if 0 if (CTX_HAS_FLOAT(flags)) { struct user_i387_struct fpregs; r = ptrace_get_fpregs( get_child_pid(), &fpregs ); if (r < 0) return r; ctx->ContextFlags |= CONTEXT_FLOATING_POINT; ctx->FloatSave.ControlWord = fpregs.cwd; ctx->FloatSave.StatusWord = fpregs.swd; ctx->FloatSave.TagWord = fpregs.twd; //FloatSave. = fpregs.fip; //FloatSave. = fpregs.fcs; //FloatSave. = fpregs.foo; //FloatSave. = fpregs.fos; //FloatSave. = fpregs.fip; assert( sizeof fpregs.st_space == sizeof ctx->FloatSave.RegisterArea ); memcpy( ctx->FloatSave.RegisterArea, fpregs.st_space, sizeof fpregs.st_space ); //ErrorOffset; //ErrorSelector; //DataOffset; //DataSelector; //Cr0NpxState; dprintf("not complete\n"); } if (flags & ~CONTEXT86_FULL) die( "invalid context flags\n"); #endif return 0; } void ptrace_address_space_impl::wait_for_signal( pid_t pid, int signal ) { while (1) { int r, status = 0; r = wait4( pid, &status, WUNTRACED, NULL ); if (r < 0) { if (errno == EINTR) continue; die("wait_for_signal: wait4() failed %d\n", errno); } if (r != pid) continue; if (WIFEXITED(status) ) die("Client died\n"); if (WIFSTOPPED(status) && WEXITSTATUS(status) == signal) return; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGALRM) dprintf("stray SIGALRM\n"); else dprintf("stray signal %d\n", WEXITSTATUS(status)); // start the child again so we can get the next signal r = ptrace( PTRACE_CONT, pid, 0, 0 ); if (r < 0) die("PTRACE_CONT failed %d\n", errno); } } int ptrace_address_space_impl::ptrace_run( PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout ) { int r, status = 0; // set itimer (SIGALRM) alarm_timeout( timeout ); sig_target = this; /* set the current thread's context */ r = set_context( ctx ); if (r<0) die("set_thread_context failed\n"); /* run it */ r = ptrace( single_step ? PTRACE_SINGLESTEP : PTRACE_CONT, get_child_pid(), 0, 0 ); if (r<0) die("PTRACE_CONT failed (%d)\n", errno); /* wait until it needs our attention */ while (1) { r = wait4( get_child_pid(), &status, WUNTRACED, NULL ); if (r == -1 && errno == EINTR) continue; if (r < 0) die("wait4 failed (%d)\n", errno); if (r != get_child_pid()) continue; break; } r = get_context( ctx ); if (r < 0) die("failed to get registers\n"); // cancel itimer (SIGALRM) cancel_timer(); sig_target = 0; return status; } void ptrace_address_space_impl::alarm_timeout(LARGE_INTEGER &timeout) { /* set the timeout */ struct itimerval val; val.it_value.tv_sec = timeout.QuadPart/1000LL; val.it_value.tv_usec = (timeout.QuadPart%1000LL)*1000LL; val.it_interval.tv_sec = 0; val.it_interval.tv_usec = 0; int r = setitimer(ITIMER_REAL, &val, NULL); if (r < 0) die("couldn't set itimer\n"); } void ptrace_address_space_impl::cancel_timer() { int r = setitimer(ITIMER_REAL, NULL, NULL); if (r < 0) die("couldn't cancel itimer\n"); } ptrace_address_space_impl* ptrace_address_space_impl::sig_target; void ptrace_address_space_impl::sigitimer_handler(int signal) { if (sig_target) sig_target->handle( signal ); } void ptrace_address_space_impl::handle( int signal ) { //dprintf("signal %d\n", signal); pid_t pid = get_child_pid(); assert( pid != -1); #ifdef HAVE_SIGQUEUE sigval val; val.sival_int = 0; sigqueue(pid, SIGALRM, val); #else kill(pid, SIGALRM); #endif } void ptrace_address_space_impl::set_signals() { struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_handler = ptrace_address_space_impl::sigitimer_handler; sigemptyset(&sa.sa_mask); if (0 > sigaction(SIGALRM, &sa, NULL)) die("unable to set action for SIGALRM\n"); // turn the signal on sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGALRM); if (0 > sigprocmask(SIG_UNBLOCK, &sigset, NULL)) die("unable to unblock SIGALRM\n"); } void ptrace_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec ) { set_userspace_fs(TebBaseAddress, ctx->SegFs); while (1) { int status = ptrace_run( ctx, single_step, timeout ); if (WIFSIGNALED(status)) break; if (WIFEXITED(status)) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSEGV) { exec->handle_fault(); break; } if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSTOP) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGCONT) { dprintf("got SIGCONT\n"); continue; } if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGALRM) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGWINCH) break; if (WIFSTOPPED(status) && single_step) break; if (WIFSTOPPED(status)) { exec->handle_breakpoint(); break; } } } int ptrace_address_space_impl::get_fault_info( void *& addr ) { siginfo_t info; memset( &info, 0, sizeof info ); int r = ptrace_get_signal_info( get_child_pid(), &info ); addr = info.si_addr; return r; } unsigned short ptrace_address_space_impl::get_userspace_code_seg() { unsigned short cs; __asm__ __volatile__ ( "\n\tmovw %%cs, %0\n" : "=r"( cs ) : ); return cs; } unsigned short ptrace_address_space_impl::get_userspace_data_seg() { unsigned short cs; __asm__ __volatile__ ( "\n\tmovw %%ds, %0\n" : "=r"( cs ) : ); return cs; } void ptrace_address_space_impl::init_context( CONTEXT& ctx ) { memset( &ctx, 0, sizeof ctx ); ctx.SegFs = get_userspace_fs(); ctx.SegDs = get_userspace_data_seg(); ctx.SegEs = get_userspace_data_seg(); ctx.SegSs = get_userspace_data_seg(); ctx.SegCs = get_userspace_code_seg(); ctx.EFlags = 0x00000296; } int ptrace_address_space_impl::set_userspace_fs(void *TebBaseAddress, ULONG fs) { struct user_desc ldt; int r; memset( &ldt, 0, sizeof ldt ); ldt.entry_number = (fs >> 3); ldt.base_addr = (unsigned long) TebBaseAddress; ldt.limit = 0xfff; ldt.seg_32bit = 1; r = ptrace_set_thread_area( get_child_pid(), &ldt ); if (r<0) die("set %%fs failed, fs = %ld errno = %d child = %d\n", fs, errno, get_child_pid()); return r; }
/* * nt loader * * Copyright 2006-2008 Mike McCormack * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA */ #include "config.h" #include <unistd.h> #include <fcntl.h> #include <errno.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mman.h> #include <sys/time.h> #include <assert.h> #include <sys/wait.h> #include <sched.h> #include <sys/ptrace.h> #ifdef HAVE_ASM_PTRACE_H #include <asm/ptrace.h> #endif #include "windef.h" #include "winnt.h" #include "mem.h" #include "thread.h" #include "ptrace_if.h" #include "debug.h" #include "platform.h" #include "ptrace_base.h" #define CTX_HAS_CONTROL(flags) ((flags)&1) #define CTX_HAS_INTEGER(flags) ((flags)&2) #define CTX_HAS_SEGMENTS(flags) ((flags)&4) #define CTX_HAS_FLOAT(flags) ((flags)&8) #define CTX_HAS_DEBUG(flags) ((flags)&0x10) #define CTX_HAS_INTEGER_CONTROL_OR_SEGMENTS(flags) ((flags)&7) int ptrace_address_space_impl::set_context( PCONTEXT ctx ) { long regs[FRAME_SIZE]; memset( regs, 0, sizeof regs ); regs[EBX] = ctx->Ebx; regs[ECX] = ctx->Ecx; regs[EDX] = ctx->Edx; regs[ESI] = ctx->Esi; regs[EDI] = ctx->Edi; regs[EAX] = ctx->Eax; regs[DS] = ctx->SegDs; regs[ES] = ctx->SegEs; regs[FS] = ctx->SegFs; regs[GS] = ctx->SegGs; regs[SS] = ctx->SegSs; regs[CS] = ctx->SegCs; regs[SS] = ctx->SegSs; regs[UESP] = ctx->Esp; regs[EIP] = ctx->Eip; regs[EBP] = ctx->Ebp; regs[EFL] = ctx->EFlags; // hack - ignore the data and code segments passed from userspace // ntdll uses values that disagree with what Linux supports regs[DS] = get_userspace_data_seg(); regs[ES] = get_userspace_data_seg(); regs[SS] = get_userspace_data_seg(); regs[SS] = get_userspace_data_seg(); regs[CS] = get_userspace_code_seg(); return ptrace_set_regs( get_child_pid(), regs ); } int ptrace_address_space_impl::get_context( PCONTEXT ctx ) { long regs[FRAME_SIZE]; int r; memset( ctx, 0, sizeof *ctx ); r = ptrace_get_regs( get_child_pid(), regs ); if (r < 0) return r; ctx->ContextFlags = CONTEXT_INTEGER | CONTEXT_SEGMENTS | CONTEXT_CONTROL; // CONTEXT_INTEGER ctx->Ebx = regs[EBX]; ctx->Ecx = regs[ECX]; ctx->Edx = regs[EDX]; ctx->Esi = regs[ESI]; ctx->Edi = regs[EDI]; ctx->Eax = regs[EAX]; // CONTEXT_SEGMENTS ctx->SegDs = regs[DS]; ctx->SegEs = regs[ES]; ctx->SegFs = regs[FS]; ctx->SegGs = regs[GS]; // CONTEXT_CONTROL ctx->SegSs = regs[SS]; ctx->Esp = regs[UESP]; ctx->SegCs = regs[CS]; ctx->Eip = regs[EIP]; ctx->Ebp = regs[EBP]; ctx->EFlags = regs[EFL]; #if 0 if (CTX_HAS_FLOAT(flags)) { struct user_i387_struct fpregs; r = ptrace_get_fpregs( get_child_pid(), &fpregs ); if (r < 0) return r; ctx->ContextFlags |= CONTEXT_FLOATING_POINT; ctx->FloatSave.ControlWord = fpregs.cwd; ctx->FloatSave.StatusWord = fpregs.swd; ctx->FloatSave.TagWord = fpregs.twd; //FloatSave. = fpregs.fip; //FloatSave. = fpregs.fcs; //FloatSave. = fpregs.foo; //FloatSave. = fpregs.fos; //FloatSave. = fpregs.fip; assert( sizeof fpregs.st_space == sizeof ctx->FloatSave.RegisterArea ); memcpy( ctx->FloatSave.RegisterArea, fpregs.st_space, sizeof fpregs.st_space ); //ErrorOffset; //ErrorSelector; //DataOffset; //DataSelector; //Cr0NpxState; dprintf("not complete\n"); } if (flags & ~CONTEXT86_FULL) die( "invalid context flags\n"); #endif return 0; } void ptrace_address_space_impl::wait_for_signal( pid_t pid, int signal ) { while (1) { int r, status = 0; r = wait4( pid, &status, WUNTRACED, NULL ); if (r < 0) { if (errno == EINTR) continue; die("wait_for_signal: wait4() failed %d\n", errno); } if (r != pid) continue; if (WIFEXITED(status) ) die("Client died\n"); if (WIFSTOPPED(status) && WEXITSTATUS(status) == signal) return; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGALRM) dprintf("stray SIGALRM\n"); else dprintf("stray signal %d\n", WEXITSTATUS(status)); // start the child again so we can get the next signal r = ptrace( PTRACE_CONT, pid, 0, 0 ); if (r < 0) die("PTRACE_CONT failed %d\n", errno); } } int ptrace_address_space_impl::ptrace_run( PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout ) { int r, status = 0; // set itimer (SIGALRM) sig_target = this; alarm_timeout( timeout ); /* set the current thread's context */ r = set_context( ctx ); if (r<0) die("set_thread_context failed\n"); /* run it */ r = ptrace( single_step ? PTRACE_SINGLESTEP : PTRACE_CONT, get_child_pid(), 0, 0 ); if (r<0) die("PTRACE_CONT failed (%d)\n", errno); /* wait until it needs our attention */ while (1) { r = wait4( get_child_pid(), &status, WUNTRACED, NULL ); if (r == -1 && errno == EINTR) continue; if (r < 0) die("wait4 failed (%d)\n", errno); if (r != get_child_pid()) continue; break; } r = get_context( ctx ); if (r < 0) die("failed to get registers\n"); // cancel itimer (SIGALRM) cancel_timer(); sig_target = 0; return status; } void ptrace_address_space_impl::alarm_timeout(LARGE_INTEGER &timeout) { /* set the timeout */ struct itimerval val; val.it_value.tv_sec = timeout.QuadPart/1000LL; val.it_value.tv_usec = (timeout.QuadPart%1000LL)*1000LL; val.it_interval.tv_sec = 0; val.it_interval.tv_usec = 0; int r = setitimer(ITIMER_REAL, &val, NULL); if (r < 0) die("couldn't set itimer\n"); } void ptrace_address_space_impl::cancel_timer() { int r = setitimer(ITIMER_REAL, NULL, NULL); if (r < 0) die("couldn't cancel itimer\n"); } ptrace_address_space_impl* ptrace_address_space_impl::sig_target; void ptrace_address_space_impl::sigitimer_handler(int signal) { if (sig_target) sig_target->handle( signal ); } void ptrace_address_space_impl::handle( int signal ) { //dprintf("signal %d\n", signal); pid_t pid = get_child_pid(); assert( pid != -1); #ifdef HAVE_SIGQUEUE sigval val; val.sival_int = 0; sigqueue(pid, SIGALRM, val); #else kill(pid, SIGALRM); #endif } void ptrace_address_space_impl::set_signals() { struct sigaction sa; memset(&sa, 0, sizeof sa); sa.sa_handler = ptrace_address_space_impl::sigitimer_handler; sigemptyset(&sa.sa_mask); if (0 > sigaction(SIGALRM, &sa, NULL)) die("unable to set action for SIGALRM\n"); // turn the signal on sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGALRM); if (0 > sigprocmask(SIG_UNBLOCK, &sigset, NULL)) die("unable to unblock SIGALRM\n"); } void ptrace_address_space_impl::run( void *TebBaseAddress, PCONTEXT ctx, int single_step, LARGE_INTEGER& timeout, execution_context_t *exec ) { set_userspace_fs(TebBaseAddress, ctx->SegFs); while (1) { int status = ptrace_run( ctx, single_step, timeout ); if (WIFSIGNALED(status)) break; if (WIFEXITED(status)) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSEGV) { exec->handle_fault(); break; } if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGSTOP) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGCONT) { dprintf("got SIGCONT\n"); continue; } if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGALRM) break; if (WIFSTOPPED(status) && WEXITSTATUS(status) == SIGWINCH) break; if (WIFSTOPPED(status) && single_step) break; if (WIFSTOPPED(status)) { exec->handle_breakpoint(); break; } } } int ptrace_address_space_impl::get_fault_info( void *& addr ) { siginfo_t info; memset( &info, 0, sizeof info ); int r = ptrace_get_signal_info( get_child_pid(), &info ); addr = info.si_addr; return r; } unsigned short ptrace_address_space_impl::get_userspace_code_seg() { unsigned short cs; __asm__ __volatile__ ( "\n\tmovw %%cs, %0\n" : "=r"( cs ) : ); return cs; } unsigned short ptrace_address_space_impl::get_userspace_data_seg() { unsigned short cs; __asm__ __volatile__ ( "\n\tmovw %%ds, %0\n" : "=r"( cs ) : ); return cs; } void ptrace_address_space_impl::init_context( CONTEXT& ctx ) { memset( &ctx, 0, sizeof ctx ); ctx.SegFs = get_userspace_fs(); ctx.SegDs = get_userspace_data_seg(); ctx.SegEs = get_userspace_data_seg(); ctx.SegSs = get_userspace_data_seg(); ctx.SegCs = get_userspace_code_seg(); ctx.EFlags = 0x00000296; } int ptrace_address_space_impl::set_userspace_fs(void *TebBaseAddress, ULONG fs) { struct user_desc ldt; int r; memset( &ldt, 0, sizeof ldt ); ldt.entry_number = (fs >> 3); ldt.base_addr = (unsigned long) TebBaseAddress; ldt.limit = 0xfff; ldt.seg_32bit = 1; r = ptrace_set_thread_area( get_child_pid(), &ldt ); if (r<0) die("set %%fs failed, fs = %ld errno = %d child = %d\n", fs, errno, get_child_pid()); return r; }
Fix a race condition
Fix a race condition
C++
lgpl-2.1
bragin/ring3k,mikemccormack/ring3k,mikemccormack/ring3k,bragin/ring3k,mikemccormack/ring3k,bragin/ring3k,bragin/ring3k
b028f3c6ced73ada47e0fc156650a3dec0b0498b
Cloud.cpp
Cloud.cpp
/*===- Cloud.cpp - libSimulation -============================================== * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #include "Cloud.h" #include <cmath> #include <iostream> #include <sstream> using namespace std; Cloud::Cloud(unsigned int numPar, double sizeOfCloud) : n(numPar), cloudSize(sizeOfCloud), k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]), l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]), m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]), n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]), x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]), charge(new double[n]), mass(new double[n]), forceX(new double[n]), forceY(new double[n]) {} Cloud::~Cloud() { delete[] k1; delete[] k2; delete[] k3; delete[] k4; delete[] l1; delete[] l2; delete[] l3; delete[] l4; delete[] m1; delete[] m2; delete[] m3; delete[] m4; delete[] n1; delete[] n2; delete[] n3; delete[] n4; delete[] x; delete[] y; delete[] Vx; delete[] Vy; delete[] charge; delete[] mass; delete[] forceX; delete[] forceY; } inline void Cloud::setPosition(const unsigned int index) { double radius = ((double)rand()/(double)RAND_MAX)*cloudSize; double theta = ((double)rand()/(double)RAND_MAX)*2.0*M_PI; x[index] = radius*cos(theta); y[index] = radius*sin(theta); } inline void Cloud::setPosition(const unsigned int index, const double xVal, const double yVal) { x[index] = xVal; y[index] = yVal; } inline void Cloud::setVelocity(const unsigned int index) { Vx[index] = 0.0; Vy[index] = 0.0; } inline void Cloud::setCharge(const unsigned int index) { charge[index] = (rand()%201 + 5900)*1.6E-19; } inline void Cloud::setMass(const unsigned int index) { const double radius = 1.45E-6; const double particleDensity = 2200.0; mass[index] = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity; } Cloud * const Cloud::initializeNew(const unsigned int numParticles, const double cloudSize) { cout << "\nGenerating original data.\n\n"; Cloud * const cloud = new Cloud(numParticles, cloudSize); //seed rand function with time(NULL): srand((int)time(NULL)); //initialize dust cloud: for(unsigned int i = 0; i < numParticles; i++) { cloud->setPosition(i); cloud->setVelocity(i); cloud->setCharge(i); cloud->setMass(i); } return cloud; } Cloud * const Cloud::initializeGrid(const unsigned int numParticles, const double cloudSize) { cout << "\nInitializing grid.\n\n"; Cloud * const cloud = new Cloud(numParticles, cloudSize); const double sqrtNumPar = floor(sqrt(numParticles)); const double gridUnit = 2.0*cloudSize/sqrtNumPar; //number of particles per row/column double tempPosX = cloudSize; //position of first particle double tempPosY = cloudSize; //seed rand function with time(NULL): srand((int)time(NULL)); //initialize dust cloud: for(unsigned int i = 0; i < numParticles; i++) { cloud->setPosition(i, tempPosX, tempPosY); cloud->setVelocity(i); cloud->setCharge(i); cloud->setMass(i); tempPosX -= gridUnit; if(tempPosX <= -cloudSize) //end of row { tempPosX = cloudSize; //reset tempPosY -= gridUnit; //move to next row } } cout << "\nInitialization complete.\n"; return cloud; } Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime) { int *anyNull = NULL; long numParticles; long numTimeSteps; //move to CLOUD HDU: if(!*error) fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error); //get number of particles: if(!*error) fits_get_num_rows(file, &numParticles, error); //create cloud: Cloud* cloud = new Cloud((unsigned int)numParticles, 0.0); //cloudSize not used in this case, so set to zero //read mass and charge information: if(!*error) { //file, column #, starting row, first element, num elements, mass array, pointless pointer, error fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error); fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error); } //move to TIME_STEP HDU: if(!*error) fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error); //get number of time steps: if(!*error) fits_get_num_rows(file, &numTimeSteps, error); if(!*error) { if (currentTime) fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error); fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error); fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error); fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error); fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error); } return cloud; } void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const { //format number of elements of type double as string, e.g. 1024D stringstream numStream; numStream << n << "D"; const string numString = numStream.str(); char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")}; char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")}; char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")}; char *ttypeRun[] = {const_cast<char *> ("TIME"), const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"), const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")}; char *tformRun[] = {const_cast<char *> ("D"), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())}; char *tunitRun[] = {const_cast<char *> ("s"), const_cast<char *> ("m"), const_cast<char *> ("m"), const_cast<char *> ("m/s"), const_cast<char *> ("m/s")}; //write mass and charge: if (!*error) //file, storage type, num rows, num columns, ... fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error); if(!*error) { //file, column #, starting row, first element, num elements, mass array, error fits_write_col_dbl(file, 1, 1, 1, n, charge, error); fits_write_col_dbl(file, 2, 1, 1, n, mass, error); } //write position and velocity: if (!*error) fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error); //n.b. num rows automatically incremented. // Increment from 0 as opposed to preallocating to ensure // proper output in the event of program interruption. if (!*error) { double time = 0.0; fits_write_col_dbl(file, 1, 1, 1, 1, &time, error); fits_write_col_dbl(file, 2, 1, 1, n, x, error); fits_write_col_dbl(file, 3, 1, 1, n, y, error); fits_write_col_dbl(file, 4, 1, 1, n, Vx, error); fits_write_col_dbl(file, 5, 1, 1, n, Vy, error); } //write buffer, close file, reopen at same point: fits_flush_file(file, error); } void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const { if (!*error) { long numRows = 0; fits_get_num_rows(file, &numRows, error); fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error); fits_write_col_dbl(file, 2, numRows, 1, n, x, error); fits_write_col_dbl(file, 3, numRows, 1, n, y, error); fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error); fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error); } //write buffer, close file, reopen at same point: fits_flush_file(file, error); } // 4th order Runge-Kutta subsetp helper methods. // X position helper functions const __m128d Cloud::getx1_pd(const unsigned int i) const { // x return _mm_load_pd(x + i); } const __m128d Cloud::getx2_pd(const unsigned int i) const { // x + l1/2 return _mm_load_pd(x + i) + _mm_load_pd(l1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getx3_pd(const unsigned int i) const { // x + l2/2 return _mm_load_pd(x + i) + _mm_load_pd(l2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getx4_pd(const unsigned int i) const { // x + l3 return _mm_load_pd(x + i) + _mm_load_pd(l3 + i); } // X position helper functions const __m128d Cloud::gety1_pd(const unsigned int i) const { // y return _mm_load_pd(y + i); } const __m128d Cloud::gety2_pd(const unsigned int i) const { // y + n1/2 return _mm_load_pd(y + i) + _mm_load_pd(n1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::gety3_pd(const unsigned int i) const { // y + n2/2 return _mm_load_pd(y + i) + _mm_load_pd(n2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::gety4_pd(const unsigned int i) const { // y + n3 return _mm_load_pd(y + i) + _mm_load_pd(n3 + i); } // Vx position helper functions const __m128d Cloud::getVx1_pd(const unsigned int i) const { // Vx return _mm_load_pd(Vx + i); } const __m128d Cloud::getVx2_pd(const unsigned int i) const { // Vx + k1/2 return _mm_load_pd(Vx + i) + _mm_load_pd(k1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVx3_pd(const unsigned int i) const { // Vx + k2/2 return _mm_load_pd(Vx + i) + _mm_load_pd(k2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVx4_pd(const unsigned int i) const { // Vx + k3 return _mm_load_pd(Vx + i) + _mm_load_pd(k3 + i); } // Vy position helper functions const __m128d Cloud::getVy1_pd(const unsigned int i) const { // Vy return _mm_load_pd(Vy + i); } const __m128d Cloud::getVy2_pd(const unsigned int i) const { // Vy + m1/2 return _mm_load_pd(Vy + i) + _mm_load_pd(m1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVy3_pd(const unsigned int i) const { // Vy + m2/2 return _mm_load_pd(Vy + i) + _mm_load_pd(m2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVy4_pd(const unsigned int i) const { // Vy + m3 return _mm_load_pd(Vy + i) + _mm_load_pd(m3 + i); }
/*===- Cloud.cpp - libSimulation -============================================== * * DEMON * * This file is distributed under the BSD Open Source License. See LICENSE.TXT * for details. * *===-----------------------------------------------------------------------===*/ #include "Cloud.h" #include <cmath> #include <iostream> #include <sstream> using namespace std; Cloud::Cloud(unsigned int numPar, double sizeOfCloud) : n(numPar), cloudSize(sizeOfCloud), k1(new double[n]), k2(new double[n]), k3(new double[n]), k4(new double[n]), l1(new double[n]), l2(new double[n]), l3(new double[n]), l4(new double[n]), m1(new double[n]), m2(new double[n]), m3(new double[n]), m4(new double[n]), n1(new double[n]), n2(new double[n]), n3(new double[n]), n4(new double[n]), x(new double[n]), y(new double[n]), Vx(new double[n]), Vy(new double[n]), charge(new double[n]), mass(new double[n]), forceX(new double[n]), forceY(new double[n]) {} Cloud::~Cloud() { delete[] k1; delete[] k2; delete[] k3; delete[] k4; delete[] l1; delete[] l2; delete[] l3; delete[] l4; delete[] m1; delete[] m2; delete[] m3; delete[] m4; delete[] n1; delete[] n2; delete[] n3; delete[] n4; delete[] x; delete[] y; delete[] Vx; delete[] Vy; delete[] charge; delete[] mass; delete[] forceX; delete[] forceY; } inline void Cloud::setPosition(const unsigned int index) { double radius = ((double)rand()/(double)RAND_MAX)*cloudSize; double theta = ((double)rand()/(double)RAND_MAX)*2.0*M_PI; x[index] = radius*cos(theta); y[index] = radius*sin(theta); } inline void Cloud::setPosition(const unsigned int index, const double xVal, const double yVal) { x[index] = xVal; y[index] = yVal; } inline void Cloud::setVelocity(const unsigned int index) { Vx[index] = 0.0; Vy[index] = 0.0; } inline void Cloud::setCharge(const unsigned int index) { charge[index] = (rand()%201 + 5900)*1.6E-19; } inline void Cloud::setMass(const unsigned int index) { const double radius = 1.45E-6; const double particleDensity = 2200.0; mass[index] = (4.0/3.0)*M_PI*radius*radius*radius*particleDensity; } Cloud * const Cloud::initializeNew(const unsigned int numParticles, const double cloudSize) { cout << "\nGenerating original data.\n\n"; Cloud * const cloud = new Cloud(numParticles, cloudSize); //seed rand function with time(NULL): srand((int)time(NULL)); //initialize dust cloud: for(unsigned int i = 0; i < numParticles; i++) { cloud->setPosition(i); cloud->setVelocity(i); cloud->setCharge(i); cloud->setMass(i); } return cloud; } Cloud * const Cloud::initializeGrid(const unsigned int numParticles, const double cloudSize) { cout << "\nInitializing grid.\n\n"; Cloud * const cloud = new Cloud(numParticles, cloudSize); const double sqrtNumPar = floor(sqrt(numParticles)); const double gridUnit = 2.0*cloudSize/sqrtNumPar; //number of particles per row/column double tempPosX = cloudSize; //position of first particle double tempPosY = cloudSize; //seed rand function with time(NULL): srand((int)time(NULL)); //initialize dust cloud: for(unsigned int i = 0; i < numParticles; i++) { cloud->setPosition(i, tempPosX, tempPosY); cloud->setVelocity(i); cloud->setCharge(i); cloud->setMass(i); tempPosX -= gridUnit; if(tempPosX <= -cloudSize) //end of row { tempPosX = cloudSize; //reset tempPosY -= gridUnit; //move to next row } } cout << "\nInitialization complete.\n"; return cloud; } Cloud * const Cloud::initializeFromFile(fitsfile * const file, int * const error, double * const currentTime) { int *anyNull = NULL; long numParticles; long numTimeSteps; //move to CLOUD HDU: if(!*error) fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("CLOUD"), 0, error); //get number of particles: if(!*error) fits_get_num_rows(file, &numParticles, error); //create cloud: Cloud* cloud = new Cloud((unsigned int)numParticles, 0.0); //cloudSize not used in this case, so set to zero //read mass and charge information: if(!*error) { //file, column #, starting row, first element, num elements, mass array, pointless pointer, error fits_read_col_dbl(file, 1, 1, 1, numParticles, 0.0, cloud->charge, anyNull, error); fits_read_col_dbl(file, 2, 1, 1, numParticles, 0.0, cloud->mass, anyNull, error); } //move to TIME_STEP HDU: if(!*error) fits_movnam_hdu(file, BINARY_TBL, const_cast<char *> ("TIME_STEP"), 0, error); //get number of time steps: if(!*error) fits_get_num_rows(file, &numTimeSteps, error); if(!*error) { if (currentTime) fits_read_col_dbl(file, 1, numTimeSteps, 1, 1, 0.0, currentTime, anyNull, error); fits_read_col_dbl(file, 2, numTimeSteps, 1, numParticles, 0.0, cloud->x, anyNull, error); fits_read_col_dbl(file, 3, numTimeSteps, 1, numParticles, 0.0, cloud->y, anyNull, error); fits_read_col_dbl(file, 4, numTimeSteps, 1, numParticles, 0.0, cloud->Vx, anyNull, error); fits_read_col_dbl(file, 5, numTimeSteps, 1, numParticles, 0.0, cloud->Vy, anyNull, error); } return cloud; } void Cloud::writeCloudSetup(fitsfile * const file, int * const error) const { //format number of elements of type double as string, e.g. 1024D stringstream numStream; numStream << n << "D"; const string numString = numStream.str(); char *ttypeCloud[] = {const_cast<char *> ("CHARGE"), const_cast<char *> ("MASS")}; char *tformCloud[] = {const_cast<char *> ("D"), const_cast<char *> ("D")}; char *tunitCloud[] = {const_cast<char *> ("C"), const_cast<char *> ("kg")}; char *ttypeRun[] = {const_cast<char *> ("TIME"), const_cast<char *> ("X_POSITION"), const_cast<char *> ("Y_POSITION"), const_cast<char *> ("X_VELOCITY"), const_cast<char *> ("Y_VELOCITY")}; char *tformRun[] = {const_cast<char *> ("D"), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str()), const_cast<char *> (numString.c_str())}; char *tunitRun[] = {const_cast<char *> ("s"), const_cast<char *> ("m"), const_cast<char *> ("m"), const_cast<char *> ("m/s"), const_cast<char *> ("m/s")}; //write mass and charge: if (!*error) //file, storage type, num rows, num columns, ... fits_create_tbl(file, BINARY_TBL, n, 2, ttypeCloud, tformCloud, tunitCloud, "CLOUD", error); if(!*error) { //file, column #, starting row, first element, num elements, mass array, error fits_write_col_dbl(file, 1, 1, 1, n, charge, error); fits_write_col_dbl(file, 2, 1, 1, n, mass, error); } //write position and velocity: if (!*error) fits_create_tbl(file, BINARY_TBL, 0, 5, ttypeRun, tformRun, tunitRun, "TIME_STEP", error); //n.b. num rows automatically incremented. // Increment from 0 as opposed to preallocating to ensure // proper output in the event of program interruption. if (!*error) { double time = 0.0; fits_write_col_dbl(file, 1, 1, 1, 1, &time, error); fits_write_col_dbl(file, 2, 1, 1, n, x, error); fits_write_col_dbl(file, 3, 1, 1, n, y, error); fits_write_col_dbl(file, 4, 1, 1, n, Vx, error); fits_write_col_dbl(file, 5, 1, 1, n, Vy, error); } //write buffer, close file, reopen at same point: fits_flush_file(file, error); } void Cloud::writeTimeStep(fitsfile * const file, int * const error, double currentTime) const { if (!*error) { long numRows = 0; fits_get_num_rows(file, &numRows, error); fits_write_col_dbl(file, 1, ++numRows, 1, 1, &currentTime, error); fits_write_col_dbl(file, 2, numRows, 1, n, x, error); fits_write_col_dbl(file, 3, numRows, 1, n, y, error); fits_write_col_dbl(file, 4, numRows, 1, n, Vx, error); fits_write_col_dbl(file, 5, numRows, 1, n, Vy, error); } //write buffer, close file, reopen at same point: fits_flush_file(file, error); } // 4th order Runge-Kutta subsetp helper methods. // X position helper functions ------------------------------------------------- const __m128d Cloud::getx1_pd(const unsigned int i) const { // x return _mm_load_pd(x + i); } const __m128d Cloud::getx2_pd(const unsigned int i) const { // x + l1/2 return _mm_load_pd(x + i) + _mm_load_pd(l1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getx3_pd(const unsigned int i) const { // x + l2/2 return _mm_load_pd(x + i) + _mm_load_pd(l2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getx4_pd(const unsigned int i) const { // x + l3 return _mm_load_pd(x + i) + _mm_load_pd(l3 + i); } // Y position helper functions ------------------------------------------------- const __m128d Cloud::gety1_pd(const unsigned int i) const { // y return _mm_load_pd(y + i); } const __m128d Cloud::gety2_pd(const unsigned int i) const { // y + n1/2 return _mm_load_pd(y + i) + _mm_load_pd(n1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::gety3_pd(const unsigned int i) const { // y + n2/2 return _mm_load_pd(y + i) + _mm_load_pd(n2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::gety4_pd(const unsigned int i) const { // y + n3 return _mm_load_pd(y + i) + _mm_load_pd(n3 + i); } // Vx position helper functions ------------------------------------------------ const __m128d Cloud::getVx1_pd(const unsigned int i) const { // Vx return _mm_load_pd(Vx + i); } const __m128d Cloud::getVx2_pd(const unsigned int i) const { // Vx + k1/2 return _mm_load_pd(Vx + i) + _mm_load_pd(k1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVx3_pd(const unsigned int i) const { // Vx + k2/2 return _mm_load_pd(Vx + i) + _mm_load_pd(k2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVx4_pd(const unsigned int i) const { // Vx + k3 return _mm_load_pd(Vx + i) + _mm_load_pd(k3 + i); } // Vy position helper functions ------------------------------------------------ const __m128d Cloud::getVy1_pd(const unsigned int i) const { // Vy return _mm_load_pd(Vy + i); } const __m128d Cloud::getVy2_pd(const unsigned int i) const { // Vy + m1/2 return _mm_load_pd(Vy + i) + _mm_load_pd(m1 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVy3_pd(const unsigned int i) const { // Vy + m2/2 return _mm_load_pd(Vy + i) + _mm_load_pd(m2 + i)/_mm_set1_pd(2.0); } const __m128d Cloud::getVy4_pd(const unsigned int i) const { // Vy + m3 return _mm_load_pd(Vy + i) + _mm_load_pd(m3 + i); }
Fix comment and provide a clearer separation between methods. No functionality change.
Fix comment and provide a clearer separation between methods. No functionality change.
C++
bsd-3-clause
leios/demonsimulationcode,leios/demonsimulationcode
e2b1c08aae0f2651a56de5a519705bbe13331f46
folly/experimental/io/test/AsyncIOTest.cpp
folly/experimental/io/test/AsyncIOTest.cpp
/* * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "folly/experimental/io/AsyncIO.h" #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <poll.h> #include <cstdlib> #include <cstdio> #include <memory> #include <random> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include "folly/experimental/io/FsUtil.h" #include "folly/ScopeGuard.h" #include "folly/String.h" namespace fs = folly::fs; using folly::AsyncIO; using folly::AsyncIOQueue; namespace { constexpr size_t kAlignment = 512; // align reads to 512 B (for O_DIRECT) struct TestSpec { off_t start; size_t size; }; void waitUntilReadable(int fd) { pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; int r; do { r = poll(&pfd, 1, -1); // wait forever } while (r == -1 && errno == EINTR); PCHECK(r == 1); CHECK_EQ(pfd.revents, POLLIN); // no errors etc } folly::Range<AsyncIO::Op**> readerWait(AsyncIO* reader) { int fd = reader->pollFd(); if (fd == -1) { return reader->wait(1); } else { waitUntilReadable(fd); return reader->pollCompleted(); } } // Temporary file that is NOT kept open but is deleted on exit. // Generate random-looking but reproduceable data. class TemporaryFile { public: explicit TemporaryFile(size_t size); ~TemporaryFile(); const fs::path path() const { return path_; } private: fs::path path_; }; TemporaryFile::TemporaryFile(size_t size) : path_(fs::temp_directory_path() / fs::unique_path()) { CHECK_EQ(size % sizeof(uint32_t), 0); size /= sizeof(uint32_t); const uint32_t seed = 42; std::mt19937 rnd(seed); const size_t bufferSize = 1U << 16; uint32_t buffer[bufferSize]; FILE* fp = ::fopen(path_.c_str(), "wb"); PCHECK(fp != nullptr); while (size) { size_t n = std::min(size, bufferSize); for (size_t i = 0; i < n; ++i) { buffer[i] = rnd(); } size_t written = ::fwrite(buffer, sizeof(uint32_t), n, fp); PCHECK(written == n); size -= written; } PCHECK(::fclose(fp) == 0); } TemporaryFile::~TemporaryFile() { try { fs::remove(path_); } catch (const fs::filesystem_error& e) { LOG(ERROR) << "fs::remove: " << folly::exceptionStr(e); } } TemporaryFile tempFile(6 << 20); // 6MiB typedef std::unique_ptr<char, void(*)(void*)> ManagedBuffer; ManagedBuffer allocateAligned(size_t size) { void* buf; int rc = posix_memalign(&buf, 512, size); CHECK_EQ(rc, 0) << strerror(rc); return ManagedBuffer(reinterpret_cast<char*>(buf), free); } void testReadsSerially(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { AsyncIO aioReader(1, pollMode); AsyncIO::Op op; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { auto buf = allocateAligned(specs[i].size); op.pread(fd, buf.get(), specs[i].size, specs[i].start); aioReader.submit(&op); EXPECT_EQ(aioReader.pending(), 1); auto ops = readerWait(&aioReader); EXPECT_EQ(1, ops.size()); EXPECT_TRUE(ops[0] == &op); EXPECT_EQ(aioReader.pending(), 0); ssize_t res = op.result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[i].size, res); op.reset(); } } void testReadsParallel(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { AsyncIO aioReader(specs.size(), pollMode); std::unique_ptr<AsyncIO::Op[]> ops(new AsyncIO::Op[specs.size()]); std::vector<ManagedBuffer> bufs; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { bufs.push_back(allocateAligned(specs[i].size)); ops[i].pread(fd, bufs[i].get(), specs[i].size, specs[i].start); aioReader.submit(&ops[i]); } std::vector<bool> pending(specs.size(), true); size_t remaining = specs.size(); while (remaining != 0) { EXPECT_EQ(remaining, aioReader.pending()); auto completed = readerWait(&aioReader); size_t nrRead = completed.size(); EXPECT_NE(nrRead, 0); remaining -= nrRead; for (int i = 0; i < nrRead; i++) { int id = completed[i] - ops.get(); EXPECT_GE(id, 0); EXPECT_LT(id, specs.size()); EXPECT_TRUE(pending[id]); pending[id] = false; ssize_t res = ops[id].result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[id].size, res); } } EXPECT_EQ(aioReader.pending(), 0); for (int i = 0; i < pending.size(); i++) { EXPECT_FALSE(pending[i]); } } void testReadsQueued(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { size_t readerCapacity = std::max(specs.size() / 2, size_t(1)); AsyncIO aioReader(readerCapacity, pollMode); AsyncIOQueue aioQueue(&aioReader); std::unique_ptr<AsyncIO::Op[]> ops(new AsyncIO::Op[specs.size()]); std::vector<ManagedBuffer> bufs; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { bufs.push_back(allocateAligned(specs[i].size)); ops[i].pread(fd, bufs[i].get(), specs[i].size, specs[i].start); aioQueue.submit(&ops[i]); } std::vector<bool> pending(specs.size(), true); size_t remaining = specs.size(); while (remaining != 0) { if (remaining >= readerCapacity) { EXPECT_EQ(readerCapacity, aioReader.pending()); EXPECT_EQ(remaining - readerCapacity, aioQueue.queued()); } else { EXPECT_EQ(remaining, aioReader.pending()); EXPECT_EQ(0, aioQueue.queued()); } auto completed = readerWait(&aioReader); size_t nrRead = completed.size(); EXPECT_NE(nrRead, 0); remaining -= nrRead; for (int i = 0; i < nrRead; i++) { int id = completed[i] - ops.get(); EXPECT_GE(id, 0); EXPECT_LT(id, specs.size()); EXPECT_TRUE(pending[id]); pending[id] = false; ssize_t res = ops[id].result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[id].size, res); } } EXPECT_EQ(aioReader.pending(), 0); EXPECT_EQ(aioQueue.queued(), 0); for (int i = 0; i < pending.size(); i++) { EXPECT_FALSE(pending[i]); } } void testReads(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { testReadsSerially(specs, pollMode); testReadsParallel(specs, pollMode); testReadsQueued(specs, pollMode); } } // anonymous namespace TEST(AsyncIO, ZeroAsyncDataNotPollable) { testReads({{0, 0}}, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, ZeroAsyncDataPollable) { testReads({{0, 0}}, AsyncIO::POLLABLE); } TEST(AsyncIO, SingleAsyncDataNotPollable) { testReads({{0, 512}}, AsyncIO::NOT_POLLABLE); testReads({{0, 512}}, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, SingleAsyncDataPollable) { testReads({{0, 512}}, AsyncIO::POLLABLE); testReads({{0, 512}}, AsyncIO::POLLABLE); } TEST(AsyncIO, MultipleAsyncDataNotPollable) { testReads({{512, 1024}, {512, 1024}, {512, 2048}}, AsyncIO::NOT_POLLABLE); testReads({{512, 1024}, {512, 1024}, {512, 2048}}, AsyncIO::NOT_POLLABLE); testReads({ {0, 5*1024*1024}, {512, 5*1024*1024}, }, AsyncIO::NOT_POLLABLE); testReads({ {512, 0}, {512, 512}, {512, 1024}, {512, 10*1024}, {512, 1024*1024}, }, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, MultipleAsyncDataPollable) { testReads({{512, 1024}, {512, 1024}, {512, 2048}}, AsyncIO::POLLABLE); testReads({{512, 1024}, {512, 1024}, {512, 2048}}, AsyncIO::POLLABLE); testReads({ {0, 5*1024*1024}, {512, 5*1024*1024}, }, AsyncIO::POLLABLE); testReads({ {512, 0}, {512, 512}, {512, 1024}, {512, 10*1024}, {512, 1024*1024}, }, AsyncIO::POLLABLE); } TEST(AsyncIO, ManyAsyncDataNotPollable) { { std::vector<TestSpec> v; for (int i = 0; i < 1000; i++) { v.push_back({512 * i, 512}); } testReads(v, AsyncIO::NOT_POLLABLE); } } TEST(AsyncIO, ManyAsyncDataPollable) { { std::vector<TestSpec> v; for (int i = 0; i < 1000; i++) { v.push_back({512 * i, 512}); } testReads(v, AsyncIO::POLLABLE); } } TEST(AsyncIO, NonBlockingWait) { AsyncIO aioReader(1, AsyncIO::NOT_POLLABLE); AsyncIO::Op op; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; size_t size = 1024; auto buf = allocateAligned(size); op.pread(fd, buf.get(), size, 0); aioReader.submit(&op); EXPECT_EQ(aioReader.pending(), 1); folly::Range<AsyncIO::Op**> completed; while (completed.empty()) { // poll without blocking until the read request completes. completed = aioReader.wait(0); } EXPECT_EQ(completed.size(), 1); EXPECT_TRUE(completed[0] == &op); ssize_t res = op.result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(size, res); EXPECT_EQ(aioReader.pending(), 0); }
/* * Copyright 2013 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "folly/experimental/io/AsyncIO.h" #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <poll.h> #include <cstdlib> #include <cstdio> #include <memory> #include <random> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include "folly/experimental/io/FsUtil.h" #include "folly/ScopeGuard.h" #include "folly/String.h" namespace fs = folly::fs; using folly::AsyncIO; using folly::AsyncIOQueue; namespace { constexpr size_t kAlign = 4096; // align reads to 4096 B (for O_DIRECT) struct TestSpec { off_t start; size_t size; }; void waitUntilReadable(int fd) { pollfd pfd; pfd.fd = fd; pfd.events = POLLIN; int r; do { r = poll(&pfd, 1, -1); // wait forever } while (r == -1 && errno == EINTR); PCHECK(r == 1); CHECK_EQ(pfd.revents, POLLIN); // no errors etc } folly::Range<AsyncIO::Op**> readerWait(AsyncIO* reader) { int fd = reader->pollFd(); if (fd == -1) { return reader->wait(1); } else { waitUntilReadable(fd); return reader->pollCompleted(); } } // Temporary file that is NOT kept open but is deleted on exit. // Generate random-looking but reproduceable data. class TemporaryFile { public: explicit TemporaryFile(size_t size); ~TemporaryFile(); const fs::path path() const { return path_; } private: fs::path path_; }; TemporaryFile::TemporaryFile(size_t size) : path_(fs::temp_directory_path() / fs::unique_path()) { CHECK_EQ(size % sizeof(uint32_t), 0); size /= sizeof(uint32_t); const uint32_t seed = 42; std::mt19937 rnd(seed); const size_t bufferSize = 1U << 16; uint32_t buffer[bufferSize]; FILE* fp = ::fopen(path_.c_str(), "wb"); PCHECK(fp != nullptr); while (size) { size_t n = std::min(size, bufferSize); for (size_t i = 0; i < n; ++i) { buffer[i] = rnd(); } size_t written = ::fwrite(buffer, sizeof(uint32_t), n, fp); PCHECK(written == n); size -= written; } PCHECK(::fclose(fp) == 0); } TemporaryFile::~TemporaryFile() { try { fs::remove(path_); } catch (const fs::filesystem_error& e) { LOG(ERROR) << "fs::remove: " << folly::exceptionStr(e); } } TemporaryFile tempFile(6 << 20); // 6MiB typedef std::unique_ptr<char, void(*)(void*)> ManagedBuffer; ManagedBuffer allocateAligned(size_t size) { void* buf; int rc = posix_memalign(&buf, kAlign, size); CHECK_EQ(rc, 0) << strerror(rc); return ManagedBuffer(reinterpret_cast<char*>(buf), free); } void testReadsSerially(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { AsyncIO aioReader(1, pollMode); AsyncIO::Op op; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { auto buf = allocateAligned(specs[i].size); op.pread(fd, buf.get(), specs[i].size, specs[i].start); aioReader.submit(&op); EXPECT_EQ(aioReader.pending(), 1); auto ops = readerWait(&aioReader); EXPECT_EQ(1, ops.size()); EXPECT_TRUE(ops[0] == &op); EXPECT_EQ(aioReader.pending(), 0); ssize_t res = op.result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[i].size, res); op.reset(); } } void testReadsParallel(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { AsyncIO aioReader(specs.size(), pollMode); std::unique_ptr<AsyncIO::Op[]> ops(new AsyncIO::Op[specs.size()]); std::vector<ManagedBuffer> bufs; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { bufs.push_back(allocateAligned(specs[i].size)); ops[i].pread(fd, bufs[i].get(), specs[i].size, specs[i].start); aioReader.submit(&ops[i]); } std::vector<bool> pending(specs.size(), true); size_t remaining = specs.size(); while (remaining != 0) { EXPECT_EQ(remaining, aioReader.pending()); auto completed = readerWait(&aioReader); size_t nrRead = completed.size(); EXPECT_NE(nrRead, 0); remaining -= nrRead; for (int i = 0; i < nrRead; i++) { int id = completed[i] - ops.get(); EXPECT_GE(id, 0); EXPECT_LT(id, specs.size()); EXPECT_TRUE(pending[id]); pending[id] = false; ssize_t res = ops[id].result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[id].size, res); } } EXPECT_EQ(aioReader.pending(), 0); for (int i = 0; i < pending.size(); i++) { EXPECT_FALSE(pending[i]); } } void testReadsQueued(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { size_t readerCapacity = std::max(specs.size() / 2, size_t(1)); AsyncIO aioReader(readerCapacity, pollMode); AsyncIOQueue aioQueue(&aioReader); std::unique_ptr<AsyncIO::Op[]> ops(new AsyncIO::Op[specs.size()]); std::vector<ManagedBuffer> bufs; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; for (int i = 0; i < specs.size(); i++) { bufs.push_back(allocateAligned(specs[i].size)); ops[i].pread(fd, bufs[i].get(), specs[i].size, specs[i].start); aioQueue.submit(&ops[i]); } std::vector<bool> pending(specs.size(), true); size_t remaining = specs.size(); while (remaining != 0) { if (remaining >= readerCapacity) { EXPECT_EQ(readerCapacity, aioReader.pending()); EXPECT_EQ(remaining - readerCapacity, aioQueue.queued()); } else { EXPECT_EQ(remaining, aioReader.pending()); EXPECT_EQ(0, aioQueue.queued()); } auto completed = readerWait(&aioReader); size_t nrRead = completed.size(); EXPECT_NE(nrRead, 0); remaining -= nrRead; for (int i = 0; i < nrRead; i++) { int id = completed[i] - ops.get(); EXPECT_GE(id, 0); EXPECT_LT(id, specs.size()); EXPECT_TRUE(pending[id]); pending[id] = false; ssize_t res = ops[id].result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(specs[id].size, res); } } EXPECT_EQ(aioReader.pending(), 0); EXPECT_EQ(aioQueue.queued(), 0); for (int i = 0; i < pending.size(); i++) { EXPECT_FALSE(pending[i]); } } void testReads(const std::vector<TestSpec>& specs, AsyncIO::PollMode pollMode) { testReadsSerially(specs, pollMode); testReadsParallel(specs, pollMode); testReadsQueued(specs, pollMode); } } // anonymous namespace TEST(AsyncIO, ZeroAsyncDataNotPollable) { testReads({{0, 0}}, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, ZeroAsyncDataPollable) { testReads({{0, 0}}, AsyncIO::POLLABLE); } TEST(AsyncIO, SingleAsyncDataNotPollable) { testReads({{0, kAlign}}, AsyncIO::NOT_POLLABLE); testReads({{0, kAlign}}, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, SingleAsyncDataPollable) { testReads({{0, kAlign}}, AsyncIO::POLLABLE); testReads({{0, kAlign}}, AsyncIO::POLLABLE); } TEST(AsyncIO, MultipleAsyncDataNotPollable) { testReads( {{kAlign, 2*kAlign}, {kAlign, 2*kAlign}, {kAlign, 4*kAlign}}, AsyncIO::NOT_POLLABLE); testReads( {{kAlign, 2*kAlign}, {kAlign, 2*kAlign}, {kAlign, 4*kAlign}}, AsyncIO::NOT_POLLABLE); testReads({ {0, 5*1024*1024}, {kAlign, 5*1024*1024} }, AsyncIO::NOT_POLLABLE); testReads({ {kAlign, 0}, {kAlign, kAlign}, {kAlign, 2*kAlign}, {kAlign, 20*kAlign}, {kAlign, 1024*1024}, }, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, MultipleAsyncDataPollable) { testReads( {{kAlign, 2*kAlign}, {kAlign, 2*kAlign}, {kAlign, 4*kAlign}}, AsyncIO::POLLABLE); testReads( {{kAlign, 2*kAlign}, {kAlign, 2*kAlign}, {kAlign, 4*kAlign}}, AsyncIO::POLLABLE); testReads({ {0, 5*1024*1024}, {kAlign, 5*1024*1024} }, AsyncIO::NOT_POLLABLE); testReads({ {kAlign, 0}, {kAlign, kAlign}, {kAlign, 2*kAlign}, {kAlign, 20*kAlign}, {kAlign, 1024*1024}, }, AsyncIO::NOT_POLLABLE); } TEST(AsyncIO, ManyAsyncDataNotPollable) { { std::vector<TestSpec> v; for (int i = 0; i < 1000; i++) { v.push_back({kAlign * i, kAlign}); } testReads(v, AsyncIO::NOT_POLLABLE); } } TEST(AsyncIO, ManyAsyncDataPollable) { { std::vector<TestSpec> v; for (int i = 0; i < 1000; i++) { v.push_back({kAlign * i, kAlign}); } testReads(v, AsyncIO::POLLABLE); } } TEST(AsyncIO, NonBlockingWait) { AsyncIO aioReader(1, AsyncIO::NOT_POLLABLE); AsyncIO::Op op; int fd = ::open(tempFile.path().c_str(), O_DIRECT | O_RDONLY); PCHECK(fd != -1); SCOPE_EXIT { ::close(fd); }; size_t size = 2*kAlign; auto buf = allocateAligned(size); op.pread(fd, buf.get(), size, 0); aioReader.submit(&op); EXPECT_EQ(aioReader.pending(), 1); folly::Range<AsyncIO::Op**> completed; while (completed.empty()) { // poll without blocking until the read request completes. completed = aioReader.wait(0); } EXPECT_EQ(completed.size(), 1); EXPECT_TRUE(completed[0] == &op); ssize_t res = op.result(); EXPECT_LE(0, res) << folly::errnoStr(-res); EXPECT_EQ(size, res); EXPECT_EQ(aioReader.pending(), 0); }
Fix async_io_test to work with larger block sizes
Fix async_io_test to work with larger block sizes Test Plan: ran it Reviewed By: [email protected] FB internal diff: D787733
C++
apache-2.0
shaobz/folly,constantine001/folly,nickhen/folly,CJstar/folly,ykarlsbrun/folly,xzmagic/folly,Hincoin/folly,bowlofstew/folly,unmeshvrije/C--,PPC64/folly,CJstar/folly,tomhughes/folly,lifei/folly,SeanRBurton/folly,yangjin-unique/folly,romange/folly,reddit/folly,brunomorishita/folly,nickhen/folly,cppfool/folly,shaobz/folly,loverszhaokai/folly,lifei/folly,colemancda/folly,guker/folly,clearlinux/folly,raphaelamorim/folly,chjp2046/folly,mqeizi/folly,bowlofstew/folly,sonnyhu/folly,romange/folly,romange/folly,arg0/folly,mqeizi/folly,reddit/folly,KSreeHarsha/folly,charsyam/folly,SammyK/folly,sakishum/folly,gaoyingie/folly,upsoft/folly,bobegir/folly,upsoft/folly,clearlylin/folly,sonnyhu/folly,rklabs/folly,sakishum/folly,bsampath/folly,raphaelamorim/folly,renyinew/folly,project-zerus/folly,bsampath/folly,doctaweeks/folly,bowlofstew/folly,juniway/folly,PoisonBOx/folly,Hincoin/folly,SammyK/folly,shaobz/folly,romange/folly,reddit/folly,tempbottle/folly,loverszhaokai/folly,mqeizi/folly,ykarlsbrun/folly,SeanRBurton/folly,Eagle-X/folly,lifei/folly,guker/folly,PPC64/folly,nickhen/folly,floxard/folly,SeanRBurton/folly,project-zerus/folly,chjp2046/folly,chjp2046/folly,doctaweeks/folly,fw1121/folly,tomhughes/folly,gaoyingie/folly,KSreeHarsha/folly,zhiweicai/folly,Orvid/folly,sakishum/folly,brunomorishita/folly,Eagle-X/folly,arg0/folly,raphaelamorim/folly,gavioto/folly,colemancda/folly,Hincoin/folly,bikong2/folly,clearlinux/folly,floxard/folly,mqeizi/folly,guker/folly,clearlinux/folly,constantine001/folly,cole14/folly,project-zerus/folly,floxard/folly,rklabs/folly,hongliangzhao/folly,bobegir/folly,zhiweicai/folly,yangjin-unique/folly,floxard/folly,unmeshvrije/C--,loversInJapan/folly,upsoft/folly,SeanRBurton/folly,chjp2046/folly,cole14/folly,Hincoin/folly,loversInJapan/folly,loversInJapan/folly,zhiweicai/folly,sakishum/folly,fw1121/folly,cole14/folly,shaobz/folly,nickhen/folly,shaobz/folly,arg0/folly,PoisonBOx/folly,facebook/folly,arg0/folly,kernelim/folly,chjp2046/folly,theiver9827/folly,bsampath/folly,fw1121/folly,PPC64/folly,renyinew/folly,Hincoin/folly,bikong2/folly,fw1121/folly,gavioto/folly,tempbottle/folly,clearlinux/folly,stonegithubs/folly,fw1121/folly,cole14/folly,rklabs/folly,xzmagic/folly,kernelim/folly,ykarlsbrun/folly,cppfool/folly,lifei/folly,KSreeHarsha/folly,bowlofstew/folly,cppfool/folly,PPC64/folly,tomhughes/folly,gaoyingie/folly,cole14/folly,theiver9827/folly,CJstar/folly,bikong2/folly,clearlinux/folly,renyinew/folly,gaoyingie/folly,juniway/folly,leolujuyi/folly,colemancda/folly,tomhughes/folly,unmeshvrije/C--,project-zerus/folly,PoisonBOx/folly,wildinto/folly,brunomorishita/folly,Eagle-X/folly,renyinew/folly,alexst07/folly,Orvid/folly,facebook/folly,brunomorishita/folly,ykarlsbrun/folly,project-zerus/folly,unmeshvrije/C--,leolujuyi/folly,constantine001/folly,clearlylin/folly,reddit/folly,colemancda/folly,loverszhaokai/folly,raphaelamorim/folly,floxard/folly,renyinew/folly,mqeizi/folly,colemancda/folly,reddit/folly,guker/folly,bowlofstew/folly,upsoft/folly,facebook/folly,lifei/folly,gavioto/folly,CJstar/folly,gavioto/folly,wildinto/folly,loversInJapan/folly,bobegir/folly,alexst07/folly,tempbottle/folly,theiver9827/folly,zhiweicai/folly,SammyK/folly,unmeshvrije/C--,upsoft/folly,kernelim/folly,tempbottle/folly,KSreeHarsha/folly,stonegithubs/folly,PoisonBOx/folly,kernelim/folly,wildinto/folly,SammyK/folly,tempbottle/folly,xzmagic/folly,cppfool/folly,Orvid/folly,hongliangzhao/folly,wildinto/folly,hongliangzhao/folly,raphaelamorim/folly,clearlylin/folly,bikong2/folly,cppfool/folly,sakishum/folly,leolujuyi/folly,PoisonBOx/folly,Orvid/folly,loverszhaokai/folly,bikong2/folly,stonegithubs/folly,ykarlsbrun/folly,KSreeHarsha/folly,hongliangzhao/folly,alexst07/folly,doctaweeks/folly,CJstar/folly,zhiweicai/folly,xzmagic/folly,hongliangzhao/folly,yangjin-unique/folly,rklabs/folly,bobegir/folly,rklabs/folly,arg0/folly,juniway/folly,tomhughes/folly,Eagle-X/folly,kernelim/folly,clearlylin/folly,clearlylin/folly,brunomorishita/folly,gavioto/folly,leolujuyi/folly,theiver9827/folly,SammyK/folly,loverszhaokai/folly,facebook/folly,Eagle-X/folly,bobegir/folly,yangjin-unique/folly,charsyam/folly,alexst07/folly,alexst07/folly,nickhen/folly,doctaweeks/folly,loversInJapan/folly,yangjin-unique/folly,gaoyingie/folly,SeanRBurton/folly,stonegithubs/folly,Orvid/folly,sonnyhu/folly,leolujuyi/folly,charsyam/folly,wildinto/folly,sonnyhu/folly,facebook/folly,constantine001/folly,guker/folly,sonnyhu/folly,PPC64/folly,juniway/folly,xzmagic/folly,bsampath/folly,stonegithubs/folly,juniway/folly,bsampath/folly,theiver9827/folly,doctaweeks/folly,constantine001/folly,unmeshvrije/C--,charsyam/folly,romange/folly
61bb9cac0409faa6c671727b3bb065e07dff5315
CodeGen/CodeGenModule.cpp
CodeGen/CodeGenModule.cpp
//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This coordinates the per-module state used while generating code. // //===----------------------------------------------------------------------===// #include "CodeGenModule.h" #include "CodeGenFunction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Intrinsics.h" using namespace clang; using namespace CodeGen; CodeGenModule::CodeGenModule(ASTContext &C, llvm::Module &M) : Context(C), TheModule(M), Types(C, M), CFConstantStringClassRef(0) {} llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) { // See if it is already in the map. llvm::Constant *&Entry = GlobalDeclMap[D]; if (Entry) return Entry; QualType ASTTy = cast<ValueDecl>(D)->getType(); const llvm::Type *Ty = getTypes().ConvertType(ASTTy); if (isa<FunctionDecl>(D)) { const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); // FIXME: param attributes for sext/zext etc. return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(), &getModule()); } assert(isa<FileVarDecl>(D) && "Unknown global decl!"); return Entry = new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 0, D->getName(), &getModule()); } void CodeGenModule::EmitFunction(const FunctionDecl *FD) { // If this is not a prototype, emit the body. if (FD->getBody()) CodeGenFunction(*this).GenerateCode(FD); } llvm::Constant *CodeGenModule::EmitGlobalInit(const FileVarDecl *D, llvm::GlobalVariable *GV) { const InitListExpr *ILE = dyn_cast<InitListExpr>(D->getInit()); if (!ILE) return 0; unsigned NumInitElements = ILE->getNumInits(); assert ( ILE->getType()->isArrayType() && "FIXME: Only Array initializers are supported"); std::vector<llvm::Constant*> ArrayElts; const llvm::PointerType *APType = cast<llvm::PointerType>(GV->getType()); const llvm::ArrayType *AType = cast<llvm::ArrayType>(APType->getElementType()); // Copy initializer elements. unsigned i = 0; for (i = 0; i < NumInitElements; ++i) { assert (ILE->getInit(i)->getType()->isIntegerType() && "Only IntegerType global array initializers are supported"); llvm::APSInt Value(static_cast<uint32_t> (getContext().getTypeSize(ILE->getInit(i)->getType(), SourceLocation()))); if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) { llvm::Constant *C = llvm::ConstantInt::get(Value); ArrayElts.push_back(C); } } // Initialize remaining array elements. unsigned NumArrayElements = AType->getNumElements(); const llvm::Type *AElemTy = AType->getElementType(); for (; i < NumArrayElements; ++i) ArrayElts.push_back(llvm::Constant::getNullValue(AElemTy)); return llvm::ConstantArray::get(AType, ArrayElts); } void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) { llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D)); // If the storage class is external and there is no initializer, just leave it // as a declaration. if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) return; // Otherwise, convert the initializer, or use zero if appropriate. llvm::Constant *Init = 0; if (D->getInit() == 0) { Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); } else if (D->getType()->isIntegerType()) { llvm::APSInt Value(static_cast<uint32_t>( getContext().getTypeSize(D->getInit()->getType(), SourceLocation()))); if (D->getInit()->isIntegerConstantExpr(Value, Context)) Init = llvm::ConstantInt::get(Value); } if (!Init) Init = EmitGlobalInit(D, GV); assert(Init && "FIXME: Global variable initializers unimp!"); GV->setInitializer(Init); // Set the llvm linkage type as appropriate. // FIXME: This isn't right. This should handle common linkage and other // stuff. switch (D->getStorageClass()) { case VarDecl::Auto: case VarDecl::Register: assert(0 && "Can't have auto or register globals"); case VarDecl::None: case VarDecl::Extern: // todo: common break; case VarDecl::Static: GV->setLinkage(llvm::GlobalVariable::InternalLinkage); break; } } /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified /// declarator chain. void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) { for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator())) EmitGlobalVar(D); } /// getBuiltinLibFunction llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { if (BuiltinFunctions.size() <= BuiltinID) BuiltinFunctions.resize(BuiltinID); // Already available? llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID]; if (FunctionSlot) return FunctionSlot; assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); // Get the name, skip over the __builtin_ prefix. const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; // Get the type for the builtin. QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); const llvm::FunctionType *Ty = cast<llvm::FunctionType>(getTypes().ConvertType(Type)); // FIXME: This has a serious problem with code like this: // void abs() {} // ... __builtin_abs(x); // The two versions of abs will collide. The fix is for the builtin to win, // and for the existing one to be turned into a constantexpr cast of the // builtin. In the case where the existing one is a static function, it // should just be renamed. if (llvm::Function *Existing = getModule().getFunction(Name)) { if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) return FunctionSlot = Existing; assert(Existing == 0 && "FIXME: Name collision"); } // FIXME: param attributes for sext/zext etc. return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage, Name, &getModule()); } llvm::Function *CodeGenModule::getMemCpyFn() { if (MemCpyFn) return MemCpyFn; llvm::Intrinsic::ID IID; uint64_t Size; unsigned Align; Context.Target.getPointerInfo(Size, Align, SourceLocation()); switch (Size) { default: assert(0 && "Unknown ptr width"); case 32: IID = llvm::Intrinsic::memcpy_i32; break; case 64: IID = llvm::Intrinsic::memcpy_i64; break; } return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID); } llvm::Constant *CodeGenModule:: GetAddrOfConstantCFString(const std::string &str) { llvm::StringMapEntry<llvm::Constant *> &Entry = CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); if (Entry.getValue()) return Entry.getValue(); std::vector<llvm::Constant*> Fields; if (!CFConstantStringClassRef) { const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); Ty = llvm::ArrayType::get(Ty, 0); CFConstantStringClassRef = new llvm::GlobalVariable(Ty, false, llvm::GlobalVariable::ExternalLinkage, 0, "__CFConstantStringClassReference", &getModule()); } // Class pointer. llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); llvm::Constant *Zeros[] = { Zero, Zero }; llvm::Constant *C = llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); Fields.push_back(C); // Flags. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); // String pointer. C = llvm::ConstantArray::get(str); C = new llvm::GlobalVariable(C->getType(), true, llvm::GlobalValue::InternalLinkage, C, ".str", &getModule()); C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); Fields.push_back(C); // String length. Ty = getTypes().ConvertType(getContext().LongTy); Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); // The struct. Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); C = new llvm::GlobalVariable(C->getType(), true, llvm::GlobalVariable::InternalLinkage, C, "", &getModule()); Entry.setValue(C); return C; }
//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===// // // The LLVM Compiler Infrastructure // // This file was developed by Chris Lattner and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This coordinates the per-module state used while generating code. // //===----------------------------------------------------------------------===// #include "CodeGenModule.h" #include "CodeGenFunction.h" #include "clang/AST/ASTContext.h" #include "clang/AST/Decl.h" #include "clang/Basic/TargetInfo.h" #include "llvm/Constants.h" #include "llvm/DerivedTypes.h" #include "llvm/Module.h" #include "llvm/Intrinsics.h" using namespace clang; using namespace CodeGen; CodeGenModule::CodeGenModule(ASTContext &C, llvm::Module &M) : Context(C), TheModule(M), Types(C, M), MemCpyFn(0), CFConstantStringClassRef(0) {} llvm::Constant *CodeGenModule::GetAddrOfGlobalDecl(const ValueDecl *D) { // See if it is already in the map. llvm::Constant *&Entry = GlobalDeclMap[D]; if (Entry) return Entry; QualType ASTTy = cast<ValueDecl>(D)->getType(); const llvm::Type *Ty = getTypes().ConvertType(ASTTy); if (isa<FunctionDecl>(D)) { const llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty); // FIXME: param attributes for sext/zext etc. return Entry = new llvm::Function(FTy, llvm::Function::ExternalLinkage, D->getName(), &getModule()); } assert(isa<FileVarDecl>(D) && "Unknown global decl!"); return Entry = new llvm::GlobalVariable(Ty, false, llvm::GlobalValue::ExternalLinkage, 0, D->getName(), &getModule()); } void CodeGenModule::EmitFunction(const FunctionDecl *FD) { // If this is not a prototype, emit the body. if (FD->getBody()) CodeGenFunction(*this).GenerateCode(FD); } llvm::Constant *CodeGenModule::EmitGlobalInit(const FileVarDecl *D, llvm::GlobalVariable *GV) { const InitListExpr *ILE = dyn_cast<InitListExpr>(D->getInit()); if (!ILE) return 0; unsigned NumInitElements = ILE->getNumInits(); assert ( ILE->getType()->isArrayType() && "FIXME: Only Array initializers are supported"); std::vector<llvm::Constant*> ArrayElts; const llvm::PointerType *APType = cast<llvm::PointerType>(GV->getType()); const llvm::ArrayType *AType = cast<llvm::ArrayType>(APType->getElementType()); // Copy initializer elements. unsigned i = 0; for (i = 0; i < NumInitElements; ++i) { assert (ILE->getInit(i)->getType()->isIntegerType() && "Only IntegerType global array initializers are supported"); llvm::APSInt Value(static_cast<uint32_t> (getContext().getTypeSize(ILE->getInit(i)->getType(), SourceLocation()))); if (ILE->getInit(i)->isIntegerConstantExpr(Value, Context)) { llvm::Constant *C = llvm::ConstantInt::get(Value); ArrayElts.push_back(C); } } // Initialize remaining array elements. unsigned NumArrayElements = AType->getNumElements(); const llvm::Type *AElemTy = AType->getElementType(); for (; i < NumArrayElements; ++i) ArrayElts.push_back(llvm::Constant::getNullValue(AElemTy)); return llvm::ConstantArray::get(AType, ArrayElts); } void CodeGenModule::EmitGlobalVar(const FileVarDecl *D) { llvm::GlobalVariable *GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalDecl(D)); // If the storage class is external and there is no initializer, just leave it // as a declaration. if (D->getStorageClass() == VarDecl::Extern && D->getInit() == 0) return; // Otherwise, convert the initializer, or use zero if appropriate. llvm::Constant *Init = 0; if (D->getInit() == 0) { Init = llvm::Constant::getNullValue(GV->getType()->getElementType()); } else if (D->getType()->isIntegerType()) { llvm::APSInt Value(static_cast<uint32_t>( getContext().getTypeSize(D->getInit()->getType(), SourceLocation()))); if (D->getInit()->isIntegerConstantExpr(Value, Context)) Init = llvm::ConstantInt::get(Value); } if (!Init) Init = EmitGlobalInit(D, GV); assert(Init && "FIXME: Global variable initializers unimp!"); GV->setInitializer(Init); // Set the llvm linkage type as appropriate. // FIXME: This isn't right. This should handle common linkage and other // stuff. switch (D->getStorageClass()) { case VarDecl::Auto: case VarDecl::Register: assert(0 && "Can't have auto or register globals"); case VarDecl::None: case VarDecl::Extern: // todo: common break; case VarDecl::Static: GV->setLinkage(llvm::GlobalVariable::InternalLinkage); break; } } /// EmitGlobalVarDeclarator - Emit all the global vars attached to the specified /// declarator chain. void CodeGenModule::EmitGlobalVarDeclarator(const FileVarDecl *D) { for (; D; D = cast_or_null<FileVarDecl>(D->getNextDeclarator())) EmitGlobalVar(D); } /// getBuiltinLibFunction llvm::Function *CodeGenModule::getBuiltinLibFunction(unsigned BuiltinID) { if (BuiltinFunctions.size() <= BuiltinID) BuiltinFunctions.resize(BuiltinID); // Already available? llvm::Function *&FunctionSlot = BuiltinFunctions[BuiltinID]; if (FunctionSlot) return FunctionSlot; assert(Context.BuiltinInfo.isLibFunction(BuiltinID) && "isn't a lib fn"); // Get the name, skip over the __builtin_ prefix. const char *Name = Context.BuiltinInfo.GetName(BuiltinID)+10; // Get the type for the builtin. QualType Type = Context.BuiltinInfo.GetBuiltinType(BuiltinID, Context); const llvm::FunctionType *Ty = cast<llvm::FunctionType>(getTypes().ConvertType(Type)); // FIXME: This has a serious problem with code like this: // void abs() {} // ... __builtin_abs(x); // The two versions of abs will collide. The fix is for the builtin to win, // and for the existing one to be turned into a constantexpr cast of the // builtin. In the case where the existing one is a static function, it // should just be renamed. if (llvm::Function *Existing = getModule().getFunction(Name)) { if (Existing->getFunctionType() == Ty && Existing->hasExternalLinkage()) return FunctionSlot = Existing; assert(Existing == 0 && "FIXME: Name collision"); } // FIXME: param attributes for sext/zext etc. return FunctionSlot = new llvm::Function(Ty, llvm::Function::ExternalLinkage, Name, &getModule()); } llvm::Function *CodeGenModule::getMemCpyFn() { if (MemCpyFn) return MemCpyFn; llvm::Intrinsic::ID IID; uint64_t Size; unsigned Align; Context.Target.getPointerInfo(Size, Align, SourceLocation()); switch (Size) { default: assert(0 && "Unknown ptr width"); case 32: IID = llvm::Intrinsic::memcpy_i32; break; case 64: IID = llvm::Intrinsic::memcpy_i64; break; } return MemCpyFn = llvm::Intrinsic::getDeclaration(&TheModule, IID); } llvm::Constant *CodeGenModule:: GetAddrOfConstantCFString(const std::string &str) { llvm::StringMapEntry<llvm::Constant *> &Entry = CFConstantStringMap.GetOrCreateValue(&str[0], &str[str.length()]); if (Entry.getValue()) return Entry.getValue(); std::vector<llvm::Constant*> Fields; if (!CFConstantStringClassRef) { const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); Ty = llvm::ArrayType::get(Ty, 0); CFConstantStringClassRef = new llvm::GlobalVariable(Ty, false, llvm::GlobalVariable::ExternalLinkage, 0, "__CFConstantStringClassReference", &getModule()); } // Class pointer. llvm::Constant *Zero = llvm::Constant::getNullValue(llvm::Type::Int32Ty); llvm::Constant *Zeros[] = { Zero, Zero }; llvm::Constant *C = llvm::ConstantExpr::getGetElementPtr(CFConstantStringClassRef, Zeros, 2); Fields.push_back(C); // Flags. const llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy); Fields.push_back(llvm::ConstantInt::get(Ty, 1992)); // String pointer. C = llvm::ConstantArray::get(str); C = new llvm::GlobalVariable(C->getType(), true, llvm::GlobalValue::InternalLinkage, C, ".str", &getModule()); C = llvm::ConstantExpr::getGetElementPtr(C, Zeros, 2); Fields.push_back(C); // String length. Ty = getTypes().ConvertType(getContext().LongTy); Fields.push_back(llvm::ConstantInt::get(Ty, str.length())); // The struct. Ty = getTypes().ConvertType(getContext().getCFConstantStringType()); C = llvm::ConstantStruct::get(cast<llvm::StructType>(Ty), Fields); C = new llvm::GlobalVariable(C->getType(), true, llvm::GlobalVariable::InternalLinkage, C, "", &getModule()); Entry.setValue(C); return C; }
Initialize MemCpyFn
Initialize MemCpyFn git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@43569 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang
544ca18d5fe7e415dc56e185b20ed1ac0f8b7a83
microflo/emscripten.hpp
microflo/emscripten.hpp
/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <[email protected]> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <stdio.h> #include <unistd.h> #include <stddef.h> #include <stdlib.h> #include "microflo.hpp" void loadFromEEPROM(HostCommunication *controller) { for (unsigned int i=0; i<sizeof(graph); i++) { unsigned char c = graph[i]; controller->parseByte(c); } } #include <new> void * operator new(size_t n) throw(std::bad_alloc) { void * const p = malloc(n); if (!p) { throw std::bad_alloc(); } return p; } void operator delete(void * p) throw() { free(p); } void print_foo(int ignored) { printf("FOO\n"); } extern "C" { void emscripten_main(); } class EmscriptenIO : public IO { public: long timeMs; EmscriptenIO() { timeMs = 0; } ~EmscriptenIO() {} // Serial virtual void SerialBegin(int serialDevice, int baudrate) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual long SerialDataAvailable(int serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual unsigned char SerialRead(int serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return '\0'; } virtual void SerialWrite(int serialDevice, unsigned char b) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Pin config virtual void PinSetMode(int pin, IO::PinMode mode) { printf("%s: timeMs=%ld, pin=%d, mode=%s\n", __PRETTY_FUNCTION__, TimerCurrentMs(), pin, (mode == IO::InputPin) ? "INPUT" : "OUTPUT"); MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual void PinSetPullup(int pin, IO::PullupMode mode) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Digital virtual void DigitalWrite(int pin, bool val) { printf("%s: timeMs=%ld, pin=%d, value=%s\n", __PRETTY_FUNCTION__, TimerCurrentMs(), pin, val ? "ON" : "OFF"); MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual bool DigitalRead(int pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return false; } // Analog virtual long AnalogRead(int pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual void PwmWrite(int pin, long dutyPercent) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Timer virtual long TimerCurrentMs() { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return timeMs; } virtual void AttachExternalInterrupt(int interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } }; void emscripten_main() { EmscriptenIO io; Network network(&io); HostCommunication controller; NullHostTransport transport; transport.setup(&io, &controller); network.emitDebug(DebugLevelInfo, DebugProgramStart); controller.setup(&network, &transport); loadFromEEPROM(&controller); for (int i=0; i<50; i++) { transport.runTick(); network.runTick(); io.timeMs += 100; // Fast-forward time } } int main(void) { emscripten_main(); return 0; }
/* MicroFlo - Flow-Based Programming for microcontrollers * Copyright (c) 2013 Jon Nordby <[email protected]> * MicroFlo may be freely distributed under the MIT license * * Note: Arduino is under the LGPL license. */ #include "microflo.h" #include <stdio.h> #include <unistd.h> #include <stddef.h> #include <stdlib.h> #include "microflo.hpp" void loadFromEEPROM(HostCommunication *controller) { for (unsigned int i=0; i<sizeof(graph); i++) { unsigned char c = graph[i]; controller->parseByte(c); } } #include <new> void * operator new(size_t n) throw(std::bad_alloc) { void * const p = malloc(n); if (!p) { throw std::bad_alloc(); } return p; } void operator delete(void * p) throw() { free(p); } void print_foo(int ignored) { printf("FOO\n"); } extern "C" { void emscripten_main(); } class EmscriptenIO : public IO { public: long timeMs; EmscriptenIO() { timeMs = 0; } ~EmscriptenIO() {} // Serial virtual void SerialBegin(int serialDevice, int baudrate) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual long SerialDataAvailable(int serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual unsigned char SerialRead(int serialDevice) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return '\0'; } virtual void SerialWrite(int serialDevice, unsigned char b) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Pin config virtual void PinSetMode(int pin, IO::PinMode mode) { printf("%s: timeMs=%ld, pin=%d, mode=%s\n", __PRETTY_FUNCTION__, TimerCurrentMs(), pin, (mode == IO::InputPin) ? "INPUT" : "OUTPUT"); MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual void PinSetPullup(int pin, IO::PullupMode mode) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Digital virtual void DigitalWrite(int pin, bool val) { printf("%s: timeMs=%ld, pin=%d, value=%s\n", __PRETTY_FUNCTION__, TimerCurrentMs(), pin, val ? "ON" : "OFF"); MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } virtual bool DigitalRead(int pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return false; } // Analog virtual long AnalogRead(int pin) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return 0; } virtual void PwmWrite(int pin, long dutyPercent) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } // Timer virtual long TimerCurrentMs() { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); return timeMs; } virtual void AttachExternalInterrupt(int interrupt, IO::Interrupt::Mode mode, IOInterruptFunction func, void *user) { MICROFLO_DEBUG(debug, DebugLevelError, DebugIoOperationNotImplemented); } }; void emscripten_main() { EmscriptenIO io; Network network(&io); HostCommunication controller; NullHostTransport transport; transport.setup(&io, &controller); controller.setup(&network, &transport); loadFromEEPROM(&controller); for (int i=0; i<50; i++) { transport.runTick(); network.runTick(); io.timeMs += 100; // Fast-forward time } } int main(void) { emscripten_main(); return 0; }
Fix compile error in Emscripten
runtime: Fix compile error in Emscripten
C++
mit
microflo/microflo,microflo/microflo,microflo/microflo,microflo/microflo,rraallvv/microflo,rraallvv/microflo,microflo/microflo,rraallvv/microflo,microflo/microflo,rraallvv/microflo
f1ecb0b1e31a8981cbd4e5a303dd9883de47dee6
protocols/qq/libeva.cpp
protocols/qq/libeva.cpp
#include "libeva.h" #include "md5.h" #include "crypt.h" #include <arpa/inet.h> // FIXME: remove me after debug. #include <stdio.h> namespace Eva { static const char login_16_51 [] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0xc0, 0xf8, 0xc4, 0xbe, 0x3b, 0xee, 0x57, 0x92, 0xd2, 0x42, 0xa6, 0xbe, 0x41, 0x98, 0x97, 0xb4 }; static const char login_53_68 []= { 0xce, 0x11, 0xd5, 0xd9, 0x97, 0x46, 0xac, 0x41, 0xa5, 0x01, 0xb2, 0xf5, 0xe9, 0x62, 0x8e, 0x07 }; static const char login_94_193 []= { 0x01, 0x40, 0x01, 0xb6, 0xfb, 0x54, 0x6e, 0x00, 0x10, 0x33, 0x11, 0xa3, 0xab, 0x86, 0x86, 0xff, 0x5b, 0x90, 0x5c, 0x74, 0x5d, 0xf1, 0x47, 0xbf, 0xcf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const char init_key[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; ByteArray header( int id, short const command, short const sequence ) { // CODE DEBT: udp does not have the lenght placeholder! ByteArray data(13); data += '\0'; data += '\0'; data += Head; data += htons(Version); data += htons(command); data += htons(sequence); data += htonl(id); return data; } void setLength( ByteArray& data ) { data.copyAt(0, htons(data.size()) ); } int rand(void) { return 0xdead; } ByteArray doMd5( const ByteArray& text ) { ByteArray code( Md5KeyLength ); md5_state_t ctx; md5_init( &ctx ); md5_append( &ctx, (md5_byte_t*) text.data(), text.size() ); md5_finish( &ctx, (md5_byte_t*)code.data() ); code.setSize( Md5KeyLength ); return code; } inline void encrypt64( unsigned char* plain, unsigned char* plain_pre, unsigned char* key, unsigned char* crypted, unsigned char* crypted_pre, bool& isHeader ) { int i; for( i = 0; i< 8; i++ ) plain[i] ^= isHeader ? plain_pre[i] : crypted_pre[i]; TEA::encipher( (unsigned int*) plain, (unsigned int*) key, (unsigned int*) crypted ); for( i = 0; i< 8; i++ ) crypted[i] ^= plain_pre[i]; memcpy( plain_pre, plain, 8 ); isHeader = false; } inline void decrypt64( unsigned char* crypt, unsigned char* crypt_pre, unsigned char* key, unsigned char* decrypted, int len) { bool isWrapped = false; for( int i = 0; i< 8; i++ ) { if( i >= len ) { isWrapped = true; break; } decrypted[i] ^= crypt[i]; } if( !isWrapped ) TEA::decipher( (unsigned int*) decrypted, (unsigned int*) key, (unsigned int*) decrypted ); } // Interface for application // Utilities ByteArray loginToken( const ByteArray& packet ) { char reply = packet.data()[0]; char length = packet.data()[1]; ByteArray data(length); if( reply != LoginTokenOK ) return data; data.append( packet.data()+2, length ); return data; } ByteArray QQHash( const ByteArray& text ) { return doMd5( doMd5( text ) ); } ByteArray encrypt( const ByteArray& text, const ByteArray& key ) { unsigned char plain[8], /* plain text buffer*/ plain_pre[8], /* plain text buffer, previous 8 bytes*/ crypted[8], /* crypted text*/ crypted_pre[8]; /* crypted test, previous 8 bytes*/ int pos, len, i; bool isHeader = true; /* header is one byte*/ ByteArray encoded( text.size() + 32 ); pos = ( text.size() + 10 ) % 8; if( pos ) pos = 8 - pos; // Prepare the first 8 bytes: plain[0] = ( rand() & 0xf8 ) | pos; memset( plain_pre, 0, 8 ); memset( plain+1, rand()& 0xff, pos++ ); // pad at most 2 bytes len = min( 8-pos, 2 ); for( i = 0; i< len; i++ ) plain[ pos++ ] = rand() & 0xff; for( i = 0; i< text.size(); i++ ) { if( pos == 8 ) { encrypt64( plain, plain_pre, (unsigned char*)key.data(), crypted, crypted_pre, isHeader ); pos = 0; encoded.append( (char*)crypted, 8 ); memcpy( crypted_pre, crypted, 8 ); } else plain[pos++] = text.data()[i]; } for( i = 0; i< 7; i++ ) { if( pos == 8 ) { encrypt64( plain, plain_pre, (unsigned char*)key.data(), crypted, crypted_pre, isHeader ); encoded.append( (char*)crypted, 8 ); break; } else plain[pos++] = 0; } return encoded; } ByteArray decrypt( const ByteArray& code, const ByteArray& key ) { unsigned char decrypted[8], m[8], *crypt_pre, *crypt; char* outp; int pos, len, i; if( code.size() < 16 || code.size() % 8 ) return ByteArray(0); TEA::decipher( (unsigned int*) code.data(), (unsigned int*) key.data(), (unsigned int*) decrypted ); pos = decrypted[0] & 0x7; len = code.size() - pos - 10; if( len < 0 ) return ByteArray(0); ByteArray text(len); memset( m, 0, 8 ); crypt_pre = m; crypt = (unsigned char*)code.data() + 8; pos ++; for( i = 0; i< 2; i++ ) { if( pos < 8 ) pos ++; if( pos == 8 ) { crypt_pre = (unsigned char*)code.data(); decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, code.size() - 8 ); break; } } outp = text.data(); while( len > 0 ) { if( pos < 8 ) { *outp = crypt_pre[pos] ^ decrypted[pos]; outp ++; pos ++; len --; } else { crypt_pre = crypt - 8; decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, len ); } } for( i = 0; i< 7; i++ ) { if( pos == 8 ) { crypt_pre = crypt; decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, len ); break; } else { if( crypt[pos] ^ decrypted[pos] ) return ByteArray(0); pos ++; } } return text; } // Core functions ByteArray requestLoginToken( int id, short const sequence ) { ByteArray data(16); data += header(id, RequestLoginToken, sequence); data += '\0'; data += Tail; setLength( data ); return data; } ByteArray login( int id, short const sequence, const ByteArray& key, const ByteArray& token, char const loginMode ) { ByteArray login(LoginLength); ByteArray data(MaxPacketLength); ByteArray initKey( (char*)init_key, 16 ); ByteArray nil(0); login += encrypt( nil, key ); login.append( login_16_51, 36 ); login += loginMode; login.append( login_53_68, 16 ); login += (char) (token.size()); login += token; login.append( login_94_193, 100 ); memset( login.data()+login.size(), 0, login.capacity()-login.size() ); // dump the login for( int i = 0; i< login.capacity(); i++ ) fprintf( stderr, "%x ", ((unsigned char*)login.data())[i] ); fprintf( stderr, "\n" ); data += header( id, Login, sequence ); data += initKey; data += encrypt( login, initKey ); data += Tail; setLength( data ); initKey.release(); // static data, no need to free return data; } }
#include "libeva.h" #include "md5.h" #include "crypt.h" #include <arpa/inet.h> // FIXME: remove me after debug. #include <stdio.h> namespace Eva { static const char login_16_51 [] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0xc0, 0xf8, 0xc4, 0xbe, 0x3b, 0xee, 0x57, 0x92, 0xd2, 0x42, 0xa6, 0xbe, 0x41, 0x98, 0x97, 0xb4 }; static const char login_53_68 []= { 0xce, 0x11, 0xd5, 0xd9, 0x97, 0x46, 0xac, 0x41, 0xa5, 0x01, 0xb2, 0xf5, 0xe9, 0x62, 0x8e, 0x07 }; static const char login_94_193 []= { 0x01, 0x40, 0x01, 0xb6, 0xfb, 0x54, 0x6e, 0x00, 0x10, 0x33, 0x11, 0xa3, 0xab, 0x86, 0x86, 0xff, 0x5b, 0x90, 0x5c, 0x74, 0x5d, 0xf1, 0x47, 0xbf, 0xcf, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; static const char init_key[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; ByteArray header( int id, short const command, short const sequence ) { // CODE DEBT: udp does not have the lenght placeholder! ByteArray data(13); data += '\0'; data += '\0'; data += Head; data += htons(Version); data += htons(command); data += htons(sequence); data += htonl(id); return data; } void setLength( ByteArray& data ) { data.copyAt(0, htons(data.size()) ); } int rand(void) { return 0xdead; } ByteArray doMd5( const ByteArray& text ) { ByteArray code( Md5KeyLength ); md5_state_t ctx; md5_init( &ctx ); md5_append( &ctx, (md5_byte_t*) text.data(), text.size() ); md5_finish( &ctx, (md5_byte_t*)code.data() ); code.setSize( Md5KeyLength ); return code; } inline void encrypt64( unsigned char* plain, unsigned char* plain_pre, unsigned char* key, unsigned char* crypted, unsigned char* crypted_pre, bool& isHeader ) { int i; for( i = 0; i< 8; i++ ) plain[i] ^= isHeader ? plain_pre[i] : crypted_pre[i]; TEA::encipher( (unsigned int*) plain, (unsigned int*) key, (unsigned int*) crypted ); for( i = 0; i< 8; i++ ) crypted[i] ^= plain_pre[i]; memcpy( plain_pre, plain, 8 ); memcpy( crypted_pre, crypted, 8 ); isHeader = false; } inline void decrypt64( unsigned char* crypt, unsigned char* crypt_pre, unsigned char* key, unsigned char* decrypted, int len) { bool isWrapped = false; for( int i = 0; i< 8; i++ ) { if( i >= len ) { isWrapped = true; break; } decrypted[i] ^= crypt[i]; } if( !isWrapped ) TEA::decipher( (unsigned int*) decrypted, (unsigned int*) key, (unsigned int*) decrypted ); } // Interface for application // Utilities ByteArray loginToken( const ByteArray& packet ) { char reply = packet.data()[0]; char length = packet.data()[1]; ByteArray data(length); if( reply != LoginTokenOK ) return data; data.append( packet.data()+2, length ); return data; } ByteArray QQHash( const ByteArray& text ) { return doMd5( doMd5( text ) ); } ByteArray encrypt( const ByteArray& text, const ByteArray& key ) { unsigned char plain[8], /* plain text buffer*/ plain_pre[8], /* plain text buffer, previous 8 bytes*/ crypted[8], /* crypted text*/ crypted_pre[8]; /* crypted test, previous 8 bytes*/ int pos, len, i; bool isHeader = true; /* header is one byte*/ ByteArray encoded( text.size() + 32 ); pos = ( text.size() + 10 ) % 8; if( pos ) pos = 8 - pos; // Prepare the first 8 bytes: plain[0] = ( rand() & 0xf8 ) | pos; memset( plain_pre, 0, 8 ); memset( plain+1, rand()& 0xff, pos++ ); // pad 2 bytes for( i = 0; i< 2; i++ ) { if( pos < 8 ) plain[pos++] = rand() & 0xff; if( pos == 8 ) { encrypt64( plain, plain_pre, (unsigned char*)key.data(), crypted, crypted_pre, isHeader ); pos = 0; encoded.append( (char*)crypted, 8 ); } } for( i = 0; i< text.size(); i++ ) { if( pos < 8 ) plain[pos++] = text.data()[i]; if( pos == 8 ) { encrypt64( plain, plain_pre, (unsigned char*)key.data(), crypted, crypted_pre, isHeader ); pos = 0; encoded.append( (char*)crypted, 8 ); } } for( i = 0; i< 7; i++ ) { if( pos < 8 ) plain[pos++] = 0; if( pos == 8 ) { encrypt64( plain, plain_pre, (unsigned char*)key.data(), crypted, crypted_pre, isHeader ); encoded.append( (char*)crypted, 8 ); break; } } return encoded; } ByteArray decrypt( const ByteArray& code, const ByteArray& key ) { unsigned char decrypted[8], m[8], *crypt_pre, *crypt; char* outp; int pos, len, i; if( code.size() < 16 || code.size() % 8 ) return ByteArray(0); TEA::decipher( (unsigned int*) code.data(), (unsigned int*) key.data(), (unsigned int*) decrypted ); pos = decrypted[0] & 0x7; len = code.size() - pos - 10; if( len < 0 ) return ByteArray(0); ByteArray text(len); memset( m, 0, 8 ); crypt_pre = m; crypt = (unsigned char*)code.data() + 8; pos ++; for( i = 0; i< 2; i++ ) { if( pos < 8 ) pos ++; if( pos == 8 ) { crypt_pre = (unsigned char*)code.data(); decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, code.size() - 8 ); break; } } outp = text.data(); while( len > 0 ) { if( pos < 8 ) { *outp = crypt_pre[pos] ^ decrypted[pos]; outp ++; pos ++; len --; } else { crypt_pre = crypt - 8; decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, len ); } } for( i = 0; i< 7; i++ ) { if( pos == 8 ) { crypt_pre = crypt; decrypt64( crypt, crypt_pre, (unsigned char*) key.data(), decrypted, len ); break; } else { if( crypt[pos] ^ decrypted[pos] ) return ByteArray(0); pos ++; } } return text; } // Core functions ByteArray requestLoginToken( int id, short const sequence ) { ByteArray data(16); data += header(id, RequestLoginToken, sequence); data += '\0'; data += Tail; setLength( data ); return data; } ByteArray login( int id, short const sequence, const ByteArray& key, const ByteArray& token, char const loginMode ) { ByteArray login(LoginLength); ByteArray data(MaxPacketLength); ByteArray initKey( (char*)init_key, 16 ); ByteArray nil(0); login += encrypt( nil, key ); login.append( login_16_51, 36 ); login += loginMode; login.append( login_53_68, 16 ); login += (char) (token.size()); login += token; login.append( login_94_193, 100 ); memset( login.data()+login.size(), 0, login.capacity()-login.size() ); // dump the login for( int i = 0; i< login.capacity(); i++ ) fprintf( stderr, "%x ", ((unsigned char*)login.data())[i] ); fprintf( stderr, "\n" ); data += header( id, Login, sequence ); data += initKey; data += encrypt( login, initKey ); data += Tail; setLength( data ); initKey.release(); // static data, no need to free return data; } }
Encrypt bug for null text fixes. TODO: check the output of login ecryption.
Encrypt bug for null text fixes. TODO: check the output of login ecryption. svn path=/trunk/KDE/kdenetwork/kopete/; revision=558933
C++
lgpl-2.1
josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete,josh-wambua/kopete,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,Jtalk/kopete-fork-xep0136,josh-wambua/kopete
6e857a6fa7c56a20d1dd7e6200357128955159ae
map/feature_styler.cpp
map/feature_styler.cpp
#include "feature_styler.hpp" #include "geometry_processors.hpp" #include "proto_to_styles.hpp" #include "../indexer/drawing_rules.hpp" #include "../indexer/feature.hpp" #include "../indexer/feature_visibility.hpp" #ifdef OMIM_PRODUCTION #include "../indexer/drules_struct_lite.pb.h" #else #include "../indexer/drules_struct.pb.h" #endif #include "../geometry/screenbase.hpp" #include "../graphics/glyph_cache.hpp" #include "../base/stl_add.hpp" #include "../std/iterator_facade.hpp" namespace { struct less_depth { bool operator() (di::DrawRule const & r1, di::DrawRule const & r2) const { return (r1.m_depth < r2.m_depth); } }; } namespace di { uint32_t DrawRule::GetID(size_t threadSlot) const { return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot)); } void DrawRule::SetID(size_t threadSlot, uint32_t id) const { m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id); } FeatureStyler::FeatureStyler(FeatureType const & f, int const zoom, double const visualScale, graphics::GlyphCache * glyphCache, ScreenBase const * convertor, m2::RectD const * rect) : m_hasPathText(false), m_visualScale(visualScale), m_glyphCache(glyphCache), m_convertor(convertor), m_rect(rect) { vector<drule::Key> keys; string names; // for debug use only, in release it's empty pair<int, bool> type = feature::GetDrawRule(f, zoom, keys, names); // don't try to do anything to invisible feature if (keys.empty()) return; m_hasLineStyles = false; m_geometryType = type.first; m_isCoastline = type.second; f.GetPreferredNames(m_primaryText, m_secondaryText); // Get house number if feature has one. string houseNumber = f.GetHouseNumber(); if (!houseNumber.empty()) { if (m_primaryText.empty()) houseNumber.swap(m_primaryText); else m_primaryText = m_primaryText + " (" + houseNumber + ")"; } m_refText = f.GetRoadNumber(); double const population = static_cast<double>(f.GetPopulation()); if (population == 1) m_popRank = 0.0; else { double const upperBound = 3.0E6; m_popRank = min(upperBound, population) / upperBound / 4; } // low zoom heuristics if (zoom <= 5) { // hide superlong names on low zoom if (m_primaryText.size() > 50) m_primaryText.clear(); } double area = 0.0; if (m_geometryType != feature::GEOM_POINT) { m2::RectD const bbox = f.GetLimitRect(zoom); area = bbox.SizeX() * bbox.SizeY(); } double priorityModifier; if (area != 0) priorityModifier = min(1., area*10000.); // making area larger so it's not lost on double conversions else priorityModifier = static_cast<double>(population) / 7E9; // dividing by planet population to get priorityModifier < 1 drule::MakeUnique(keys); int layer = f.GetLayer(); bool isTransparent = false; if (layer == feature::LAYER_TRANSPARENT_TUNNEL) layer = 0; bool hasIcon = false; bool hasCaptionWithoutOffset = false; m_fontSize = 0; size_t const count = keys.size(); m_rules.resize(count); for (size_t i = 0; i < count; ++i) { double depth = keys[i].m_priority; if (layer != 0) depth = (layer * drule::layer_base_priority) + fmod(depth, drule::layer_base_priority); if (keys[i].m_type == drule::symbol) hasIcon = true; if ((keys[i].m_type == drule::caption) || (keys[i].m_type == drule::symbol) || (keys[i].m_type == drule::circle) || (keys[i].m_type == drule::pathtext) || (keys[i].m_type == drule::waymarker)) { // show labels of larger objects first depth += priorityModifier; } else if (keys[i].m_type == drule::area) { // show smaller polygons on top depth -= priorityModifier; } if (!m_hasLineStyles && (keys[i].m_type == drule::line)) m_hasLineStyles = true; m_rules[i] = di::DrawRule( drule::rules().Find(keys[i]), depth, isTransparent); if ((m_geometryType == feature::GEOM_LINE) && !m_hasPathText && !m_primaryText.empty()) if (m_rules[i].m_rule->GetCaption(0) != 0) { m_hasPathText = true; if (!FilterTextSize(m_rules[i].m_rule)) m_fontSize = max(m_fontSize, GetTextFontSize(m_rules[i].m_rule)); } if (keys[i].m_type == drule::caption) if (m_rules[i].m_rule->GetCaption(0) != 0) hasCaptionWithoutOffset = !m_rules[i].m_rule->GetCaption(0)->has_offset_y(); } // placing a text on the path if (m_hasPathText && (m_fontSize != 0)) { typedef gp::filter_screenpts_adapter<gp::get_path_intervals> functor_t; functor_t::params p; p.m_convertor = m_convertor; p.m_rect = m_rect; p.m_intervals = &m_intervals; functor_t fun(p); f.ForEachPointRef(fun, zoom); LayoutTexts(fun.m_length); } if (hasIcon && hasCaptionWithoutOffset) // we need to delete symbol style (single one due to MakeUnique call above) for (size_t i = 0; i < count; ++i) { if (keys[i].m_type == drule::symbol) { m_rules[i] = m_rules[m_rules.size() - 1]; m_rules.pop_back(); break; } } sort(m_rules.begin(), m_rules.end(), less_depth()); } typedef pair<double, double> RangeT; template <class IterT> class RangeIterT : public iterator_facade<RangeIterT<IterT>, RangeT, forward_traversal_tag, RangeT> { IterT m_iter; public: RangeIterT(IterT iter) : m_iter(iter) {} RangeT dereference() const { IterT next = m_iter; ++next; return RangeT(*m_iter, *next); } bool equal(RangeIterT const & r) const { return (m_iter == r.m_iter); } void increment() { ++m_iter; ++m_iter; } }; template <class ContT> class RangeInserter { ContT & m_cont; public: RangeInserter(ContT & cont) : m_cont(cont) {} RangeInserter & operator*() { return *this; } RangeInserter & operator++(int) { return *this; } RangeInserter & operator=(RangeT const & r) { m_cont.push_back(r.first); m_cont.push_back(r.second); return *this; } }; void FeatureStyler::LayoutTexts(double pathLength) { double const textLength = m_glyphCache->getTextLength(m_fontSize, GetPathName()); /// @todo Choose best constant for minimal space. double const emptySize = max(200 * m_visualScale, textLength); // multiply on factor because tiles will be rendered in smaller scales double const minPeriodSize = 1.5 * (emptySize + textLength); size_t textCnt = 0; double firstTextOffset = 0; if (pathLength > textLength) { textCnt = ceil((pathLength - textLength) / minPeriodSize); firstTextOffset = 0.5 * (pathLength - (textCnt * textLength + (textCnt - 1) * emptySize)); } if (textCnt != 0 && !m_intervals.empty()) { buffer_vector<RangeT, 8> deadZones; for (size_t i = 0; i < textCnt; ++i) { double const deadZoneStart = firstTextOffset + minPeriodSize * i; double const deadZoneEnd = deadZoneStart + textLength; if (deadZoneStart > m_intervals.back()) break; deadZones.push_back(make_pair(deadZoneStart, deadZoneEnd)); } if (!deadZones.empty()) { buffer_vector<double, 16> res; // accumulate text layout intervals with cliping intervals typedef RangeIterT<ClipIntervalsT::iterator> IterT; AccumulateIntervals1With2(IterT(m_intervals.begin()), IterT(m_intervals.end()), deadZones.begin(), deadZones.end(), RangeInserter<ClipIntervalsT>(res)); m_intervals = res; ASSERT_EQUAL(m_intervals.size() % 2, 0, ()); // get final text offsets (belongs to final clipping intervals) size_t i = 0; size_t j = 0; while (i != deadZones.size() && j != m_intervals.size()) { ASSERT_LESS(deadZones[i].first, deadZones[i].second, ()); ASSERT_LESS(m_intervals[j], m_intervals[j+1], ()); if (deadZones[i].first < m_intervals[j]) { ++i; continue; } if (m_intervals[j+1] <= deadZones[i].first) { j += 2; continue; } ASSERT_LESS_OR_EQUAL(m_intervals[j], deadZones[i].first, ()); ASSERT_LESS_OR_EQUAL(deadZones[i].second, m_intervals[j+1], ()); m_offsets.push_back(deadZones[i].first); ++i; } } } } string const FeatureStyler::GetPathName() const { if (m_secondaryText.empty()) return m_primaryText; else return m_primaryText + " " + m_secondaryText; } bool FeatureStyler::IsEmpty() const { return m_rules.empty(); } uint8_t FeatureStyler::GetTextFontSize(drule::BaseRule const * pRule) const { return pRule->GetCaption(0)->height() * m_visualScale; } bool FeatureStyler::FilterTextSize(drule::BaseRule const * pRule) const { if (pRule->GetCaption(0)) return (GetFontSize(pRule->GetCaption(0)) < 3); else { // this rule is not a caption at all return true; } } }
#include "feature_styler.hpp" #include "geometry_processors.hpp" #include "proto_to_styles.hpp" #include "../indexer/drawing_rules.hpp" #include "../indexer/feature.hpp" #include "../indexer/feature_visibility.hpp" #ifdef OMIM_PRODUCTION #include "../indexer/drules_struct_lite.pb.h" #else #include "../indexer/drules_struct.pb.h" #endif #include "../geometry/screenbase.hpp" #include "../graphics/glyph_cache.hpp" #include "../base/stl_add.hpp" #include "../std/iterator_facade.hpp" namespace { struct less_depth { bool operator() (di::DrawRule const & r1, di::DrawRule const & r2) const { return (r1.m_depth < r2.m_depth); } }; } namespace di { uint32_t DrawRule::GetID(size_t threadSlot) const { return (m_transparent ? m_rule->GetID2(threadSlot) : m_rule->GetID(threadSlot)); } void DrawRule::SetID(size_t threadSlot, uint32_t id) const { m_transparent ? m_rule->SetID2(threadSlot, id) : m_rule->SetID(threadSlot, id); } FeatureStyler::FeatureStyler(FeatureType const & f, int const zoom, double const visualScale, graphics::GlyphCache * glyphCache, ScreenBase const * convertor, m2::RectD const * rect) : m_hasPathText(false), m_visualScale(visualScale), m_glyphCache(glyphCache), m_convertor(convertor), m_rect(rect) { vector<drule::Key> keys; string names; // for debug use only, in release it's empty pair<int, bool> type = feature::GetDrawRule(f, zoom, keys, names); // don't try to do anything to invisible feature if (keys.empty()) return; m_hasLineStyles = false; m_geometryType = type.first; m_isCoastline = type.second; f.GetPreferredNames(m_primaryText, m_secondaryText); // Get house number if feature has one. string houseNumber = f.GetHouseNumber(); if (!houseNumber.empty()) { if (m_primaryText.empty()) houseNumber.swap(m_primaryText); else m_primaryText = m_primaryText + " (" + houseNumber + ")"; } m_refText = f.GetRoadNumber(); double const population = static_cast<double>(f.GetPopulation()); if (population == 1) m_popRank = 0.0; else { double const upperBound = 3.0E6; m_popRank = min(upperBound, population) / upperBound / 4; } // low zoom heuristics if (zoom <= 5) { // hide superlong names on low zoom if (m_primaryText.size() > 50) m_primaryText.clear(); } double area = 0.0; if (m_geometryType != feature::GEOM_POINT) { m2::RectD const bbox = f.GetLimitRect(zoom); area = bbox.SizeX() * bbox.SizeY(); } double priorityModifier; if (area != 0) priorityModifier = min(1., area*10000.); // making area larger so it's not lost on double conversions else priorityModifier = static_cast<double>(population) / 7E9; // dividing by planet population to get priorityModifier < 1 drule::MakeUnique(keys); int layer = f.GetLayer(); bool isTransparent = false; if (layer == feature::LAYER_TRANSPARENT_TUNNEL) layer = 0; bool hasIcon = false; bool hasCaptionWithoutOffset = false; m_fontSize = 0; size_t const count = keys.size(); m_rules.resize(count); for (size_t i = 0; i < count; ++i) { double depth = keys[i].m_priority; if ((layer != 0) && (depth < 19000)) depth = (layer * drule::layer_base_priority) + fmod(depth, drule::layer_base_priority); if (keys[i].m_type == drule::symbol) hasIcon = true; if ((keys[i].m_type == drule::caption) || (keys[i].m_type == drule::symbol) || (keys[i].m_type == drule::circle) || (keys[i].m_type == drule::pathtext) || (keys[i].m_type == drule::waymarker)) { // show labels of larger objects first depth += priorityModifier; } else if (keys[i].m_type == drule::area) { // show smaller polygons on top depth -= priorityModifier; } if (!m_hasLineStyles && (keys[i].m_type == drule::line)) m_hasLineStyles = true; m_rules[i] = di::DrawRule( drule::rules().Find(keys[i]), depth, isTransparent); if ((m_geometryType == feature::GEOM_LINE) && !m_hasPathText && !m_primaryText.empty()) if (m_rules[i].m_rule->GetCaption(0) != 0) { m_hasPathText = true; if (!FilterTextSize(m_rules[i].m_rule)) m_fontSize = max(m_fontSize, GetTextFontSize(m_rules[i].m_rule)); } if (keys[i].m_type == drule::caption) if (m_rules[i].m_rule->GetCaption(0) != 0) hasCaptionWithoutOffset = !m_rules[i].m_rule->GetCaption(0)->has_offset_y(); } // placing a text on the path if (m_hasPathText && (m_fontSize != 0)) { typedef gp::filter_screenpts_adapter<gp::get_path_intervals> functor_t; functor_t::params p; p.m_convertor = m_convertor; p.m_rect = m_rect; p.m_intervals = &m_intervals; functor_t fun(p); f.ForEachPointRef(fun, zoom); LayoutTexts(fun.m_length); } if (hasIcon && hasCaptionWithoutOffset) // we need to delete symbol style (single one due to MakeUnique call above) for (size_t i = 0; i < count; ++i) { if (keys[i].m_type == drule::symbol) { m_rules[i] = m_rules[m_rules.size() - 1]; m_rules.pop_back(); break; } } sort(m_rules.begin(), m_rules.end(), less_depth()); } typedef pair<double, double> RangeT; template <class IterT> class RangeIterT : public iterator_facade<RangeIterT<IterT>, RangeT, forward_traversal_tag, RangeT> { IterT m_iter; public: RangeIterT(IterT iter) : m_iter(iter) {} RangeT dereference() const { IterT next = m_iter; ++next; return RangeT(*m_iter, *next); } bool equal(RangeIterT const & r) const { return (m_iter == r.m_iter); } void increment() { ++m_iter; ++m_iter; } }; template <class ContT> class RangeInserter { ContT & m_cont; public: RangeInserter(ContT & cont) : m_cont(cont) {} RangeInserter & operator*() { return *this; } RangeInserter & operator++(int) { return *this; } RangeInserter & operator=(RangeT const & r) { m_cont.push_back(r.first); m_cont.push_back(r.second); return *this; } }; void FeatureStyler::LayoutTexts(double pathLength) { double const textLength = m_glyphCache->getTextLength(m_fontSize, GetPathName()); /// @todo Choose best constant for minimal space. double const emptySize = max(200 * m_visualScale, textLength); // multiply on factor because tiles will be rendered in smaller scales double const minPeriodSize = 1.5 * (emptySize + textLength); size_t textCnt = 0; double firstTextOffset = 0; if (pathLength > textLength) { textCnt = ceil((pathLength - textLength) / minPeriodSize); firstTextOffset = 0.5 * (pathLength - (textCnt * textLength + (textCnt - 1) * emptySize)); } if (textCnt != 0 && !m_intervals.empty()) { buffer_vector<RangeT, 8> deadZones; for (size_t i = 0; i < textCnt; ++i) { double const deadZoneStart = firstTextOffset + minPeriodSize * i; double const deadZoneEnd = deadZoneStart + textLength; if (deadZoneStart > m_intervals.back()) break; deadZones.push_back(make_pair(deadZoneStart, deadZoneEnd)); } if (!deadZones.empty()) { buffer_vector<double, 16> res; // accumulate text layout intervals with cliping intervals typedef RangeIterT<ClipIntervalsT::iterator> IterT; AccumulateIntervals1With2(IterT(m_intervals.begin()), IterT(m_intervals.end()), deadZones.begin(), deadZones.end(), RangeInserter<ClipIntervalsT>(res)); m_intervals = res; ASSERT_EQUAL(m_intervals.size() % 2, 0, ()); // get final text offsets (belongs to final clipping intervals) size_t i = 0; size_t j = 0; while (i != deadZones.size() && j != m_intervals.size()) { ASSERT_LESS(deadZones[i].first, deadZones[i].second, ()); ASSERT_LESS(m_intervals[j], m_intervals[j+1], ()); if (deadZones[i].first < m_intervals[j]) { ++i; continue; } if (m_intervals[j+1] <= deadZones[i].first) { j += 2; continue; } ASSERT_LESS_OR_EQUAL(m_intervals[j], deadZones[i].first, ()); ASSERT_LESS_OR_EQUAL(deadZones[i].second, m_intervals[j+1], ()); m_offsets.push_back(deadZones[i].first); ++i; } } } } string const FeatureStyler::GetPathName() const { if (m_secondaryText.empty()) return m_primaryText; else return m_primaryText + " " + m_secondaryText; } bool FeatureStyler::IsEmpty() const { return m_rules.empty(); } uint8_t FeatureStyler::GetTextFontSize(drule::BaseRule const * pRule) const { return pRule->GetCaption(0)->height() * m_visualScale; } bool FeatureStyler::FilterTextSize(drule::BaseRule const * pRule) const { if (pRule->GetCaption(0)) return (GetFontSize(pRule->GetCaption(0)) < 3); else { // this rule is not a caption at all return true; } } }
allow forced always-on-top for highest priorities
[map] allow forced always-on-top for highest priorities
C++
apache-2.0
dobriy-eeh/omim,victorbriz/omim,65apps/omim,milchakov/omim,TimurTarasenko/omim,Zverik/omim,albertshift/omim,vasilenkomike/omim,kw217/omim,matsprea/omim,UdjinM6/omim,kw217/omim,vng/omim,stangls/omim,stangls/omim,therearesomewhocallmetim/omim,lydonchandra/omim,Transtech/omim,65apps/omim,guard163/omim,sidorov-panda/omim,wersoo/omim,milchakov/omim,mapsme/omim,TimurTarasenko/omim,AlexanderMatveenko/omim,syershov/omim,gardster/omim,dkorolev/omim,guard163/omim,65apps/omim,bykoianko/omim,goblinr/omim,guard163/omim,matsprea/omim,andrewshadura/omim,ygorshenin/omim,darina/omim,AlexanderMatveenko/omim,sidorov-panda/omim,programming086/omim,mpimenov/omim,simon247/omim,alexzatsepin/omim,lydonchandra/omim,dkorolev/omim,UdjinM6/omim,trashkalmar/omim,TimurTarasenko/omim,felipebetancur/omim,bykoianko/omim,gardster/omim,krasin/omim,AlexanderMatveenko/omim,kw217/omim,darina/omim,andrewshadura/omim,felipebetancur/omim,darina/omim,Zverik/omim,krasin/omim,yunikkk/omim,simon247/omim,therearesomewhocallmetim/omim,trashkalmar/omim,dkorolev/omim,augmify/omim,mgsergio/omim,AlexanderMatveenko/omim,matsprea/omim,UdjinM6/omim,dkorolev/omim,goblinr/omim,syershov/omim,mgsergio/omim,Volcanoscar/omim,yunikkk/omim,stangls/omim,dkorolev/omim,yunikkk/omim,vladon/omim,vladon/omim,VladiMihaylenko/omim,AlexanderMatveenko/omim,trashkalmar/omim,stangls/omim,matsprea/omim,VladiMihaylenko/omim,mgsergio/omim,victorbriz/omim,Komzpa/omim,Volcanoscar/omim,simon247/omim,goblinr/omim,wersoo/omim,goblinr/omim,syershov/omim,mpimenov/omim,trashkalmar/omim,programming086/omim,mpimenov/omim,Endika/omim,albertshift/omim,andrewshadura/omim,yunikkk/omim,yunikkk/omim,augmify/omim,vng/omim,ygorshenin/omim,igrechuhin/omim,rokuz/omim,kw217/omim,guard163/omim,simon247/omim,mpimenov/omim,programming086/omim,mapsme/omim,igrechuhin/omim,65apps/omim,darina/omim,gardster/omim,Transtech/omim,yunikkk/omim,Transtech/omim,rokuz/omim,mapsme/omim,TimurTarasenko/omim,mapsme/omim,mgsergio/omim,darina/omim,alexzatsepin/omim,programming086/omim,mpimenov/omim,Saicheg/omim,UdjinM6/omim,victorbriz/omim,rokuz/omim,darina/omim,mapsme/omim,lydonchandra/omim,65apps/omim,milchakov/omim,victorbriz/omim,therearesomewhocallmetim/omim,vladon/omim,Komzpa/omim,vladon/omim,milchakov/omim,jam891/omim,jam891/omim,mpimenov/omim,bykoianko/omim,TimurTarasenko/omim,Zverik/omim,Transtech/omim,syershov/omim,darina/omim,rokuz/omim,ygorshenin/omim,Zverik/omim,yunikkk/omim,trashkalmar/omim,programming086/omim,lydonchandra/omim,VladiMihaylenko/omim,vasilenkomike/omim,therearesomewhocallmetim/omim,felipebetancur/omim,lydonchandra/omim,goblinr/omim,Komzpa/omim,yunikkk/omim,syershov/omim,therearesomewhocallmetim/omim,Saicheg/omim,felipebetancur/omim,Zverik/omim,kw217/omim,dobriy-eeh/omim,Saicheg/omim,alexzatsepin/omim,wersoo/omim,albertshift/omim,Zverik/omim,ygorshenin/omim,jam891/omim,wersoo/omim,albertshift/omim,mapsme/omim,Transtech/omim,bykoianko/omim,mpimenov/omim,kw217/omim,sidorov-panda/omim,trashkalmar/omim,vng/omim,ygorshenin/omim,vng/omim,ygorshenin/omim,stangls/omim,vasilenkomike/omim,milchakov/omim,goblinr/omim,AlexanderMatveenko/omim,sidorov-panda/omim,UdjinM6/omim,andrewshadura/omim,rokuz/omim,alexzatsepin/omim,lydonchandra/omim,igrechuhin/omim,rokuz/omim,dobriy-eeh/omim,andrewshadura/omim,andrewshadura/omim,edl00k/omim,wersoo/omim,igrechuhin/omim,edl00k/omim,wersoo/omim,albertshift/omim,65apps/omim,mgsergio/omim,AlexanderMatveenko/omim,rokuz/omim,vng/omim,vasilenkomike/omim,Volcanoscar/omim,guard163/omim,sidorov-panda/omim,igrechuhin/omim,VladiMihaylenko/omim,Zverik/omim,igrechuhin/omim,stangls/omim,Volcanoscar/omim,Komzpa/omim,felipebetancur/omim,krasin/omim,igrechuhin/omim,Komzpa/omim,Transtech/omim,bykoianko/omim,ygorshenin/omim,albertshift/omim,edl00k/omim,VladiMihaylenko/omim,dobriy-eeh/omim,dobriy-eeh/omim,Saicheg/omim,Komzpa/omim,programming086/omim,mapsme/omim,Endika/omim,milchakov/omim,krasin/omim,gardster/omim,Zverik/omim,AlexanderMatveenko/omim,dobriy-eeh/omim,programming086/omim,UdjinM6/omim,sidorov-panda/omim,krasin/omim,Volcanoscar/omim,simon247/omim,matsprea/omim,dobriy-eeh/omim,bykoianko/omim,alexzatsepin/omim,mpimenov/omim,mpimenov/omim,matsprea/omim,wersoo/omim,TimurTarasenko/omim,vng/omim,65apps/omim,trashkalmar/omim,UdjinM6/omim,mapsme/omim,krasin/omim,edl00k/omim,Volcanoscar/omim,albertshift/omim,Volcanoscar/omim,trashkalmar/omim,gardster/omim,victorbriz/omim,Endika/omim,VladiMihaylenko/omim,victorbriz/omim,VladiMihaylenko/omim,andrewshadura/omim,vasilenkomike/omim,Saicheg/omim,Transtech/omim,syershov/omim,jam891/omim,bykoianko/omim,gardster/omim,Zverik/omim,alexzatsepin/omim,guard163/omim,guard163/omim,therearesomewhocallmetim/omim,albertshift/omim,alexzatsepin/omim,lydonchandra/omim,Endika/omim,Komzpa/omim,mapsme/omim,mapsme/omim,VladiMihaylenko/omim,Zverik/omim,goblinr/omim,augmify/omim,Endika/omim,sidorov-panda/omim,victorbriz/omim,mapsme/omim,igrechuhin/omim,vng/omim,therearesomewhocallmetim/omim,jam891/omim,edl00k/omim,vasilenkomike/omim,VladiMihaylenko/omim,jam891/omim,syershov/omim,simon247/omim,dkorolev/omim,gardster/omim,alexzatsepin/omim,goblinr/omim,kw217/omim,kw217/omim,UdjinM6/omim,felipebetancur/omim,lydonchandra/omim,jam891/omim,felipebetancur/omim,stangls/omim,VladiMihaylenko/omim,kw217/omim,darina/omim,Endika/omim,krasin/omim,wersoo/omim,stangls/omim,jam891/omim,mpimenov/omim,kw217/omim,TimurTarasenko/omim,therearesomewhocallmetim/omim,bykoianko/omim,augmify/omim,lydonchandra/omim,trashkalmar/omim,Saicheg/omim,augmify/omim,augmify/omim,Transtech/omim,felipebetancur/omim,alexzatsepin/omim,gardster/omim,lydonchandra/omim,trashkalmar/omim,rokuz/omim,wersoo/omim,Transtech/omim,VladiMihaylenko/omim,darina/omim,guard163/omim,goblinr/omim,goblinr/omim,guard163/omim,mapsme/omim,stangls/omim,yunikkk/omim,albertshift/omim,65apps/omim,darina/omim,edl00k/omim,stangls/omim,augmify/omim,dobriy-eeh/omim,edl00k/omim,gardster/omim,gardster/omim,programming086/omim,augmify/omim,krasin/omim,Saicheg/omim,mgsergio/omim,alexzatsepin/omim,felipebetancur/omim,darina/omim,mpimenov/omim,rokuz/omim,dobriy-eeh/omim,felipebetancur/omim,rokuz/omim,syershov/omim,milchakov/omim,darina/omim,yunikkk/omim,augmify/omim,alexzatsepin/omim,Endika/omim,vasilenkomike/omim,Saicheg/omim,Endika/omim,therearesomewhocallmetim/omim,UdjinM6/omim,mpimenov/omim,matsprea/omim,igrechuhin/omim,dkorolev/omim,therearesomewhocallmetim/omim,programming086/omim,bykoianko/omim,mgsergio/omim,Endika/omim,vladon/omim,Transtech/omim,vng/omim,victorbriz/omim,vladon/omim,Volcanoscar/omim,matsprea/omim,simon247/omim,sidorov-panda/omim,bykoianko/omim,vng/omim,mgsergio/omim,edl00k/omim,bykoianko/omim,Transtech/omim,dobriy-eeh/omim,andrewshadura/omim,stangls/omim,AlexanderMatveenko/omim,Zverik/omim,goblinr/omim,syershov/omim,Endika/omim,rokuz/omim,programming086/omim,goblinr/omim,65apps/omim,Volcanoscar/omim,victorbriz/omim,trashkalmar/omim,milchakov/omim,Transtech/omim,ygorshenin/omim,andrewshadura/omim,krasin/omim,krasin/omim,Komzpa/omim,milchakov/omim,milchakov/omim,vasilenkomike/omim,65apps/omim,mgsergio/omim,andrewshadura/omim,mgsergio/omim,augmify/omim,vladon/omim,Zverik/omim,dobriy-eeh/omim,mapsme/omim,rokuz/omim,sidorov-panda/omim,vasilenkomike/omim,jam891/omim,simon247/omim,edl00k/omim,yunikkk/omim,albertshift/omim,rokuz/omim,vasilenkomike/omim,dobriy-eeh/omim,bykoianko/omim,matsprea/omim,dobriy-eeh/omim,milchakov/omim,ygorshenin/omim,ygorshenin/omim,jam891/omim,mgsergio/omim,milchakov/omim,simon247/omim,sidorov-panda/omim,alexzatsepin/omim,dkorolev/omim,65apps/omim,syershov/omim,vladon/omim,AlexanderMatveenko/omim,dkorolev/omim,syershov/omim,igrechuhin/omim,Volcanoscar/omim,ygorshenin/omim,matsprea/omim,Saicheg/omim,UdjinM6/omim,dkorolev/omim,vladon/omim,Komzpa/omim,TimurTarasenko/omim,syershov/omim,alexzatsepin/omim,mpimenov/omim,trashkalmar/omim,vng/omim,milchakov/omim,darina/omim,Saicheg/omim,goblinr/omim,vladon/omim,Komzpa/omim,mgsergio/omim,ygorshenin/omim,simon247/omim,guard163/omim,victorbriz/omim,VladiMihaylenko/omim,Zverik/omim,VladiMihaylenko/omim,edl00k/omim,wersoo/omim,TimurTarasenko/omim,syershov/omim,TimurTarasenko/omim,bykoianko/omim
10f6fbc731a7e8b77824ce035d8f4ca88eadbd22
src/datasource_cache.cpp
src/datasource_cache.cpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/debug.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/make_shared.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <iostream> #include <stdexcept> namespace mapnik { bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } datasource_ptr datasource_cache::create(const parameters& params, bool bind) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(std::string("Could not create datasource. Required ") + "parameter 'type' is missing"); } #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif datasource_ptr ds; std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { throw config_error(std::string("Could not create datasource. No plugin ") + "found for type '" + * type + "' (searched in: " + plugin_directories() + ")"); } if ( ! itr->second->handle()) { throw std::runtime_error(std::string("Cannot load library: ") + lt_dlerror()); } // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif create_ds* create_datasource = reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create")); if (! create_datasource) { throw std::runtime_error(std::string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_LOG MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Size=" << params.size(); parameters::const_iterator i = params.begin(); for (; i != params.end(); ++i) { MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: -- " << i->first << "=" << i->second; } #endif ds = datasource_ptr(create_datasource(params, bind), datasource_deleter()); MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Datasource=" << ds << " type=" << type; return ds; } bool datasource_cache::insert(std::string const& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo> (type,module))).second; } std::string datasource_cache::plugin_directories() { return boost::algorithm::join(plugin_directories_,", "); } std::vector<std::string> datasource_cache::plugin_names() { std::vector<std::string> names; std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr; for (itr = plugins_.begin();itr!=plugins_.end();++itr) { names.push_back(itr->first); } return names; } void datasource_cache::register_datasources(std::string const& str) { #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif boost::filesystem::path path(str); // TODO - only push unique paths plugin_directories_.push_back(str); boost::filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { #if (BOOST_FILESYSTEM_VERSION == 3) if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string())) #else // v2 if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) #endif { #if (BOOST_FILESYSTEM_VERSION == 3) if (register_datasource(itr->path().string().c_str())) #else // v2 if (register_datasource(itr->string().c_str())) #endif { registered_ = true; } } } } } bool datasource_cache::register_datasource(std::string const& str) { bool success = false; try { lt_dlhandle module = lt_dlopen(str.c_str()); if (module) { // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif datasource_name* ds_name = reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name")); if (ds_name && insert(ds_name(),module)) { MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Registered=" << ds_name(); success = true; } else if (!ds_name) { MAPNIK_LOG_ERROR(datasource_cache) << "Problem loading plugin library '" << str << "' (plugin is lacking compatible interface)"; } } else { MAPNIK_LOG_ERROR(datasource_cache) << "Problem loading plugin library: " << str << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)"; } } catch (...) { MAPNIK_LOG_ERROR(datasource_cache) << "Exception caught while loading plugin library: " << str; } return success; } }
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2011 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ // mapnik #include <mapnik/debug.hpp> #include <mapnik/datasource_cache.hpp> #include <mapnik/config_error.hpp> // boost #include <boost/make_shared.hpp> #include <boost/filesystem/operations.hpp> #include <boost/algorithm/string.hpp> // ltdl #include <ltdl.h> // stl #include <algorithm> #include <iostream> #include <sstream> #include <stdexcept> namespace mapnik { bool is_input_plugin (std::string const& filename) { return boost::algorithm::ends_with(filename,std::string(".input")); } datasource_cache::datasource_cache() { if (lt_dlinit()) throw std::runtime_error("lt_dlinit() failed"); } datasource_cache::~datasource_cache() { lt_dlexit(); } datasource_ptr datasource_cache::create(const parameters& params, bool bind) { boost::optional<std::string> type = params.get<std::string>("type"); if ( ! type) { throw config_error(std::string("Could not create datasource. Required ") + "parameter 'type' is missing"); } #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif datasource_ptr ds; std::map<std::string,boost::shared_ptr<PluginInfo> >::iterator itr=plugins_.find(*type); if ( itr == plugins_.end() ) { std::ostringstream s; s << "Could not create datasource for type: '" << *type << "'"; if (plugin_directories_.empty()) { s << " (no datasource plugin directories have been successfully registered)"; } else { s << " (searched for datasource plugins in '" << plugin_directories() << "')"; } throw config_error(s.str()); } if ( ! itr->second->handle()) { throw std::runtime_error(std::string("Cannot load library: ") + lt_dlerror()); } // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif create_ds* create_datasource = reinterpret_cast<create_ds*>(lt_dlsym(itr->second->handle(), "create")); if (! create_datasource) { throw std::runtime_error(std::string("Cannot load symbols: ") + lt_dlerror()); } #ifdef MAPNIK_LOG MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Size=" << params.size(); parameters::const_iterator i = params.begin(); for (; i != params.end(); ++i) { MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: -- " << i->first << "=" << i->second; } #endif ds = datasource_ptr(create_datasource(params, bind), datasource_deleter()); MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Datasource=" << ds << " type=" << type; return ds; } bool datasource_cache::insert(std::string const& type,const lt_dlhandle module) { return plugins_.insert(make_pair(type,boost::make_shared<PluginInfo> (type,module))).second; } std::string datasource_cache::plugin_directories() { return boost::algorithm::join(plugin_directories_,", "); } std::vector<std::string> datasource_cache::plugin_names() { std::vector<std::string> names; std::map<std::string,boost::shared_ptr<PluginInfo> >::const_iterator itr; for (itr = plugins_.begin();itr!=plugins_.end();++itr) { names.push_back(itr->first); } return names; } void datasource_cache::register_datasources(std::string const& str) { #ifdef MAPNIK_THREADSAFE mutex::scoped_lock lock(mutex_); #endif boost::filesystem::path path(str); // TODO - only push unique paths plugin_directories_.push_back(str); boost::filesystem::directory_iterator end_itr; if (exists(path) && is_directory(path)) { for (boost::filesystem::directory_iterator itr(path);itr!=end_itr;++itr ) { #if (BOOST_FILESYSTEM_VERSION == 3) if (!is_directory( *itr ) && is_input_plugin(itr->path().filename().string())) #else // v2 if (!is_directory( *itr ) && is_input_plugin(itr->path().leaf())) #endif { #if (BOOST_FILESYSTEM_VERSION == 3) if (register_datasource(itr->path().string().c_str())) #else // v2 if (register_datasource(itr->string().c_str())) #endif { registered_ = true; } } } } } bool datasource_cache::register_datasource(std::string const& str) { bool success = false; try { lt_dlhandle module = lt_dlopen(str.c_str()); if (module) { // http://www.mr-edd.co.uk/blog/supressing_gcc_warnings #ifdef __GNUC__ __extension__ #endif datasource_name* ds_name = reinterpret_cast<datasource_name*>(lt_dlsym(module, "datasource_name")); if (ds_name && insert(ds_name(),module)) { MAPNIK_LOG_DEBUG(datasource_cache) << "datasource_cache: Registered=" << ds_name(); success = true; } else if (!ds_name) { MAPNIK_LOG_ERROR(datasource_cache) << "Problem loading plugin library '" << str << "' (plugin is lacking compatible interface)"; } } else { MAPNIK_LOG_ERROR(datasource_cache) << "Problem loading plugin library: " << str << " (dlopen failed - plugin likely has an unsatisfied dependency or incompatible ABI)"; } } catch (...) { MAPNIK_LOG_ERROR(datasource_cache) << "Exception caught while loading plugin library: " << str; } return success; } }
improve error message when datasource plugin is not available
improve error message when datasource plugin is not available
C++
lgpl-2.1
qianwenming/mapnik,Mappy/mapnik,Mappy/mapnik,kapouer/mapnik,jwomeara/mapnik,jwomeara/mapnik,qianwenming/mapnik,CartoDB/mapnik,manz/python-mapnik,mapycz/mapnik,whuaegeanse/mapnik,qianwenming/mapnik,pramsey/mapnik,lightmare/mapnik,naturalatlas/mapnik,kapouer/mapnik,tomhughes/python-mapnik,mapnik/mapnik,mbrukman/mapnik,whuaegeanse/mapnik,yiqingj/work,Airphrame/mapnik,manz/python-mapnik,lightmare/mapnik,yiqingj/work,tomhughes/python-mapnik,naturalatlas/mapnik,mbrukman/mapnik,strk/mapnik,mapnik/python-mapnik,manz/python-mapnik,tomhughes/mapnik,whuaegeanse/mapnik,cjmayo/mapnik,mapycz/python-mapnik,lightmare/mapnik,naturalatlas/mapnik,pnorman/mapnik,CartoDB/mapnik,strk/mapnik,kapouer/mapnik,Uli1/mapnik,whuaegeanse/mapnik,yohanboniface/python-mapnik,zerebubuth/mapnik,mapycz/mapnik,Mappy/mapnik,zerebubuth/mapnik,qianwenming/mapnik,davenquinn/python-mapnik,sebastic/python-mapnik,garnertb/python-mapnik,Mappy/mapnik,mbrukman/mapnik,mbrukman/mapnik,mapycz/mapnik,mapnik/mapnik,Uli1/mapnik,stefanklug/mapnik,jwomeara/mapnik,sebastic/python-mapnik,tomhughes/mapnik,yiqingj/work,mapnik/mapnik,stefanklug/mapnik,lightmare/mapnik,pnorman/mapnik,tomhughes/python-mapnik,yohanboniface/python-mapnik,rouault/mapnik,cjmayo/mapnik,cjmayo/mapnik,garnertb/python-mapnik,Uli1/mapnik,davenquinn/python-mapnik,sebastic/python-mapnik,mapnik/mapnik,jwomeara/mapnik,yohanboniface/python-mapnik,cjmayo/mapnik,pnorman/mapnik,qianwenming/mapnik,pramsey/mapnik,Airphrame/mapnik,stefanklug/mapnik,zerebubuth/mapnik,pramsey/mapnik,strk/mapnik,garnertb/python-mapnik,davenquinn/python-mapnik,mapycz/python-mapnik,pnorman/mapnik,rouault/mapnik,rouault/mapnik,mapnik/python-mapnik,kapouer/mapnik,Airphrame/mapnik,strk/mapnik,naturalatlas/mapnik,tomhughes/mapnik,stefanklug/mapnik,rouault/mapnik,Airphrame/mapnik,tomhughes/mapnik,yiqingj/work,Uli1/mapnik,CartoDB/mapnik,pramsey/mapnik,mapnik/python-mapnik
04e910ae6a2d6982e8a02af9c41fbbb506bd313e
tutorials/developers/tutorial_02/tutorial_02.cpp
tutorials/developers/tutorial_02/tutorial_02.cpp
/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = input[i, j] + i + 2; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("tut_02"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare two constants N and M. These constants will be used as loop bounds. constant N_const("N", NN); constant M_const("M", MM); // Declare iterator variables. var i("i", 0, N_const), j("j", 0, M_const); // Declare a wrapper around the input. // In Tiramisu, if a function reads an input buffer (or writes to it), that buffer // is not accessed directly, but should first be wrapped in a computation. // This is mainly because computations in Tiramisu do not access memory directly, // since the algorithm is supposed to be expressed independently of how data is stored. // Therefore computations (algorithms) access only other computations. The actual data // layout is only specified later in Layer III. // A wrapper is usually declared by providing the iterators (that define the size of the // buffer) and the type of the buffer elements. computation input({i,j}, p_uint8); // Declare the output computation. computation output({i,j}, (input(i, j) + cast(p_uint8, i) + (uint8_t)4)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); // Tile the i, j loop around output by a 2x2 tile. The names of iterators // in the resulting loop are i0, j0, i1, j1. output.tile(i, j, 2, 2, i0, j0, i1, j1); // Parallelize the outermost loop i0 (OpenMP style parallelism). output.parallelize(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Declare input and output buffers. buffer b_input("b_input", {expr(NN), expr(MM)}, p_uint8, a_input); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output); // Map the computations to a buffer. // The following call indicates that each computation input[i,j] // is stored in the buffer element b_input[i,j] (one-to-one mapping). // This is the most common mapping to memory. input.store_in(&b_input); output.store_in(&b_output); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments and generate code tiramisu::codegen({&b_input, &b_output}, "build/generated_fct_developers_tutorial_02.o"); return 0; }
/** The goal of this tutorial is to implement in Tiramisu a code that is equivalent to the following for (int i = 0; i < 10; i++) for (int j = 0; j < 20; j++) output[i, j] = A[i, j] + i + 2; */ #include <tiramisu/tiramisu.h> #define NN 10 #define MM 20 using namespace tiramisu; int main(int argc, char **argv) { tiramisu::init("tut_02"); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- // Declare two constants N and M. These constants will be used as loop bounds. constant N_const("N", NN); constant M_const("M", MM); // Declare iterator variables. var i("i", 0, N_const), j("j", 0, M_const); // Declare an input. The input is declared by providing iterators // (that define the size of the buffer) and the type of the buffer elements. input A({i,j}, p_uint8); // Declare the output computation. computation output({i,j}, (A(i, j) + cast(p_uint8, i) + (uint8_t)4)); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of the computation. var i0("i0"), i1("i1"), j0("j0"), j1("j1"); // Tile the i, j loop around output by a 2x2 tile. The names of iterators // in the resulting loop are i0, j0, i1, j1. output.tile(i, j, 2, 2, i0, j0, i1, j1); // Parallelize the outermost loop i0 (OpenMP style parallelism). output.parallelize(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- // Declare input and output buffers. buffer b_A("b_A", {expr(NN), expr(MM)}, p_uint8, a_input); buffer b_output("b_output", {expr(NN), expr(MM)}, p_uint8, a_output); // Map the computations to a buffer. // The following call indicates that each computation A[i,j] // is stored in the buffer element b_A[i,j] (one-to-one mapping). // This is the most common mapping to memory. A.store_in(&b_A); output.store_in(&b_output); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments and generate code tiramisu::codegen({&b_A, &b_output}, "build/generated_fct_developers_tutorial_02.o"); return 0; }
Update tutorial_02.cpp
Update tutorial_02.cpp
C++
mit
rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/COLi,rbaghdadi/ISIR,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/COLi
1e9fb161f7b56946d41c197abac094293dd1c4ba
tutorials/developers/tutorial_03/tutorial_03.cpp
tutorials/developers/tutorial_03/tutorial_03.cpp
#include <tiramisu/tiramisu.h> /* Halide code for matrix multiplication. Func matmul(Input A, Input B, Output C) { Halide::Func A, B, C; Halide::Var x, y; Halide::RDom r(0, N); C(x,y) = C(x,y) + A(x,r) * B(r,y); C.realize(N, N); } */ #define SIZE0 1000 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. tiramisu::init(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- /* * Declare a function matmul. * Declare two arguments (tiramisu buffers) for the function: b_A and b_B * Declare an invariant for the function. */ function matmul("matmul"); constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &matmul); // Declare a computation c_A that represents a binding to the buffer b_A computation c_A("[N]->{c_A[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul); // Declare a computation c_B that represents a binding to the buffer b_B computation c_B("[N]->{c_B[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul); // Indices var i = var("i"); var j = var("j"); var k = var("k"); // Declare a computation c_C computation c_C("[N]->{c_C[i,j,-1]: 0<=i<N and 0<=j<N}", expr((uint8_t) 0), true, p_uint8, &matmul); c_C.add_definitions("[N]->{c_C[i,j,k]: 0<=i<N and 0<=j<N and 0<=k<N}", expr(), true, p_uint8, &matmul); expr e1 = c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j); c_C.get_update(1).set_expression(e1); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of each computation. // The identity schedule means that the program order is not modified // (i.e. no optimization is applied). c_C.get_update(1).after(c_C, var("j")); c_C.tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1")); c_C.get_update(1).tile(var("i"), var("j"), 32, 32, var("i0"), var("j0"), var("i1"), var("j1")); c_C.get_update(1).tag_parallel_level(var("i0")); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input, &matmul); buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input, &matmul); buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output, &matmul); // Map the computations to a buffer. c_A.set_access("{c_A[i,j]->b_A[i,j]}"); c_B.set_access("{c_B[i,j]->b_B[i,j]}"); c_C.set_access("{c_C[i,j,k]->b_C[i,j]}"); c_C.get_update(1).set_access("{c_C[i,j,k]->b_C[i,j]}"); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to blurxy matmul.codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_03.o"); return 0; }
/* Matrix multiplication. for i = 0 .. N for j = 0 .. N C[i,j] = 0; for k = 0 .. N C[i,j] = C[i,j] + A[i,k] * B[k,j]; } */ #include <tiramisu/tiramisu.h> #define SIZE0 1000 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. tiramisu::init(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- /* * Declare a function matmul. */ function matmul("matmul"); constant p0("N", expr((int32_t) SIZE0), p_int32, true, NULL, 0, &matmul); // Declare computations that represents the input buffer (b_A and b_B) computation c_A("[N]->{c_A[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul); computation c_B("[N]->{c_B[i,j]: 0<=i<N and 0<=j<N}", expr(), false, p_uint8, &matmul); // Indices var i("i"), j("j"), k("k"), i0("i0"), j0("j0"), var("i1"), var("j1"); // Declare a computation to initialize the reduction c[i,j] computation C_init("[N]->{c_C[i,j,-1]: 0<=i<N and 0<=j<N}", expr((uint8_t) 0), true, p_uint8, &matmul); computation c_C("[N]->{c_C[i,j,k]: 0<=i<N and 0<=j<N and 0<=k<N}", expr(), true, p_uint8, &matmul); expr e1 = c_C(i, j, k - 1) + c_A(i, k) * c_B(k, j); c_C.set_expression(e1); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- // Set the schedule of each computation. // The identity schedule means that the program order is not modified // (i.e. no optimization is applied). C_init.tile(i, j, 32, 32, i0, j0, i1, j1); c_C.after(C_init, j); c_C.tile(i, j, 32, 32, i0, j0, i1, j1); c_C.tag_parallel_level(i0); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b_A("b_A", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input, &matmul); buffer b_B("b_B", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_input, &matmul); buffer b_C("b_C", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output, &matmul); // Map the computations to a buffer. c_A.set_access("{c_A[i,j]->b_A[i,j]}"); c_B.set_access("{c_B[i,j]->b_B[i,j]}"); C_init.set_access("{c_C[i,j,k]->b_C[i,j]}"); c_C.set_access("{c_C[i,j,k]->b_C[i,j]}"); // ------------------------------------------------------- // Code Generation // ------------------------------------------------------- // Set the arguments to blurxy matmul.codegen({&b_A, &b_B, &b_C}, "build/generated_fct_developers_tutorial_03.o"); return 0; }
Update tutorial_03.cpp
Update tutorial_03.cpp
C++
mit
rbaghdadi/tiramisu,rbaghdadi/COLi,rbaghdadi/COLi,rbaghdadi/tiramisu,rbaghdadi/tiramisu,rbaghdadi/ISIR,rbaghdadi/ISIR,rbaghdadi/tiramisu
2885c76e70e2a9ad6dfae9a22936b2b1125ca2ad
mjolnir/math/Matrix.hpp
mjolnir/math/Matrix.hpp
#ifndef MJOLNIR_MATH_MATRIX #define MJOLNIR_MATH_MATRIX #include <mjolnir/util/is_all.hpp> #include <mjolnir/util/scalar_type_of.hpp> #include <array> namespace mjolnir { template<typename realT, std::size_t Row, std::size_t Col> class Matrix { public: using real_type = realT; using scalar_type = real_type; constexpr static std::size_t dim_row = Row; constexpr static std::size_t dim_col = Col; constexpr static std::size_t number_of_element = Row * Col; public: Matrix() : values_{{}}{} ~Matrix() = default; template<typename ... T_args, class = typename std::enable_if< (sizeof...(T_args) == number_of_element) && is_all<std::is_convertible, realT, T_args...>::value>::type> Matrix(T_args ... args) : values_{{args...}}{} Matrix(const Matrix& mat) = default; Matrix& operator=(const Matrix& mat) = default; Matrix& operator+=(const Matrix& mat); Matrix& operator-=(const Matrix& mat); Matrix& operator*=(const scalar_type& scl); Matrix& operator/=(const scalar_type& scl); scalar_type at(const std::size_t i, const std::size_t j) const; scalar_type& at(const std::size_t i, const std::size_t j); scalar_type operator()(const std::size_t i, const std::size_t j) const; scalar_type& operator()(const std::size_t i, const std::size_t j); scalar_type at(const std::size_t i) const {return values_.at(i);} scalar_type& at(const std::size_t i) {return values_.at(i);} scalar_type operator[](const std::size_t i) const {return values_[i];} scalar_type& operator[](const std::size_t i) {return values_[i];} private: std::array<real_type, number_of_element> values_; }; template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) += mat(i, j); return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) -= mat(i, j); return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator*=(const scalar_type& s) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) *= s; return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator/=(const scalar_type& s) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) /= s; return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) + rhs(i, j); return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) - rhs(i, j); return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator*(const Matrix<realT, R, C>& lhs, const realT rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) * rhs; return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator*(const realT lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = rhs(i, j) * lhs; return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator/(const Matrix<realT, R, C>& lhs, const realT rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) / rhs; return retval; } template<typename realT, std::size_t L, std::size_t M, std::size_t N> Matrix<realT, L, N> operator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs) { Matrix<realT, L, N> retval; for(std::size_t i=0; i < L; ++i) for(std::size_t j=0; j < N; ++j) for(std::size_t k=0; k < M; ++k) retval(i, j) += lhs(i, k) * rhs(k, j); return retval; } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const { return this->values_.at(i * C + j); } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type& Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) { return this->values_.at(i * C + j); } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const { return this->values_[i * C + j]; } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type& Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) { return this->values_[i * C + j]; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat) { Matrix<realT, C, R> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(j, i) = mat(i, j); return retval; } // for 3*3 only ... template<typename realT> inline realT determinant(const Matrix<realT, 3, 3>& mat) { return mat(0,0) * mat(1,1) * mat(2,2) + mat(1,0) * mat(2,1) * mat(0,2) + mat(2,0) * mat(0,1) * mat(1,2) - mat(0,0) * mat(2,1) * mat(1,2) - mat(2,0) * mat(1,1) * mat(0,2) - mat(1,0) * mat(0,1) * mat(2,2); } template<typename realT> Matrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat) { const auto det_inv = 1e0 / determinant(mat); Matrix<realT, 3, 3> inv; inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1)); inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0)); inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0)); inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2)); inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1)); inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2)); inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2)); inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1)); inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1)); return inv; } template<typename T, std::size_t S1, std::size_t S2> struct scalar_type_of<Matrix<T, S1, S2>> { typedef T type; }; } // mjolnir #endif /* MJOLNIR_MATH_MATRIX */
#ifndef MJOLNIR_MATH_MATRIX #define MJOLNIR_MATH_MATRIX #include <mjolnir/util/is_all.hpp> #include <mjolnir/util/scalar_type_of.hpp> #include <array> namespace mjolnir { template<typename realT, std::size_t Row, std::size_t Col> class Matrix { public: using real_type = realT; using scalar_type = real_type; constexpr static std::size_t dim_row = Row; constexpr static std::size_t dim_col = Col; constexpr static std::size_t number_of_element = Row * Col; public: Matrix() : values_{{}}{} ~Matrix() = default; template<typename ... T_args, class = typename std::enable_if< (sizeof...(T_args) == number_of_element) && is_all<std::is_convertible, realT, T_args...>::value>::type> Matrix(T_args ... args) : values_{{static_cast<real_type>(args)...}}{} Matrix(const Matrix& mat) = default; Matrix& operator=(const Matrix& mat) = default; Matrix& operator+=(const Matrix& mat); Matrix& operator-=(const Matrix& mat); Matrix& operator*=(const scalar_type& scl); Matrix& operator/=(const scalar_type& scl); scalar_type at(const std::size_t i, const std::size_t j) const; scalar_type& at(const std::size_t i, const std::size_t j); scalar_type operator()(const std::size_t i, const std::size_t j) const; scalar_type& operator()(const std::size_t i, const std::size_t j); scalar_type at(const std::size_t i) const {return values_.at(i);} scalar_type& at(const std::size_t i) {return values_.at(i);} scalar_type operator[](const std::size_t i) const {return values_[i];} scalar_type& operator[](const std::size_t i) {return values_[i];} private: std::array<real_type, number_of_element> values_; }; template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator+=(const Matrix<realT, R, C>& mat) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) += mat(i, j); return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator-=(const Matrix<realT, R, C>& mat) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) -= mat(i, j); return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator*=(const scalar_type& s) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) *= s; return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C>& Matrix<realT, R, C>::operator/=(const scalar_type& s) { for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) (*this)(i, j) /= s; return *this; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator+(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) + rhs(i, j); return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator-(const Matrix<realT, R, C>& lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) - rhs(i, j); return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator*(const Matrix<realT, R, C>& lhs, const realT rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) * rhs; return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator*(const realT lhs, const Matrix<realT, R, C>& rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = rhs(i, j) * lhs; return retval; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, R, C> operator/(const Matrix<realT, R, C>& lhs, const realT rhs) { Matrix<realT, R, C> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(i, j) = lhs(i, j) / rhs; return retval; } template<typename realT, std::size_t L, std::size_t M, std::size_t N> Matrix<realT, L, N> operator*(const Matrix<realT, L, M>& lhs, const Matrix<realT, M, N>& rhs) { Matrix<realT, L, N> retval; for(std::size_t i=0; i < L; ++i) for(std::size_t j=0; j < N; ++j) for(std::size_t k=0; k < M; ++k) retval(i, j) += lhs(i, k) * rhs(k, j); return retval; } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) const { return this->values_.at(i * C + j); } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type& Matrix<realT, R, C>::at(const std::size_t i, const std::size_t j) { return this->values_.at(i * C + j); } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) const { return this->values_[i * C + j]; } template<typename realT, std::size_t R, std::size_t C> typename Matrix<realT, R, C>::scalar_type& Matrix<realT, R, C>::operator()(const std::size_t i, const std::size_t j) { return this->values_[i * C + j]; } template<typename realT, std::size_t R, std::size_t C> Matrix<realT, C, R> transpose(const Matrix<realT, R, C>& mat) { Matrix<realT, C, R> retval; for(std::size_t i=0; i<R; ++i) for(std::size_t j=0; j<C; ++j) retval(j, i) = mat(i, j); return retval; } // for 3*3 only ... template<typename realT> inline realT determinant(const Matrix<realT, 3, 3>& mat) { return mat(0,0) * mat(1,1) * mat(2,2) + mat(1,0) * mat(2,1) * mat(0,2) + mat(2,0) * mat(0,1) * mat(1,2) - mat(0,0) * mat(2,1) * mat(1,2) - mat(2,0) * mat(1,1) * mat(0,2) - mat(1,0) * mat(0,1) * mat(2,2); } template<typename realT> Matrix<realT, 3, 3> inverse(const Matrix<realT, 3, 3>& mat) { const auto det_inv = 1e0 / determinant(mat); Matrix<realT, 3, 3> inv; inv(0,0) = det_inv * (mat(1,1) * mat(2,2) - mat(1,2) * mat(2,1)); inv(1,1) = det_inv * (mat(0,0) * mat(2,2) - mat(0,2) * mat(2,0)); inv(2,2) = det_inv * (mat(0,0) * mat(1,1) - mat(0,1) * mat(1,0)); inv(0,1) = det_inv * (mat(0,2) * mat(2,1) - mat(0,1) * mat(2,2)); inv(0,2) = det_inv * (mat(0,1) * mat(1,2) - mat(0,2) * mat(1,1)); inv(1,2) = det_inv * (mat(0,2) * mat(1,0) - mat(0,0) * mat(1,2)); inv(1,0) = det_inv * (mat(1,2) * mat(2,0) - mat(1,0) * mat(2,2)); inv(2,0) = det_inv * (mat(1,0) * mat(2,1) - mat(2,0) * mat(1,1)); inv(2,1) = det_inv * (mat(2,0) * mat(0,1) - mat(0,0) * mat(2,1)); return inv; } template<typename T, std::size_t S1, std::size_t S2> struct scalar_type_of<Matrix<T, S1, S2>> { typedef T type; }; } // mjolnir #endif /* MJOLNIR_MATH_MATRIX */
add static_cast to ctor of Matrix
add static_cast to ctor of Matrix
C++
mit
ToruNiina/Mjolnir,ToruNiina/Mjolnir,ToruNiina/Mjolnir
f75b3353303c01d012392e407876dd0904330b6f
base/timer.cc
base/timer.cc
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. #include "base/timer.h" #include <mmsystem.h> #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/task.h" // Note about hi-resolution timers. // This class would *like* to provide high resolution timers. Windows timers // using SetTimer() have a 10ms granularity. We have to use WM_TIMER as a // wakeup mechanism because the application can enter modal windows loops where // it is not running our MessageLoop; the only way to have our timers fire in // these cases is to post messages there. // // To provide sub-10ms timers, we process timers directly from our main // MessageLoop. For the common case, timers will be processed there as the // message loop does its normal work. However, we *also* set the system timer // so that WM_TIMER events fire. This mops up the case of timers not being // able to work in modal message loops. It is possible for the SetTimer to // pop and have no pending timers, because they could have already been // processed by the message loop itself. // // We use a single SetTimer corresponding to the timer that will expire // soonest. As new timers are created and destroyed, we update SetTimer. // Getting a spurrious SetTimer event firing is benign, as we'll just be // processing an empty timer queue. static const wchar_t kWndClass[] = L"Chrome_TimerMessageWindow"; static LRESULT CALLBACK MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_TIMER) { // Timer not firing? Maybe you're suffering from a WM_PAINTstorm. Make sure // any WM_PAINT handler you have calls BeginPaint and EndPaint to validate // the invalid region, otherwise you will be flooded with paint messages // that trump WM_TIMER when PeekMessage is called. UINT_PTR timer_id = static_cast<UINT_PTR>(wparam); TimerManager* tm = reinterpret_cast<TimerManager*>(timer_id); return tm->MessageWndProc(hwnd, message, wparam, lparam); } return DefWindowProc(hwnd, message, wparam, lparam); } // A sequence number for all allocated times (used to break ties when // comparing times in the TimerManager, and assure FIFO execution sequence). static base::AtomicSequenceNumber timer_id_counter_; //----------------------------------------------------------------------------- // Timer Timer::Timer(int delay, Task* task, bool repeating) : delay_(delay), task_(task), repeating_(repeating) { timer_id_ = timer_id_counter_.GetNext(); DCHECK(delay >= 0); Reset(); } void Timer::Reset() { creation_time_ = Time::Now(); fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_); DHISTOGRAM_COUNTS(L"Timer.Durations", delay_); } //----------------------------------------------------------------------------- // TimerPQueue void TimerPQueue::RemoveTimer(Timer* timer) { const std::vector<Timer*>::iterator location = find(c.begin(), c.end(), timer); if (location != c.end()) { c.erase(location); make_heap(c.begin(), c.end(), TimerComparison()); } } bool TimerPQueue::ContainsTimer(const Timer* timer) const { return find(c.begin(), c.end(), timer) != c.end(); } //----------------------------------------------------------------------------- // TimerManager TimerManager::TimerManager() : message_hwnd_(NULL), use_broken_delay_(false), use_native_timers_(true), message_loop_(NULL) { // We've experimented with all sorts of timers, and initially tried // to avoid using timeBeginPeriod because it does affect the system // globally. However, after much investigation, it turns out that all // of the major plugins (flash, windows media 9-11, and quicktime) // already use timeBeginPeriod to increase the speed of the clock. // Since the browser must work with these plugins, the browser already // needs to support a fast clock. We may as well use this ourselves, // as it really is the best timer mechanism for our needs. timeBeginPeriod(1); // Initialize the Message HWND in the constructor so that the window // belongs to the same thread as the message loop (this is important!) GetMessageHWND(); } TimerManager::~TimerManager() { // Match timeBeginPeriod() from construction. timeEndPeriod(1); if (message_hwnd_ != NULL) DestroyWindow(message_hwnd_); // Be nice to unit tests, and discard and delete all timers along with the // embedded task objects by handing off to MessageLoop (which would have Run() // and optionally deleted the objects). while (timers_.size()) { Timer* pending = timers_.top(); timers_.pop(); message_loop_->DiscardTimer(pending); } } Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) { Timer* t = new Timer(delay, task, repeating); StartTimer(t); return t; } void TimerManager::StopTimer(Timer* timer) { // Make sure the timer is actually running. if (!IsTimerRunning(timer)) return; // Kill the active timer, and remove the pending entry from the queue. if (timer != timers_.top()) { timers_.RemoveTimer(timer); } else { timers_.pop(); UpdateWindowsWmTimer(); // We took away the head of our queue. } } void TimerManager::ResetTimer(Timer* timer) { StopTimer(timer); timer->Reset(); StartTimer(timer); } bool TimerManager::IsTimerRunning(const Timer* timer) const { return timers_.ContainsTimer(timer); } Timer* TimerManager::PeekTopTimer() { if (timers_.empty()) return NULL; return timers_.top(); } bool TimerManager::RunSomePendingTimers() { bool did_work = false; bool allowed_to_run = message_loop()->NestableTasksAllowed(); // Process a small group of timers. Cap the maximum number of timers we can // process so we don't deny cycles to other parts of the process when lots of // timers have been set. const int kMaxTimersPerCall = 2; for (int i = 0; i < kMaxTimersPerCall; ++i) { if (timers_.empty() || GetCurrentDelay() > 0) break; // Get a pending timer. Deal with updating the timers_ queue and setting // the TopTimer. We'll execute the timer task only after the timer queue // is back in a consistent state. Timer* pending = timers_.top(); // If pending task isn't invoked_later, then it must be possible to run it // now (i.e., current task needs to be reentrant). // TODO(jar): We may block tasks that we can queue from being popped. if (!message_loop()->NestableTasksAllowed() && !pending->task()->is_owned_by_message_loop()) break; timers_.pop(); did_work = true; // If the timer is repeating, add it back to the list of timers to process. if (pending->repeating()) { pending->Reset(); timers_.push(pending); } message_loop()->RunTimerTask(pending); } // Restart the WM_TIMER (if necessary). if (did_work) UpdateWindowsWmTimer(); return did_work; } // Note: Caller is required to call timer->Reset() before calling StartTimer(). // TODO(jar): change API so that Reset() is called as part of StartTimer, making // the API a little less error prone. void TimerManager::StartTimer(Timer* timer) { // Make sure the timer is not running. if (IsTimerRunning(timer)) return; timers_.push(timer); // Priority queue will sort the timer into place. if (timers_.top() == timer) UpdateWindowsWmTimer(); // We are new head of queue. } void TimerManager::UpdateWindowsWmTimer() { if (!use_native_timers_) return; if (timers_.empty()) { KillTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this)); return; } int delay = GetCurrentDelay(); if (delay < USER_TIMER_MINIMUM) delay = USER_TIMER_MINIMUM; // Simulates malfunctioning, early firing timers. Pending tasks should // only be invoked when the delay they specify has elapsed. if (use_broken_delay_) delay = 10; // Create a WM_TIMER event that will wake us up to check for any pending // timers (in case the message loop was otherwise starving us). SetTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this), delay, NULL); } int TimerManager::GetCurrentDelay() { if (timers_.empty()) return -1; int delay = timers_.top()->current_delay(); if (delay < 0) delay = 0; return delay; } int TimerManager::MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { DCHECK(!lparam); DCHECK(this == message_loop()->timer_manager()); if (message_loop()->NestableTasksAllowed()) RunSomePendingTimers(); else UpdateWindowsWmTimer(); return 0; } MessageLoop* TimerManager::message_loop() { if (!message_loop_) message_loop_ = MessageLoop::current(); DCHECK(message_loop_ == MessageLoop::current()); return message_loop_; } HWND TimerManager::GetMessageHWND() { if (!message_hwnd_) { HINSTANCE hinst = GetModuleHandle(NULL); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = ::MessageWndProc; wc.hInstance = hinst; wc.lpszClassName = kWndClass; RegisterClassEx(&wc); message_hwnd_ = CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0); DCHECK(message_hwnd_); } return message_hwnd_; } //----------------------------------------------------------------------------- // SimpleTimer SimpleTimer::SimpleTimer(TimeDelta delay, Task* task, bool repeating) : timer_(static_cast<int>(delay.InMilliseconds()), task, repeating), owns_task_(true) { } SimpleTimer::~SimpleTimer() { Stop(); if (owns_task_) delete timer_.task(); } void SimpleTimer::Start() { DCHECK(timer_.task()); timer_.Reset(); MessageLoop::current()->timer_manager()->StartTimer(&timer_); } void SimpleTimer::Stop() { MessageLoop::current()->timer_manager()->StopTimer(&timer_); } bool SimpleTimer::IsRunning() const { return MessageLoop::current()->timer_manager()->IsTimerRunning(&timer_); } void SimpleTimer::Reset() { DCHECK(timer_.task()); MessageLoop::current()->timer_manager()->ResetTimer(&timer_); }
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. #include "base/timer.h" #include <mmsystem.h> #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/task.h" // Note about hi-resolution timers. // This class would *like* to provide high resolution timers. Windows timers // using SetTimer() have a 10ms granularity. We have to use WM_TIMER as a // wakeup mechanism because the application can enter modal windows loops where // it is not running our MessageLoop; the only way to have our timers fire in // these cases is to post messages there. // // To provide sub-10ms timers, we process timers directly from our main // MessageLoop. For the common case, timers will be processed there as the // message loop does its normal work. However, we *also* set the system timer // so that WM_TIMER events fire. This mops up the case of timers not being // able to work in modal message loops. It is possible for the SetTimer to // pop and have no pending timers, because they could have already been // processed by the message loop itself. // // We use a single SetTimer corresponding to the timer that will expire // soonest. As new timers are created and destroyed, we update SetTimer. // Getting a spurrious SetTimer event firing is benign, as we'll just be // processing an empty timer queue. static const wchar_t kWndClass[] = L"Chrome_TimerMessageWindow"; static LRESULT CALLBACK MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_TIMER) { // Timer not firing? Maybe you're suffering from a WM_PAINTstorm. Make sure // any WM_PAINT handler you have calls BeginPaint and EndPaint to validate // the invalid region, otherwise you will be flooded with paint messages // that trump WM_TIMER when PeekMessage is called. UINT_PTR timer_id = static_cast<UINT_PTR>(wparam); TimerManager* tm = reinterpret_cast<TimerManager*>(timer_id); return tm->MessageWndProc(hwnd, message, wparam, lparam); } return DefWindowProc(hwnd, message, wparam, lparam); } // A sequence number for all allocated times (used to break ties when // comparing times in the TimerManager, and assure FIFO execution sequence). static base::AtomicSequenceNumber timer_id_counter_; //----------------------------------------------------------------------------- // Timer Timer::Timer(int delay, Task* task, bool repeating) : task_(task), delay_(delay), repeating_(repeating) { timer_id_ = timer_id_counter_.GetNext(); DCHECK(delay >= 0); Reset(); } void Timer::Reset() { creation_time_ = Time::Now(); fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_); DHISTOGRAM_COUNTS(L"Timer.Durations", delay_); } //----------------------------------------------------------------------------- // TimerPQueue void TimerPQueue::RemoveTimer(Timer* timer) { const std::vector<Timer*>::iterator location = find(c.begin(), c.end(), timer); if (location != c.end()) { c.erase(location); make_heap(c.begin(), c.end(), TimerComparison()); } } bool TimerPQueue::ContainsTimer(const Timer* timer) const { return find(c.begin(), c.end(), timer) != c.end(); } //----------------------------------------------------------------------------- // TimerManager TimerManager::TimerManager() : message_hwnd_(NULL), use_broken_delay_(false), use_native_timers_(true), message_loop_(NULL) { // We've experimented with all sorts of timers, and initially tried // to avoid using timeBeginPeriod because it does affect the system // globally. However, after much investigation, it turns out that all // of the major plugins (flash, windows media 9-11, and quicktime) // already use timeBeginPeriod to increase the speed of the clock. // Since the browser must work with these plugins, the browser already // needs to support a fast clock. We may as well use this ourselves, // as it really is the best timer mechanism for our needs. timeBeginPeriod(1); // Initialize the Message HWND in the constructor so that the window // belongs to the same thread as the message loop (this is important!) GetMessageHWND(); } TimerManager::~TimerManager() { // Match timeBeginPeriod() from construction. timeEndPeriod(1); if (message_hwnd_ != NULL) DestroyWindow(message_hwnd_); // Be nice to unit tests, and discard and delete all timers along with the // embedded task objects by handing off to MessageLoop (which would have Run() // and optionally deleted the objects). while (timers_.size()) { Timer* pending = timers_.top(); timers_.pop(); message_loop_->DiscardTimer(pending); } } Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) { Timer* t = new Timer(delay, task, repeating); StartTimer(t); return t; } void TimerManager::StopTimer(Timer* timer) { // Make sure the timer is actually running. if (!IsTimerRunning(timer)) return; // Kill the active timer, and remove the pending entry from the queue. if (timer != timers_.top()) { timers_.RemoveTimer(timer); } else { timers_.pop(); UpdateWindowsWmTimer(); // We took away the head of our queue. } } void TimerManager::ResetTimer(Timer* timer) { StopTimer(timer); timer->Reset(); StartTimer(timer); } bool TimerManager::IsTimerRunning(const Timer* timer) const { return timers_.ContainsTimer(timer); } Timer* TimerManager::PeekTopTimer() { if (timers_.empty()) return NULL; return timers_.top(); } bool TimerManager::RunSomePendingTimers() { bool did_work = false; bool allowed_to_run = message_loop()->NestableTasksAllowed(); // Process a small group of timers. Cap the maximum number of timers we can // process so we don't deny cycles to other parts of the process when lots of // timers have been set. const int kMaxTimersPerCall = 2; for (int i = 0; i < kMaxTimersPerCall; ++i) { if (timers_.empty() || GetCurrentDelay() > 0) break; // Get a pending timer. Deal with updating the timers_ queue and setting // the TopTimer. We'll execute the timer task only after the timer queue // is back in a consistent state. Timer* pending = timers_.top(); // If pending task isn't invoked_later, then it must be possible to run it // now (i.e., current task needs to be reentrant). // TODO(jar): We may block tasks that we can queue from being popped. if (!message_loop()->NestableTasksAllowed() && !pending->task()->is_owned_by_message_loop()) break; timers_.pop(); did_work = true; // If the timer is repeating, add it back to the list of timers to process. if (pending->repeating()) { pending->Reset(); timers_.push(pending); } message_loop()->RunTimerTask(pending); } // Restart the WM_TIMER (if necessary). if (did_work) UpdateWindowsWmTimer(); return did_work; } // Note: Caller is required to call timer->Reset() before calling StartTimer(). // TODO(jar): change API so that Reset() is called as part of StartTimer, making // the API a little less error prone. void TimerManager::StartTimer(Timer* timer) { // Make sure the timer is not running. if (IsTimerRunning(timer)) return; timers_.push(timer); // Priority queue will sort the timer into place. if (timers_.top() == timer) UpdateWindowsWmTimer(); // We are new head of queue. } void TimerManager::UpdateWindowsWmTimer() { if (!use_native_timers_) return; if (timers_.empty()) { KillTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this)); return; } int delay = GetCurrentDelay(); if (delay < USER_TIMER_MINIMUM) delay = USER_TIMER_MINIMUM; // Simulates malfunctioning, early firing timers. Pending tasks should // only be invoked when the delay they specify has elapsed. if (use_broken_delay_) delay = 10; // Create a WM_TIMER event that will wake us up to check for any pending // timers (in case the message loop was otherwise starving us). SetTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this), delay, NULL); } int TimerManager::GetCurrentDelay() { if (timers_.empty()) return -1; int delay = timers_.top()->current_delay(); if (delay < 0) delay = 0; return delay; } int TimerManager::MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { DCHECK(!lparam); DCHECK(this == message_loop()->timer_manager()); if (message_loop()->NestableTasksAllowed()) RunSomePendingTimers(); else UpdateWindowsWmTimer(); return 0; } MessageLoop* TimerManager::message_loop() { if (!message_loop_) message_loop_ = MessageLoop::current(); DCHECK(message_loop_ == MessageLoop::current()); return message_loop_; } HWND TimerManager::GetMessageHWND() { if (!message_hwnd_) { HINSTANCE hinst = GetModuleHandle(NULL); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = ::MessageWndProc; wc.hInstance = hinst; wc.lpszClassName = kWndClass; RegisterClassEx(&wc); message_hwnd_ = CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0); DCHECK(message_hwnd_); } return message_hwnd_; } //----------------------------------------------------------------------------- // SimpleTimer SimpleTimer::SimpleTimer(TimeDelta delay, Task* task, bool repeating) : timer_(static_cast<int>(delay.InMilliseconds()), task, repeating), owns_task_(true) { } SimpleTimer::~SimpleTimer() { Stop(); if (owns_task_) delete timer_.task(); } void SimpleTimer::Start() { DCHECK(timer_.task()); timer_.Reset(); MessageLoop::current()->timer_manager()->StartTimer(&timer_); } void SimpleTimer::Stop() { MessageLoop::current()->timer_manager()->StopTimer(&timer_); } bool SimpleTimer::IsRunning() const { return MessageLoop::current()->timer_manager()->IsTimerRunning(&timer_); } void SimpleTimer::Reset() { DCHECK(timer_.task()); MessageLoop::current()->timer_manager()->ResetTimer(&timer_); }
fix initialization order warning
fix initialization order warning git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@757 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
anirudhSK/chromium,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,fujunwei/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,markYoungH/chromium.src,hujiajie/pa-chromium,keishi/chromium,keishi/chromium,ltilve/chromium,Chilledheart/chromium,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,hujiajie/pa-chromium,markYoungH/chromium.src,axinging/chromium-crosswalk,jaruba/chromium.src,axinging/chromium-crosswalk,Fireblend/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,ltilve/chromium,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Just-D/chromium-1,krieger-od/nwjs_chromium.src,robclark/chromium,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,axinging/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,dushu1203/chromium.src,ltilve/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,Chilledheart/chromium,keishi/chromium,hgl888/chromium-crosswalk-efl,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,keishi/chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,dednal/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,Jonekee/chromium.src,robclark/chromium,Fireblend/chromium-crosswalk,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,robclark/chromium,Jonekee/chromium.src,keishi/chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,jaruba/chromium.src,dednal/chromium.src,keishi/chromium,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,robclark/chromium,Just-D/chromium-1,keishi/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,ltilve/chromium,dushu1203/chromium.src,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,M4sse/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,robclark/chromium,hujiajie/pa-chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,krieger-od/nwjs_chromium.src,hujiajie/pa-chromium,Chilledheart/chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,robclark/chromium,chuan9/chromium-crosswalk,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,anirudhSK/chromium,rogerwang/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,littlstar/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,Just-D/chromium-1,Chilledheart/chromium,littlstar/chromium.src,dednal/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,markYoungH/chromium.src,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,jaruba/chromium.src,M4sse/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,robclark/chromium,hujiajie/pa-chromium,anirudhSK/chromium,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,keishi/chromium,ChromiumWebApps/chromium,dednal/chromium.src,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,jaruba/chromium.src,fujunwei/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,dednal/chromium.src,dednal/chromium.src,Just-D/chromium-1,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,zcbenz/cefode-chromium,ChromiumWebApps/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,ltilve/chromium,Chilledheart/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,ChromiumWebApps/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,rogerwang/chromium,mohamed--abdel-maksoud/chromium.src,hgl888/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,bright-sparks/chromium-spacewalk,dednal/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,keishi/chromium,patrickm/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,Pluto-tv/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,patrickm/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,Fireblend/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,chuan9/chromium-crosswalk,axinging/chromium-crosswalk,rogerwang/chromium,Chilledheart/chromium,nacl-webkit/chrome_deps,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,rogerwang/chromium,ChromiumWebApps/chromium,dednal/chromium.src,Fireblend/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,ondra-novak/chromium.src,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mogoweb/chromium-crosswalk,zcbenz/cefode-chromium,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,Just-D/chromium-1,dednal/chromium.src,rogerwang/chromium,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk,markYoungH/chromium.src,nacl-webkit/chrome_deps,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,rogerwang/chromium,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,markYoungH/chromium.src,zcbenz/cefode-chromium,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,rogerwang/chromium,anirudhSK/chromium,ondra-novak/chromium.src,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,ondra-novak/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,jaruba/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,nacl-webkit/chrome_deps,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,M4sse/chromium.src,zcbenz/cefode-chromium,robclark/chromium,patrickm/chromium.src,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,markYoungH/chromium.src,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,fujunwei/chromium-crosswalk,chuan9/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,ltilve/chromium,anirudhSK/chromium
830864cbb205fa5edde0420db02bdaf3b9a5e27d
base/timer.cc
base/timer.cc
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. #include "base/timer.h" #include <mmsystem.h> #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/task.h" // Note about hi-resolution timers. // This class would *like* to provide high resolution timers. Windows timers // using SetTimer() have a 10ms granularity. We have to use WM_TIMER as a // wakeup mechanism because the application can enter modal windows loops where // it is not running our MessageLoop; the only way to have our timers fire in // these cases is to post messages there. // // To provide sub-10ms timers, we process timers directly from our main // MessageLoop. For the common case, timers will be processed there as the // message loop does its normal work. However, we *also* set the system timer // so that WM_TIMER events fire. This mops up the case of timers not being // able to work in modal message loops. It is possible for the SetTimer to // pop and have no pending timers, because they could have already been // processed by the message loop itself. // // We use a single SetTimer corresponding to the timer that will expire // soonest. As new timers are created and destroyed, we update SetTimer. // Getting a spurrious SetTimer event firing is benign, as we'll just be // processing an empty timer queue. static const wchar_t kWndClass[] = L"Chrome_TimerMessageWindow"; static LRESULT CALLBACK MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_TIMER) { // Timer not firing? Maybe you're suffering from a WM_PAINTstorm. Make sure // any WM_PAINT handler you have calls BeginPaint and EndPaint to validate // the invalid region, otherwise you will be flooded with paint messages // that trump WM_TIMER when PeekMessage is called. UINT_PTR timer_id = static_cast<UINT_PTR>(wparam); TimerManager* tm = reinterpret_cast<TimerManager*>(timer_id); return tm->MessageWndProc(hwnd, message, wparam, lparam); } return DefWindowProc(hwnd, message, wparam, lparam); } // A sequence number for all allocated times (used to break ties when // comparing times in the TimerManager, and assure FIFO execution sequence). static base::AtomicSequenceNumber timer_id_counter_; //----------------------------------------------------------------------------- // Timer Timer::Timer(int delay, Task* task, bool repeating) : delay_(delay), task_(task), repeating_(repeating) { timer_id_ = timer_id_counter_.GetNext(); DCHECK(delay >= 0); Reset(); } void Timer::Reset() { creation_time_ = Time::Now(); fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_); DHISTOGRAM_COUNTS(L"Timer.Durations", delay_); } //----------------------------------------------------------------------------- // TimerPQueue void TimerPQueue::RemoveTimer(Timer* timer) { const std::vector<Timer*>::iterator location = find(c.begin(), c.end(), timer); if (location != c.end()) { c.erase(location); make_heap(c.begin(), c.end(), TimerComparison()); } } bool TimerPQueue::ContainsTimer(const Timer* timer) const { return find(c.begin(), c.end(), timer) != c.end(); } //----------------------------------------------------------------------------- // TimerManager TimerManager::TimerManager() : message_hwnd_(NULL), use_broken_delay_(false), use_native_timers_(true), message_loop_(NULL) { // We've experimented with all sorts of timers, and initially tried // to avoid using timeBeginPeriod because it does affect the system // globally. However, after much investigation, it turns out that all // of the major plugins (flash, windows media 9-11, and quicktime) // already use timeBeginPeriod to increase the speed of the clock. // Since the browser must work with these plugins, the browser already // needs to support a fast clock. We may as well use this ourselves, // as it really is the best timer mechanism for our needs. timeBeginPeriod(1); // Initialize the Message HWND in the constructor so that the window // belongs to the same thread as the message loop (this is important!) GetMessageHWND(); } TimerManager::~TimerManager() { // Match timeBeginPeriod() from construction. timeEndPeriod(1); if (message_hwnd_ != NULL) DestroyWindow(message_hwnd_); // Be nice to unit tests, and discard and delete all timers along with the // embedded task objects by handing off to MessageLoop (which would have Run() // and optionally deleted the objects). while (timers_.size()) { Timer* pending = timers_.top(); timers_.pop(); message_loop_->DiscardTimer(pending); } } Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) { Timer* t = new Timer(delay, task, repeating); StartTimer(t); return t; } void TimerManager::StopTimer(Timer* timer) { // Make sure the timer is actually running. if (!IsTimerRunning(timer)) return; // Kill the active timer, and remove the pending entry from the queue. if (timer != timers_.top()) { timers_.RemoveTimer(timer); } else { timers_.pop(); UpdateWindowsWmTimer(); // We took away the head of our queue. } } void TimerManager::ResetTimer(Timer* timer) { StopTimer(timer); timer->Reset(); StartTimer(timer); } bool TimerManager::IsTimerRunning(const Timer* timer) const { return timers_.ContainsTimer(timer); } Timer* TimerManager::PeekTopTimer() { if (timers_.empty()) return NULL; return timers_.top(); } bool TimerManager::RunSomePendingTimers() { bool did_work = false; bool allowed_to_run = message_loop()->NestableTasksAllowed(); // Process a small group of timers. Cap the maximum number of timers we can // process so we don't deny cycles to other parts of the process when lots of // timers have been set. const int kMaxTimersPerCall = 2; for (int i = 0; i < kMaxTimersPerCall; ++i) { if (timers_.empty() || GetCurrentDelay() > 0) break; // Get a pending timer. Deal with updating the timers_ queue and setting // the TopTimer. We'll execute the timer task only after the timer queue // is back in a consistent state. Timer* pending = timers_.top(); // If pending task isn't invoked_later, then it must be possible to run it // now (i.e., current task needs to be reentrant). // TODO(jar): We may block tasks that we can queue from being popped. if (!message_loop()->NestableTasksAllowed() && !pending->task()->is_owned_by_message_loop()) break; timers_.pop(); did_work = true; // If the timer is repeating, add it back to the list of timers to process. if (pending->repeating()) { pending->Reset(); timers_.push(pending); } message_loop()->RunTimerTask(pending); } // Restart the WM_TIMER (if necessary). if (did_work) UpdateWindowsWmTimer(); return did_work; } // Note: Caller is required to call timer->Reset() before calling StartTimer(). // TODO(jar): change API so that Reset() is called as part of StartTimer, making // the API a little less error prone. void TimerManager::StartTimer(Timer* timer) { // Make sure the timer is not running. if (IsTimerRunning(timer)) return; timers_.push(timer); // Priority queue will sort the timer into place. if (timers_.top() == timer) UpdateWindowsWmTimer(); // We are new head of queue. } void TimerManager::UpdateWindowsWmTimer() { if (!use_native_timers_) return; if (timers_.empty()) { KillTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this)); return; } int delay = GetCurrentDelay(); if (delay < USER_TIMER_MINIMUM) delay = USER_TIMER_MINIMUM; // Simulates malfunctioning, early firing timers. Pending tasks should // only be invoked when the delay they specify has elapsed. if (use_broken_delay_) delay = 10; // Create a WM_TIMER event that will wake us up to check for any pending // timers (in case the message loop was otherwise starving us). SetTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this), delay, NULL); } int TimerManager::GetCurrentDelay() { if (timers_.empty()) return -1; int delay = timers_.top()->current_delay(); if (delay < 0) delay = 0; return delay; } int TimerManager::MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { DCHECK(!lparam); DCHECK(this == message_loop()->timer_manager()); if (message_loop()->NestableTasksAllowed()) RunSomePendingTimers(); else UpdateWindowsWmTimer(); return 0; } MessageLoop* TimerManager::message_loop() { if (!message_loop_) message_loop_ = MessageLoop::current(); DCHECK(message_loop_ == MessageLoop::current()); return message_loop_; } HWND TimerManager::GetMessageHWND() { if (!message_hwnd_) { HINSTANCE hinst = GetModuleHandle(NULL); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = ::MessageWndProc; wc.hInstance = hinst; wc.lpszClassName = kWndClass; RegisterClassEx(&wc); message_hwnd_ = CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0); DCHECK(message_hwnd_); } return message_hwnd_; } //----------------------------------------------------------------------------- // SimpleTimer SimpleTimer::SimpleTimer(TimeDelta delay, Task* task, bool repeating) : timer_(static_cast<int>(delay.InMilliseconds()), task, repeating), owns_task_(true) { } SimpleTimer::~SimpleTimer() { Stop(); if (owns_task_) delete timer_.task(); } void SimpleTimer::Start() { DCHECK(timer_.task()); timer_.Reset(); MessageLoop::current()->timer_manager()->StartTimer(&timer_); } void SimpleTimer::Stop() { MessageLoop::current()->timer_manager()->StopTimer(&timer_); } bool SimpleTimer::IsRunning() const { return MessageLoop::current()->timer_manager()->IsTimerRunning(&timer_); } void SimpleTimer::Reset() { DCHECK(timer_.task()); MessageLoop::current()->timer_manager()->ResetTimer(&timer_); }
// Copyright 2008, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google 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. #include "base/timer.h" #include <mmsystem.h> #include "base/atomic_sequence_num.h" #include "base/logging.h" #include "base/message_loop.h" #include "base/task.h" // Note about hi-resolution timers. // This class would *like* to provide high resolution timers. Windows timers // using SetTimer() have a 10ms granularity. We have to use WM_TIMER as a // wakeup mechanism because the application can enter modal windows loops where // it is not running our MessageLoop; the only way to have our timers fire in // these cases is to post messages there. // // To provide sub-10ms timers, we process timers directly from our main // MessageLoop. For the common case, timers will be processed there as the // message loop does its normal work. However, we *also* set the system timer // so that WM_TIMER events fire. This mops up the case of timers not being // able to work in modal message loops. It is possible for the SetTimer to // pop and have no pending timers, because they could have already been // processed by the message loop itself. // // We use a single SetTimer corresponding to the timer that will expire // soonest. As new timers are created and destroyed, we update SetTimer. // Getting a spurrious SetTimer event firing is benign, as we'll just be // processing an empty timer queue. static const wchar_t kWndClass[] = L"Chrome_TimerMessageWindow"; static LRESULT CALLBACK MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { if (message == WM_TIMER) { // Timer not firing? Maybe you're suffering from a WM_PAINTstorm. Make sure // any WM_PAINT handler you have calls BeginPaint and EndPaint to validate // the invalid region, otherwise you will be flooded with paint messages // that trump WM_TIMER when PeekMessage is called. UINT_PTR timer_id = static_cast<UINT_PTR>(wparam); TimerManager* tm = reinterpret_cast<TimerManager*>(timer_id); return tm->MessageWndProc(hwnd, message, wparam, lparam); } return DefWindowProc(hwnd, message, wparam, lparam); } // A sequence number for all allocated times (used to break ties when // comparing times in the TimerManager, and assure FIFO execution sequence). static base::AtomicSequenceNumber timer_id_counter_; //----------------------------------------------------------------------------- // Timer Timer::Timer(int delay, Task* task, bool repeating) : task_(task), delay_(delay), repeating_(repeating) { timer_id_ = timer_id_counter_.GetNext(); DCHECK(delay >= 0); Reset(); } void Timer::Reset() { creation_time_ = Time::Now(); fire_time_ = creation_time_ + TimeDelta::FromMilliseconds(delay_); DHISTOGRAM_COUNTS(L"Timer.Durations", delay_); } //----------------------------------------------------------------------------- // TimerPQueue void TimerPQueue::RemoveTimer(Timer* timer) { const std::vector<Timer*>::iterator location = find(c.begin(), c.end(), timer); if (location != c.end()) { c.erase(location); make_heap(c.begin(), c.end(), TimerComparison()); } } bool TimerPQueue::ContainsTimer(const Timer* timer) const { return find(c.begin(), c.end(), timer) != c.end(); } //----------------------------------------------------------------------------- // TimerManager TimerManager::TimerManager() : message_hwnd_(NULL), use_broken_delay_(false), use_native_timers_(true), message_loop_(NULL) { // We've experimented with all sorts of timers, and initially tried // to avoid using timeBeginPeriod because it does affect the system // globally. However, after much investigation, it turns out that all // of the major plugins (flash, windows media 9-11, and quicktime) // already use timeBeginPeriod to increase the speed of the clock. // Since the browser must work with these plugins, the browser already // needs to support a fast clock. We may as well use this ourselves, // as it really is the best timer mechanism for our needs. timeBeginPeriod(1); // Initialize the Message HWND in the constructor so that the window // belongs to the same thread as the message loop (this is important!) GetMessageHWND(); } TimerManager::~TimerManager() { // Match timeBeginPeriod() from construction. timeEndPeriod(1); if (message_hwnd_ != NULL) DestroyWindow(message_hwnd_); // Be nice to unit tests, and discard and delete all timers along with the // embedded task objects by handing off to MessageLoop (which would have Run() // and optionally deleted the objects). while (timers_.size()) { Timer* pending = timers_.top(); timers_.pop(); message_loop_->DiscardTimer(pending); } } Timer* TimerManager::StartTimer(int delay, Task* task, bool repeating) { Timer* t = new Timer(delay, task, repeating); StartTimer(t); return t; } void TimerManager::StopTimer(Timer* timer) { // Make sure the timer is actually running. if (!IsTimerRunning(timer)) return; // Kill the active timer, and remove the pending entry from the queue. if (timer != timers_.top()) { timers_.RemoveTimer(timer); } else { timers_.pop(); UpdateWindowsWmTimer(); // We took away the head of our queue. } } void TimerManager::ResetTimer(Timer* timer) { StopTimer(timer); timer->Reset(); StartTimer(timer); } bool TimerManager::IsTimerRunning(const Timer* timer) const { return timers_.ContainsTimer(timer); } Timer* TimerManager::PeekTopTimer() { if (timers_.empty()) return NULL; return timers_.top(); } bool TimerManager::RunSomePendingTimers() { bool did_work = false; bool allowed_to_run = message_loop()->NestableTasksAllowed(); // Process a small group of timers. Cap the maximum number of timers we can // process so we don't deny cycles to other parts of the process when lots of // timers have been set. const int kMaxTimersPerCall = 2; for (int i = 0; i < kMaxTimersPerCall; ++i) { if (timers_.empty() || GetCurrentDelay() > 0) break; // Get a pending timer. Deal with updating the timers_ queue and setting // the TopTimer. We'll execute the timer task only after the timer queue // is back in a consistent state. Timer* pending = timers_.top(); // If pending task isn't invoked_later, then it must be possible to run it // now (i.e., current task needs to be reentrant). // TODO(jar): We may block tasks that we can queue from being popped. if (!message_loop()->NestableTasksAllowed() && !pending->task()->is_owned_by_message_loop()) break; timers_.pop(); did_work = true; // If the timer is repeating, add it back to the list of timers to process. if (pending->repeating()) { pending->Reset(); timers_.push(pending); } message_loop()->RunTimerTask(pending); } // Restart the WM_TIMER (if necessary). if (did_work) UpdateWindowsWmTimer(); return did_work; } // Note: Caller is required to call timer->Reset() before calling StartTimer(). // TODO(jar): change API so that Reset() is called as part of StartTimer, making // the API a little less error prone. void TimerManager::StartTimer(Timer* timer) { // Make sure the timer is not running. if (IsTimerRunning(timer)) return; timers_.push(timer); // Priority queue will sort the timer into place. if (timers_.top() == timer) UpdateWindowsWmTimer(); // We are new head of queue. } void TimerManager::UpdateWindowsWmTimer() { if (!use_native_timers_) return; if (timers_.empty()) { KillTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this)); return; } int delay = GetCurrentDelay(); if (delay < USER_TIMER_MINIMUM) delay = USER_TIMER_MINIMUM; // Simulates malfunctioning, early firing timers. Pending tasks should // only be invoked when the delay they specify has elapsed. if (use_broken_delay_) delay = 10; // Create a WM_TIMER event that will wake us up to check for any pending // timers (in case the message loop was otherwise starving us). SetTimer(GetMessageHWND(), reinterpret_cast<UINT_PTR>(this), delay, NULL); } int TimerManager::GetCurrentDelay() { if (timers_.empty()) return -1; int delay = timers_.top()->current_delay(); if (delay < 0) delay = 0; return delay; } int TimerManager::MessageWndProc(HWND hwnd, UINT message, WPARAM wparam, LPARAM lparam) { DCHECK(!lparam); DCHECK(this == message_loop()->timer_manager()); if (message_loop()->NestableTasksAllowed()) RunSomePendingTimers(); else UpdateWindowsWmTimer(); return 0; } MessageLoop* TimerManager::message_loop() { if (!message_loop_) message_loop_ = MessageLoop::current(); DCHECK(message_loop_ == MessageLoop::current()); return message_loop_; } HWND TimerManager::GetMessageHWND() { if (!message_hwnd_) { HINSTANCE hinst = GetModuleHandle(NULL); WNDCLASSEX wc = {0}; wc.cbSize = sizeof(wc); wc.lpfnWndProc = ::MessageWndProc; wc.hInstance = hinst; wc.lpszClassName = kWndClass; RegisterClassEx(&wc); message_hwnd_ = CreateWindow(kWndClass, 0, 0, 0, 0, 0, 0, HWND_MESSAGE, 0, hinst, 0); DCHECK(message_hwnd_); } return message_hwnd_; } //----------------------------------------------------------------------------- // SimpleTimer SimpleTimer::SimpleTimer(TimeDelta delay, Task* task, bool repeating) : timer_(static_cast<int>(delay.InMilliseconds()), task, repeating), owns_task_(true) { } SimpleTimer::~SimpleTimer() { Stop(); if (owns_task_) delete timer_.task(); } void SimpleTimer::Start() { DCHECK(timer_.task()); timer_.Reset(); MessageLoop::current()->timer_manager()->StartTimer(&timer_); } void SimpleTimer::Stop() { MessageLoop::current()->timer_manager()->StopTimer(&timer_); } bool SimpleTimer::IsRunning() const { return MessageLoop::current()->timer_manager()->IsTimerRunning(&timer_); } void SimpleTimer::Reset() { DCHECK(timer_.task()); MessageLoop::current()->timer_manager()->ResetTimer(&timer_); }
fix initialization order warning
fix initialization order warning git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@757 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
ropik/chromium,yitian134/chromium,adobe/chromium,adobe/chromium,adobe/chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,yitian134/chromium,adobe/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,ropik/chromium,adobe/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium,adobe/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,yitian134/chromium,gavinp/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,yitian134/chromium,ropik/chromium,gavinp/chromium,gavinp/chromium,ropik/chromium,gavinp/chromium,yitian134/chromium,yitian134/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,gavinp/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,adobe/chromium,gavinp/chromium,Crystalnix/house-of-life-chromium,Crystalnix/house-of-life-chromium,ropik/chromium
52098898b463923a01a0bf3d18d6fb9f96c8d5ef
tools/lli/lli.cpp
tools/lli/lli.cpp
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Type.h" #include "llvm/Bytecode/Reader.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/System/Signals.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { try { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); sys::PrintStackTraceOnErrorSignal(); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; try { MP = getBytecodeModuleProvider(InputFile); } catch (std::string &err) { std::cerr << "Error loading program '" << InputFile << "': " << err << "\n"; exit(1); } ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, do // it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn || Fn->isExternal()) { std::cerr << "'main' function not found in module.\n"; return -1; } // Run main... int Result = EE->runFunctionAsMain(Fn, InputArgv, envp); // If the program didn't explicitly call exit, call exit now, for the program. // This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, (Type *)0); std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = Result; Args.push_back(ResultGV); EE->runFunction(Exit, Args); std::cerr << "ERROR: exit(" << Result << ") returned!\n"; abort(); } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } abort(); }
//===- lli.cpp - LLVM Interpreter / Dynamic compiler ----------------------===// // // The LLVM Compiler Infrastructure // // This file was developed by the LLVM research group and is distributed under // the University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This utility provides a simple wrapper around the LLVM Execution Engines, // which allow the direct execution of LLVM programs through a Just-In-Time // compiler, or through an intepreter if no JIT is available for this platform. // //===----------------------------------------------------------------------===// #include "llvm/Module.h" #include "llvm/ModuleProvider.h" #include "llvm/Type.h" #include "llvm/Bytecode/Reader.h" #include "llvm/ExecutionEngine/ExecutionEngine.h" #include "llvm/ExecutionEngine/GenericValue.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/PluginLoader.h" #include "llvm/System/Signals.h" #include <iostream> using namespace llvm; namespace { cl::opt<std::string> InputFile(cl::desc("<input bytecode>"), cl::Positional, cl::init("-")); cl::list<std::string> InputArgv(cl::ConsumeAfter, cl::desc("<program arguments>...")); cl::opt<bool> ForceInterpreter("force-interpreter", cl::desc("Force interpretation: disable JIT"), cl::init(false)); cl::opt<std::string> FakeArgv0("fake-argv0", cl::desc("Override the 'argv[0]' value passed into the executing" " program"), cl::value_desc("executable")); } //===----------------------------------------------------------------------===// // main Driver function // int main(int argc, char **argv, char * const *envp) { try { cl::ParseCommandLineOptions(argc, argv, " llvm interpreter & dynamic compiler\n"); sys::PrintStackTraceOnErrorSignal(); // Load the bytecode... std::string ErrorMsg; ModuleProvider *MP = 0; try { MP = getBytecodeModuleProvider(InputFile); } catch (std::string &err) { std::cerr << "Error loading program '" << InputFile << "': " << err << "\n"; exit(1); } ExecutionEngine *EE = ExecutionEngine::create(MP, ForceInterpreter); assert(EE && "Couldn't create an ExecutionEngine, not even an interpreter?"); // If the user specifically requested an argv[0] to pass into the program, do // it now. if (!FakeArgv0.empty()) { InputFile = FakeArgv0; } else { // Otherwise, if there is a .bc suffix on the executable strip it off, it // might confuse the program. if (InputFile.rfind(".bc") == InputFile.length() - 3) InputFile.erase(InputFile.length() - 3); } // Add the module's name to the start of the vector of arguments to main(). InputArgv.insert(InputArgv.begin(), InputFile); // Call the main function from M as if its signature were: // int main (int argc, char **argv, const char **envp) // using the contents of Args to determine argc & argv, and the contents of // EnvVars to determine envp. // Function *Fn = MP->getModule()->getMainFunction(); if (!Fn) { std::cerr << "'main' function not found in module.\n"; return -1; } // Run main... int Result = EE->runFunctionAsMain(Fn, InputArgv, envp); // If the program didn't explicitly call exit, call exit now, for the program. // This ensures that any atexit handlers get called correctly. Function *Exit = MP->getModule()->getOrInsertFunction("exit", Type::VoidTy, Type::IntTy, (Type *)0); std::vector<GenericValue> Args; GenericValue ResultGV; ResultGV.IntVal = Result; Args.push_back(ResultGV); EE->runFunction(Exit, Args); std::cerr << "ERROR: exit(" << Result << ") returned!\n"; abort(); } catch (const std::string& msg) { std::cerr << argv[0] << ": " << msg << "\n"; } catch (...) { std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n"; } abort(); }
Revert my previous patch which broke due to lazy streaming of functions from .bc files.
Revert my previous patch which broke due to lazy streaming of functions from .bc files. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@24575 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
GPUOpen-Drivers/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,chubbymaggie/asap,dslab-epfl/asap,llvm-mirror/llvm,chubbymaggie/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,dslab-epfl/asap,chubbymaggie/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,apple/swift-llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,llvm-mirror/llvm
00f7dea508eacc089b874223c532ff0b5e055e1e
src/bindings/cpp/tests/testcpp11_contextual_thread.cpp
src/bindings/cpp/tests/testcpp11_contextual_thread.cpp
#include <kdbthread.hpp> #include <gtest/gtest.h> using namespace kdb; void foo1(Coordinator & gc, KeySet & ks) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); ThreadContext c1(gc); ThreadValue<int> v1(ks, c1, specKey); assert(v1 == 8); v1 = 5; assert(v1 == 5); std::this_thread::sleep_for(std::chrono::seconds(1)); assert(v1 == 5); } void foo2(Coordinator & gc, KeySet & ks) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); ThreadContext c2(gc); ThreadValue<int> v2(ks, c2, specKey); assert (v2 == 5); std::this_thread::sleep_for(std::chrono::seconds(1)); c2.update(); assert (v2 == 5); v2 = 12; assert (v2 == 12); } TEST(test_contextual_thread, instanciation) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); KeySet ks; ks.append(Key("user/hello", KEY_VALUE, "22", KEY_END)); Coordinator gc; ThreadContext c(gc); ThreadValue<int> v(ks, c, specKey); assert(v == 22); v = 8; assert (v== 8); std::thread t1(foo1, std::ref(gc), std::ref(ks)); std::this_thread::sleep_for(std::chrono::milliseconds(500)); c.update(); assert (v == 5); std::thread t2(foo2, std::ref(gc), std::ref(ks)); t1.join(); t2.join(); c.update(); assert (v == 12); ks.append(Key("user/activate", KEY_VALUE, "88", KEY_END)); v.activate(); assert (v==88); }
#include <kdbthread.hpp> #include <kdbprivate.h> #include <gtest/gtest.h> using namespace kdb; void foo1(Coordinator & gc, KeySet & ks) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); ThreadContext c1(gc); ThreadValue<int> v1(ks, c1, specKey); ASSERT_EQ(v1, 8); v1 = 5; ASSERT_EQ(v1, 5); std::this_thread::sleep_for(std::chrono::milliseconds(100)); ASSERT_EQ(v1, 5); } void foo2(Coordinator & gc, KeySet & ks) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); ThreadContext c2(gc); ThreadValue<int> v2(ks, c2, specKey); ASSERT_EQ(v2, 5); std::this_thread::sleep_for(std::chrono::milliseconds(100)); c2.update(); ASSERT_EQ(v2, 5); v2 = 12; ASSERT_EQ(v2, 12); } TEST(test_contextual_thread, instanciation) { Key specKey("/hello", KEY_CASCADING_NAME, KEY_END); KeySet ks; ks.append(Key("user/hello", KEY_VALUE, "22", KEY_END)); Coordinator gc; ThreadContext c(gc); ThreadValue<int> v(ks, c, specKey); ASSERT_EQ(v, 22); v = 8; ASSERT_EQ(v, 8); std::thread t1(foo1, std::ref(gc), std::ref(ks)); std::this_thread::sleep_for(std::chrono::milliseconds(50)); c.update(); ASSERT_EQ(v, 5); std::thread t2(foo2, std::ref(gc), std::ref(ks)); t1.join(); t2.join(); c.update(); ASSERT_EQ(v, 12); ks.append(Key("user/activate", KEY_VALUE, "88", KEY_END)); v.activate(); ASSERT_EQ(v, 88); } class Activate: public kdb::Layer { public: std::string id() const override { return "activate"; } std::string operator()() const override { return "active"; } }; void activate1(Coordinator & gc, KeySet & ks) { Key specKey("/act/%activate%", KEY_CASCADING_NAME, KEY_END); ThreadContext c1(gc); ThreadValue<int> v1(ks, c1, specKey); ASSERT_EQ(v1, 10); } TEST(test_contextual_thread, activate) { Key specKey("/act/%activate%", KEY_CASCADING_NAME, KEY_END); KeySet ks; ks.append(Key("user/act/%", KEY_VALUE, "10", KEY_END)); // not active layer ks.append(Key("user/act/active", KEY_VALUE, "22", KEY_END)); Coordinator gc; ThreadContext c(gc); ThreadValue<int> v(ks, c, specKey); ASSERT_EQ(v, 10); std::thread t1(activate1, std::ref(gc), std::ref(ks)); ASSERT_EQ(v, 10); c.activate<Activate>(); ASSERT_EQ(v, 22); t1.join(); ASSERT_EQ(v, 22); }
add activate test case
add activate test case
C++
bsd-3-clause
mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,e1528532/libelektra,e1528532/libelektra,BernhardDenner/libelektra,petermax2/libelektra,mpranj/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,mpranj/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,e1528532/libelektra,e1528532/libelektra,petermax2/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,mpranj/libelektra,BernhardDenner/libelektra,mpranj/libelektra,petermax2/libelektra,e1528532/libelektra,BernhardDenner/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,e1528532/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,BernhardDenner/libelektra,petermax2/libelektra,e1528532/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,ElektraInitiative/libelektra,mpranj/libelektra,ElektraInitiative/libelektra,petermax2/libelektra,mpranj/libelektra,BernhardDenner/libelektra,petermax2/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,BernhardDenner/libelektra,mpranj/libelektra
e0a5197fffd077088b70106b2f1737f331f2a1c0
lib/CodeGen/CGLoopInfo.cpp
lib/CodeGen/CGLoopInfo.cpp
//===---- CGLoopInfo.cpp - LLVM CodeGen for loop metadata -*- C++ -*-------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CGLoopInfo.h" #include "clang/AST/Attr.h" #include "clang/Sema/LoopHint.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Metadata.h" using namespace clang::CodeGen; using namespace llvm; static MDNode *createMetadata(LLVMContext &Ctx, const LoopAttributes &Attrs) { if (!Attrs.IsParallel && Attrs.VectorizerWidth == 0 && Attrs.VectorizerUnroll == 0 && Attrs.VectorizerEnable == LoopAttributes::VecUnspecified) return nullptr; SmallVector<Metadata *, 4> Args; // Reserve operand 0 for loop id self reference. auto TempNode = MDNode::getTemporary(Ctx, None); Args.push_back(TempNode.get()); // Setting vectorizer.width if (Attrs.VectorizerWidth > 0) { Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.vectorize.width"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt32Ty(Ctx), Attrs.VectorizerWidth))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Setting vectorizer.unroll if (Attrs.VectorizerUnroll > 0) { Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.interleave.count"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt32Ty(Ctx), Attrs.VectorizerUnroll))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Setting vectorizer.enable if (Attrs.VectorizerEnable != LoopAttributes::VecUnspecified) { Metadata *Vals[] = { MDString::get(Ctx, "llvm.loop.vectorize.enable"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt1Ty(Ctx), (Attrs.VectorizerEnable == LoopAttributes::VecEnable)))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Set the first operand to itself. MDNode *LoopID = MDNode::get(Ctx, Args); LoopID->replaceOperandWith(0, LoopID); return LoopID; } LoopAttributes::LoopAttributes(bool IsParallel) : IsParallel(IsParallel), VectorizerEnable(LoopAttributes::VecUnspecified), VectorizerWidth(0), VectorizerUnroll(0) {} void LoopAttributes::clear() { IsParallel = false; VectorizerWidth = 0; VectorizerUnroll = 0; VectorizerEnable = LoopAttributes::VecUnspecified; } LoopInfo::LoopInfo(BasicBlock *Header, const LoopAttributes &Attrs) : LoopID(nullptr), Header(Header), Attrs(Attrs) { LoopID = createMetadata(Header->getContext(), Attrs); } void LoopInfoStack::push(BasicBlock *Header, ArrayRef<const Attr *> Attrs) { for (const auto *Attr : Attrs) { const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr); // Skip non loop hint attributes if (!LH) continue; LoopHintAttr::OptionType Option = LH->getOption(); LoopHintAttr::LoopHintState State = LH->getState(); switch (Option) { case LoopHintAttr::Vectorize: case LoopHintAttr::Interleave: if (State == LoopHintAttr::AssumeSafety) { // Apply "llvm.mem.parallel_loop_access" metadata to load/stores. setParallel(true); } break; case LoopHintAttr::VectorizeWidth: case LoopHintAttr::InterleaveCount: case LoopHintAttr::Unroll: case LoopHintAttr::UnrollCount: // Nothing to do here for these loop hints. break; } } Active.push_back(LoopInfo(Header, StagedAttrs)); // Clear the attributes so nested loops do not inherit them. StagedAttrs.clear(); } void LoopInfoStack::pop() { assert(!Active.empty() && "No active loops to pop"); Active.pop_back(); } void LoopInfoStack::InsertHelper(Instruction *I) const { if (!hasInfo()) return; const LoopInfo &L = getInfo(); if (!L.getLoopID()) return; if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) { for (unsigned i = 0, ie = TI->getNumSuccessors(); i < ie; ++i) if (TI->getSuccessor(i) == L.getHeader()) { TI->setMetadata("llvm.loop", L.getLoopID()); break; } return; } if (L.getAttributes().IsParallel && I->mayReadOrWriteMemory()) I->setMetadata("llvm.mem.parallel_loop_access", L.getLoopID()); }
//===---- CGLoopInfo.cpp - LLVM CodeGen for loop metadata -*- C++ -*-------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "CGLoopInfo.h" #include "clang/AST/Attr.h" #include "clang/Sema/LoopHint.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/InstrTypes.h" #include "llvm/IR/Instructions.h" #include "llvm/IR/Metadata.h" using namespace clang::CodeGen; using namespace llvm; static MDNode *createMetadata(LLVMContext &Ctx, const LoopAttributes &Attrs) { if (!Attrs.IsParallel && Attrs.VectorizerWidth == 0 && Attrs.VectorizerUnroll == 0 && Attrs.VectorizerEnable == LoopAttributes::VecUnspecified) return nullptr; SmallVector<Metadata *, 4> Args; // Reserve operand 0 for loop id self reference. auto TempNode = MDNode::getTemporary(Ctx, None); Args.push_back(TempNode.get()); // Setting vectorizer.width if (Attrs.VectorizerWidth > 0) { Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.vectorize.width"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt32Ty(Ctx), Attrs.VectorizerWidth))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Setting vectorizer.unroll if (Attrs.VectorizerUnroll > 0) { Metadata *Vals[] = {MDString::get(Ctx, "llvm.loop.interleave.count"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt32Ty(Ctx), Attrs.VectorizerUnroll))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Setting vectorizer.enable if (Attrs.VectorizerEnable != LoopAttributes::VecUnspecified) { Metadata *Vals[] = { MDString::get(Ctx, "llvm.loop.vectorize.enable"), ConstantAsMetadata::get(ConstantInt::get( Type::getInt1Ty(Ctx), (Attrs.VectorizerEnable == LoopAttributes::VecEnable)))}; Args.push_back(MDNode::get(Ctx, Vals)); } // Set the first operand to itself. MDNode *LoopID = MDNode::get(Ctx, Args); LoopID->replaceOperandWith(0, LoopID); return LoopID; } LoopAttributes::LoopAttributes(bool IsParallel) : IsParallel(IsParallel), VectorizerEnable(LoopAttributes::VecUnspecified), VectorizerWidth(0), VectorizerUnroll(0) {} void LoopAttributes::clear() { IsParallel = false; VectorizerWidth = 0; VectorizerUnroll = 0; VectorizerEnable = LoopAttributes::VecUnspecified; } LoopInfo::LoopInfo(BasicBlock *Header, const LoopAttributes &Attrs) : LoopID(nullptr), Header(Header), Attrs(Attrs) { LoopID = createMetadata(Header->getContext(), Attrs); } void LoopInfoStack::push(BasicBlock *Header, ArrayRef<const clang::Attr *> Attrs) { for (const auto *Attr : Attrs) { const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(Attr); // Skip non loop hint attributes if (!LH) continue; LoopHintAttr::OptionType Option = LH->getOption(); LoopHintAttr::LoopHintState State = LH->getState(); switch (Option) { case LoopHintAttr::Vectorize: case LoopHintAttr::Interleave: if (State == LoopHintAttr::AssumeSafety) { // Apply "llvm.mem.parallel_loop_access" metadata to load/stores. setParallel(true); } break; case LoopHintAttr::VectorizeWidth: case LoopHintAttr::InterleaveCount: case LoopHintAttr::Unroll: case LoopHintAttr::UnrollCount: // Nothing to do here for these loop hints. break; } } Active.push_back(LoopInfo(Header, StagedAttrs)); // Clear the attributes so nested loops do not inherit them. StagedAttrs.clear(); } void LoopInfoStack::pop() { assert(!Active.empty() && "No active loops to pop"); Active.pop_back(); } void LoopInfoStack::InsertHelper(Instruction *I) const { if (!hasInfo()) return; const LoopInfo &L = getInfo(); if (!L.getLoopID()) return; if (TerminatorInst *TI = dyn_cast<TerminatorInst>(I)) { for (unsigned i = 0, ie = TI->getNumSuccessors(); i < ie; ++i) if (TI->getSuccessor(i) == L.getHeader()) { TI->setMetadata("llvm.loop", L.getLoopID()); break; } return; } if (L.getAttributes().IsParallel && I->mayReadOrWriteMemory()) I->setMetadata("llvm.mem.parallel_loop_access", L.getLoopID()); }
Fix the MSVC2013 build
[IRGen] Fix the MSVC2013 build git-svn-id: ffe668792ed300d6c2daa1f6eba2e0aa28d7ec6c@239576 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang,llvm-mirror/clang,apple/swift-clang,llvm-mirror/clang,apple/swift-clang,apple/swift-clang,llvm-mirror/clang
aa4cae6f8aba4d09452f88ba78b49e9010fea572
Application/main.cpp
Application/main.cpp
/* * * C R I S S C R O S S * A multi purpose cross platform library. * formerly Codename "Technetium" * project started August 14, 2006 * * Copyright (c) 2006, Steven Noonan <[email protected]>, Rudolf Olah <[email protected]>, * and Miah Clayton <[email protected]>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of Uplink Laboratories 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. * */ #include "header.h" #include "universal_include.h" #include "datastructures/llist.h" #include "datastructures/rbtree.h" #include "core_console.h" #include "core_cpuid.h" #include "core_system.h" #include "tcpsocket.h" using namespace CrissCross::IO; using namespace CrissCross::Network; using namespace CrissCross::System; LList<TCPSocket *> *sockets; RedBlackTree<int,unsigned long *> *connections_per_host; int RunApplication ( int argc, char **argv ) { CoreConsole *console = new CoreConsole (); sockets = new LList<TCPSocket *>; connections_per_host = new RedBlackTree<int,unsigned long *>(); console->WriteLine ( "Creating CoreSystem..." ); CoreSystem *system = new CoreSystem (); console->WriteLine ( "Creating TCPSocket..." ); TCPSocket *socket = new TCPSocket (); TCPSocket *tsock = NULL; int active_connections = 0, sockets_per_second = 0; console->WriteLine ( "TCPSocket is listening on port 3193..." ); CoreAssert ( socket->Listen ( 3193 ) == 0 ); while ( true ) { tsock = NULL; sockets_per_second = 0; while ( ( tsock = socket->Accept() ) != NULL ) { sockets_per_second++; u_long host = tsock->GetRemoteHost(); RedBlackTree<int,u_long *>::nodeType *node; node = connections_per_host->findNode ( &host ); if ( node != NULL ) { node->data++; if ( node->data > 5 ) { socket->Ban ( host ); console->WriteLine ( "Connection flood from '%s'!", tsock->GetRemoteIP() ); delete tsock; for ( int i = 0; sockets->ValidIndex ( i ); i++ ) { tsock = sockets->GetData(i); if ( tsock->GetRemoteHost() == host ) { sockets->RemoveData ( i ); delete tsock; i--; } } continue; } } else { connections_per_host->PutData ( &host, 1 ); } sockets->PutData ( tsock ); } for ( int i = 0; sockets->ValidIndex ( i ); i++ ) { tsock = sockets->GetData ( i ); std::string data; int result = tsock->Read ( data, 1024 ); if ( result == -2 ) // Socket closed. { sockets->RemoveData ( i ); delete tsock; i--; // This index has changed. } else { } } system->ThreadSleep ( 1000 ); } delete system; delete socket; delete console; return 0; }
/* * * C R I S S C R O S S * A multi purpose cross platform library. * formerly Codename "Technetium" * project started August 14, 2006 * * Copyright (c) 2006, Steven Noonan <[email protected]>, Rudolf Olah <[email protected]>, * and Miah Clayton <[email protected]>. All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are * permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this list * of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this * list of conditions and the following disclaimer in the documentation and/or other * materials provided with the distribution. * * Neither the name of Uplink Laboratories 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. * */ #include "header.h" #include "universal_include.h" #include "datastructures/llist.h" #include "datastructures/rbtree.h" #include "core_console.h" #include "core_cpuid.h" #include "core_system.h" #include "tcpsocket.h" using namespace CrissCross::IO; using namespace CrissCross::Network; using namespace CrissCross::System; LList<TCPSocket *> *sockets; RedBlackTree<int,unsigned long *> *connections_per_host; int RunApplication ( int argc, char **argv ) { CoreConsole *console = new CoreConsole (); sockets = new LList<TCPSocket *>; connections_per_host = new RedBlackTree<int,unsigned long *>(); console->WriteLine ( "Creating CoreSystem..." ); CoreSystem *system = new CoreSystem (); console->WriteLine ( "Creating TCPSocket..." ); TCPSocket *socket = new TCPSocket (); TCPSocket *tsock = NULL; int sockets_per_second = 0, retval = 0, breakout = 0; console->Write ( "TCPSocket is listening on port 3193... " ); retval = socket->Listen ( 3193 ); console->WriteLine ( "retval == %d", retval ); CoreAssert ( retval == 0 ); while ( !breakout ) { tsock = NULL; sockets_per_second = 0; while ( ( tsock = socket->Accept() ) != NULL ) { sockets_per_second++; u_long host = tsock->GetRemoteHost(); RedBlackTree<int,u_long *>::nodeType *node; node = connections_per_host->findNode ( &host ); if ( node != NULL ) { node->data++; if ( node->data > 5 ) { socket->Ban ( host ); console->WriteLine ( "Connection flood from '%s'!", tsock->GetRemoteIP() ); delete tsock; for ( int i = 0; sockets->ValidIndex ( i ); i++ ) { tsock = sockets->GetData(i); if ( tsock->GetRemoteHost() == host ) { sockets->RemoveData ( i ); delete tsock; i--; } } continue; } } else { connections_per_host->PutData ( &host, 1 ); } sockets->PutData ( tsock ); } for ( int i = 0; sockets->ValidIndex ( i ); i++ ) { tsock = sockets->GetData ( i ); std::string data; int result = tsock->Read ( data, 1024 ); if ( result == -2 ) // Socket closed. { sockets->RemoveData ( i ); delete tsock; i--; // This index has changed. } else { console->WriteLine ( "%s", data.c_str() ); if ( strcasecmp ( data.c_str(), "die" ) == 0 ) breakout = true; } } system->ThreadSleep ( 1000 ); } while ( sockets->ValidIndex ( 0 ) ) { tsock = sockets->GetData ( 0 ); sockets->RemoveData ( 0 ); delete tsock; } delete sockets; delete connections_per_host; delete system; delete socket; delete console; return 0; }
Fix for Windows.
Fix for Windows.
C++
bsd-3-clause
skydevgit/crisscross,tazodie/tazodie-crisscross,tazodie/tazodie-crisscross,skydevgit/crisscross,tazodie/tazodie-crisscross,skydevgit/crisscross
aa52b47d77aa18dea2b416b2721ebe2f696d9cb9
bogoSort.cpp
bogoSort.cpp
/*The following code implements the exceedingly inefficient bogo sort (also known as slow sort or stupid sort) algorithm to sort a list of integers in ascending order. It has a factorial class complexity. Since this is the non-deterministic version of the algorithm, there is a chance that it may never finish. This is not a bug.*/ #include <iostream> #include <random> #include <ctime> #include <chrono> void swap(int&, int&); void shuffle(int*, int); void bogoSort(int*, int); bool isSorted(int*, int); int main() { int size = 0; char ch; std::cout << "Enter the size of the list." << std::endl; std::cin >> size; int *input = new int[size]; std::cout << "Enter the numbers." << std::endl; for(int i = 0; i < size; i++) std::cin >> input[i]; std::cout<<"Beginning bogo sort of the list..."<< std::endl; auto start = std::chrono::high_resolution_clock::now(); bogoSort(input, size); std::cout << "The sorted list is:" << std::endl; for(int i = 0; i < size; i++) std::cout << input[i] << " "; std::cout << "\n"; auto stop = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "\nTime taken is " << diff.count() << " seconds." << std::endl; std::cout << "Thank you." << std::endl; delete [] input; } void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } void shuffle(int *input, int size) // Knuth-Fisher-Yates shuffle { int range = size - 1, i = 0, index = 0; std::mt19937 rand(time(0)); while(i != size) { std::uniform_int_distribution<int> roll(0, range); index = roll(rand); swap(input[index], input[range]); i++; range--; } } void bogoSort(int *input, int size) // picks a random permutation of the list and checks if it is in sorted order { while(!isSorted(input, size)) shuffle(input, size); } bool isSorted(int *input, int size) { if (size == 2) return input[0] > input[1] ? false : true; // when there are only two elements in the list for(int i = 1; i < size - 1; i++) if(!(input[i] >= input[i - 1] && input[i] <= input[i + 1])) return false; return true; }
/*The following code implements the exceedingly inefficient bogo sort (also known as slow sort or stupid sort) algorithm to sort a list of integers in ascending order. It has a factorial class worst-case complexity. Since this is the non-deterministic version of the algorithm, there is a chance that it may never finish. This is not a bug.*/ #include <iostream> #include <random> #include <ctime> #include <chrono> void swap(int&, int&); void shuffle(int*, int); void bogoSort(int*, int); bool isSorted(int*, int); int main() { int size = 0; char ch; std::cout << "Enter the size of the list." << std::endl; std::cin >> size; int *input = new int[size]; std::cout << "Enter the numbers." << std::endl; for(int i = 0; i < size; i++) std::cin >> input[i]; std::cout<<"Beginning bogo sort of the list..."<< std::endl; auto start = std::chrono::high_resolution_clock::now(); bogoSort(input, size); std::cout << "The sorted list is:" << std::endl; for(int i = 0; i < size; i++) std::cout << input[i] << " "; std::cout << "\n"; auto stop = std::chrono::high_resolution_clock::now(); auto diff = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cout << "\nTime taken is " << diff.count() << " seconds." << std::endl; std::cout << "Thank you." << std::endl; delete [] input; } void swap(int &a, int &b) { int tmp = a; a = b; b = tmp; } void shuffle(int *input, int size) // Knuth-Fisher-Yates shuffle { int range = size - 1, i = 0, index = 0; std::mt19937 rand(time(0)); while(i != size) { std::uniform_int_distribution<int> roll(0, range); index = roll(rand); swap(input[index], input[range]); i++; range--; } } void bogoSort(int *input, int size) // picks a random permutation of the list and checks if it is in sorted order { while(!isSorted(input, size)) shuffle(input, size); } bool isSorted(int *input, int size) { if (size == 2) return input[0] > input[1] ? false : true; // when there are only two elements in the list for(int i = 1; i < size - 1; i++) if(!(input[i] >= input[i - 1] && input[i] <= input[i + 1])) return false; return true; }
Update bogoSort.cpp
Update bogoSort.cpp
C++
mit
wedusk101/CPP
168028c2c8d2aa62d84b914bcdfbeda53d20aae9
benchmark.cpp
benchmark.cpp
#include <iostream> #include <unordered_map> #include <chrono> #include <cstdlib> #include <vector> #define NUM_VALS 100000 typedef size_t join_single_key_t; typedef size_t pos_t; typedef std::unordered_multimap<join_single_key_t, pos_t> hmap_t; void fillHashMaps(hmap_t &mmup1, hmap_t &mmup2) { std::srand(std::time(0)); for (size_t i = 0; i < NUM_VALS; ++i) { mmup1.insert(hmap_t::value_type(std::rand(), std::rand())); mmup2.insert(hmap_t::value_type(std::rand(), std::rand())); } } size_t runWithFreshMap() { // Initialize mmup hmap_t mmup, mmup2, fresh_mmup; fillHashMaps(mmup, mmup2); // start the timer auto t0 = std::chrono::high_resolution_clock::now(); // merge hash maps in fresh hash map fresh_mmup.insert(mmup.begin(), mmup.end()); fresh_mmup.insert(mmup2.begin(), mmup2.end()); // end the timer auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "With fresh hash map: " << (t1 - t0).count() << " ticks" << std::endl; return (t1-t0).count(); } size_t runWithReuseMap() { hmap_t mmup, mmup2; fillHashMaps(mmup, mmup2); // start timer auto t0 = std::chrono::high_resolution_clock::now(); // merge hash maps with inserting second in first mmup.insert(mmup2.begin(), mmup2.end()); // end timer 2 auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "With reusing one hash map: " << (t1 - t0).count() << " ticks" << std::endl; return (t1-t0).count(); } size_t runWithReserveOnEmptyMap() { hmap_t mmup, mmup2, freshMap; fillHashMaps(mmup, mmup2); auto t0 = std::chrono::high_resolution_clock::now(); freshMap.reserve(mmup.size() + mmup2.size()); freshMap.insert(mmup.begin(), mmup.end()); freshMap.insert(mmup2.begin(), mmup2.end()); auto t1 = std::chrono::high_resolution_clock::now(); return (t1-t0).count(); } size_t runWithCopyFirstReserve() { hmap_t mmup, mmup2, freshMap; fillHashMaps(mmup, mmup2); auto t0 = std::chrono::high_resolution_clock::now(); freshMap = mmup; freshMap.reserve(freshMap.size() + mmup2.size()); freshMap.insert(mmup2.begin(), mmup2.end()); auto t1 = std::chrono::high_resolution_clock::now(); return (t1-t0).count(); } int main() { auto time1 = runWithFreshMap(); auto time2 = runWithReuseMap(); auto time3 = runWithReserveOnEmptyMap(); auto time4 = runWithCopyFirstReserve(); std::cout << "Second method speed increase over first: " << 1 / (time2/ (float) time1) << std::endl; std::cout << "Third method speed increase over first: " << 1 / (time3/ (float) time1) << std::endl; std::cout << "Fourth method speed increase over first: " << 1 / (time4/ (float) time1) << std::endl; return 0; }
#include <iostream> #include <unordered_map> #include <chrono> #include <cstdlib> #include <vector> #define NUM_VALS 100000 #define NUM_RUNS 5 typedef size_t join_single_key_t; typedef size_t pos_t; typedef std::unordered_multimap<join_single_key_t, pos_t> hmap_t; void fillHashMaps(hmap_t &mmup1, hmap_t &mmup2) { std::srand(std::time(0)); for (size_t i = 0; i < NUM_VALS; ++i) { mmup1.insert(hmap_t::value_type(std::rand(), std::rand())); mmup2.insert(hmap_t::value_type(std::rand(), std::rand())); } } size_t runWithFreshMap() { // Initialize mmup hmap_t mmup, mmup2, fresh_mmup; fillHashMaps(mmup, mmup2); // start the timer auto t0 = std::chrono::high_resolution_clock::now(); // merge hash maps in fresh hash map fresh_mmup.insert(mmup.begin(), mmup.end()); fresh_mmup.insert(mmup2.begin(), mmup2.end()); // end the timer auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "With fresh hash map: " << (t1 - t0).count() << " ticks" << std::endl; return (t1-t0).count(); } size_t runWithReuseMap() { hmap_t mmup, mmup2; fillHashMaps(mmup, mmup2); // start timer auto t0 = std::chrono::high_resolution_clock::now(); // merge hash maps with inserting second in first mmup.insert(mmup2.begin(), mmup2.end()); // end timer 2 auto t1 = std::chrono::high_resolution_clock::now(); std::cout << "With reusing one hash map: " << (t1 - t0).count() << " ticks" << std::endl; return (t1-t0).count(); } size_t runWithReserveOnEmptyMap() { hmap_t mmup, mmup2, freshMap; fillHashMaps(mmup, mmup2); auto t0 = std::chrono::high_resolution_clock::now(); freshMap.reserve(mmup.size() + mmup2.size()); freshMap.insert(mmup.begin(), mmup.end()); freshMap.insert(mmup2.begin(), mmup2.end()); auto t1 = std::chrono::high_resolution_clock::now(); return (t1-t0).count(); } size_t runWithCopyFirstReserve() { hmap_t mmup, mmup2, freshMap; fillHashMaps(mmup, mmup2); auto t0 = std::chrono::high_resolution_clock::now(); freshMap = mmup; freshMap.reserve(freshMap.size() + mmup2.size()); freshMap.insert(mmup2.begin(), mmup2.end()); auto t1 = std::chrono::high_resolution_clock::now(); return (t1-t0).count(); } size_t runWithReuseMapAndReserve() { hmap_t mmup, mmup2; fillHashMaps(mmup, mmup2); auto t0 = std::chrono::high_resolution_clock::now(); mmup.reserve(mmup.size() + mmup2.size()); mmup.insert(mmup2.begin(), mmup2.end()); auto t1 = std::chrono::high_resolution_clock::now(); return (t1-t0).count(); } size_t runNTimes(size_t (*fun)(), size_t numRuns=NUM_RUNS) { size_t sum = 0; for (size_t i = 0; i < numRuns; ++i) { sum += fun(); } return sum/numRuns; } int main() { auto time1 = runNTimes(runWithFreshMap); auto time2 = runNTimes(runWithReuseMap); auto time3 = runNTimes(runWithReserveOnEmptyMap); auto time4 = runNTimes(runWithCopyFirstReserve); auto time5 = runNTimes(runWithReuseMapAndReserve); std::cout << "Second method speed increase over first: " << 1 / (time2/ (float) time1) << std::endl; std::cout << "Third method speed increase over first: " << 1 / (time3/ (float) time1) << std::endl; std::cout << "Fourth method speed increase over first: " << 1 / (time4/ (float) time1) << std::endl; std::cout << "Fifth method speed increase over first: " << 1 / (time5/ (float) time1) << std::endl; return 0; }
Include multiple runs and last benchmark.
Include multiple runs and last benchmark.
C++
mit
kaihowl/mmup_benchmark
96f9cc9181403a93208cb44786c485ce44492eda
src/gallium/state_trackers/clover/api/device.cpp
src/gallium/state_trackers/clover/api/device.cpp
// // Copyright 2012 Francisco Jerez // // 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 "api/util.hpp" #include "core/platform.hpp" #include "core/device.hpp" using namespace clover; CLOVER_API cl_int clGetDeviceIDs(cl_platform_id d_platform, cl_device_type device_type, cl_uint num_entries, cl_device_id *rd_devices, cl_uint *rnum_devices) try { auto &platform = obj(d_platform); std::vector<cl_device_id> d_devs; if ((!num_entries && rd_devices) || (!rnum_devices && !rd_devices)) throw error(CL_INVALID_VALUE); // Collect matching devices for (device &dev : platform) { if (((device_type & CL_DEVICE_TYPE_DEFAULT) && dev == platform.front()) || (device_type & dev.type())) d_devs.push_back(desc(dev)); } if (d_devs.empty()) throw error(CL_DEVICE_NOT_FOUND); // ...and return the requested data. if (rnum_devices) *rnum_devices = d_devs.size(); if (rd_devices) copy(range(d_devs.begin(), std::min((unsigned)d_devs.size(), num_entries)), rd_devices); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clCreateSubDevices(cl_device_id d_dev, const cl_device_partition_property *props, cl_uint num_devs, cl_device_id *rd_devs, cl_uint *rnum_devs) { // There are no currently supported partitioning schemes. return CL_INVALID_VALUE; } CLOVER_API cl_int clRetainDevice(cl_device_id d_dev) try { obj(d_dev); // The reference count doesn't change for root devices. return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseDevice(cl_device_id d_dev) try { obj(d_dev); // The reference count doesn't change for root devices. return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetDeviceInfo(cl_device_id d_dev, cl_device_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &dev = obj(d_dev); switch (param) { case CL_DEVICE_TYPE: buf.as_scalar<cl_device_type>() = dev.type(); break; case CL_DEVICE_VENDOR_ID: buf.as_scalar<cl_uint>() = dev.vendor_id(); break; case CL_DEVICE_MAX_COMPUTE_UNITS: buf.as_scalar<cl_uint>() = dev.max_compute_units(); break; case CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS: buf.as_scalar<cl_uint>() = dev.max_block_size().size(); break; case CL_DEVICE_MAX_WORK_ITEM_SIZES: buf.as_vector<size_t>() = dev.max_block_size(); break; case CL_DEVICE_MAX_WORK_GROUP_SIZE: buf.as_scalar<size_t>() = dev.max_threads_per_block(); break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR: buf.as_scalar<cl_uint>() = 16; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT: buf.as_scalar<cl_uint>() = 8; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG: buf.as_scalar<cl_uint>() = 2; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE: buf.as_scalar<cl_uint>() = dev.has_doubles() ? 2 : 0; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_MAX_CLOCK_FREQUENCY: buf.as_scalar<cl_uint>() = dev.max_clock_frequency(); break; case CL_DEVICE_ADDRESS_BITS: buf.as_scalar<cl_uint>() = 32; break; case CL_DEVICE_MAX_READ_IMAGE_ARGS: buf.as_scalar<cl_uint>() = dev.max_images_read(); break; case CL_DEVICE_MAX_WRITE_IMAGE_ARGS: buf.as_scalar<cl_uint>() = dev.max_images_write(); break; case CL_DEVICE_MAX_MEM_ALLOC_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_alloc_size(); break; case CL_DEVICE_IMAGE2D_MAX_WIDTH: case CL_DEVICE_IMAGE2D_MAX_HEIGHT: buf.as_scalar<size_t>() = 1 << dev.max_image_levels_2d(); break; case CL_DEVICE_IMAGE3D_MAX_WIDTH: case CL_DEVICE_IMAGE3D_MAX_HEIGHT: case CL_DEVICE_IMAGE3D_MAX_DEPTH: buf.as_scalar<size_t>() = 1 << dev.max_image_levels_3d(); break; case CL_DEVICE_IMAGE_SUPPORT: buf.as_scalar<cl_bool>() = dev.image_support(); break; case CL_DEVICE_MAX_PARAMETER_SIZE: buf.as_scalar<size_t>() = dev.max_mem_input(); break; case CL_DEVICE_MAX_SAMPLERS: buf.as_scalar<cl_uint>() = dev.max_samplers(); break; case CL_DEVICE_MEM_BASE_ADDR_ALIGN: case CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE: buf.as_scalar<cl_uint>() = 128; break; case CL_DEVICE_SINGLE_FP_CONFIG: // This is the "mandated minimum single precision floating-point // capability" for OpenCL 1.1. In OpenCL 1.2, nothing is required for // custom devices. buf.as_scalar<cl_device_fp_config>() = CL_FP_INF_NAN | CL_FP_ROUND_TO_NEAREST; break; case CL_DEVICE_DOUBLE_FP_CONFIG: if (dev.has_doubles()) // This is the "mandated minimum double precision floating-point // capability" buf.as_scalar<cl_device_fp_config>() = CL_FP_FMA | CL_FP_ROUND_TO_NEAREST | CL_FP_ROUND_TO_ZERO | CL_FP_ROUND_TO_INF | CL_FP_INF_NAN | CL_FP_DENORM; else buf.as_scalar<cl_device_fp_config>() = 0; break; case CL_DEVICE_GLOBAL_MEM_CACHE_TYPE: buf.as_scalar<cl_device_mem_cache_type>() = CL_NONE; break; case CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_GLOBAL_MEM_CACHE_SIZE: buf.as_scalar<cl_ulong>() = 0; break; case CL_DEVICE_GLOBAL_MEM_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_global(); break; case CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: buf.as_scalar<cl_ulong>() = dev.max_const_buffer_size(); break; case CL_DEVICE_MAX_CONSTANT_ARGS: buf.as_scalar<cl_uint>() = dev.max_const_buffers(); break; case CL_DEVICE_LOCAL_MEM_TYPE: buf.as_scalar<cl_device_local_mem_type>() = CL_LOCAL; break; case CL_DEVICE_LOCAL_MEM_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_local(); break; case CL_DEVICE_ERROR_CORRECTION_SUPPORT: buf.as_scalar<cl_bool>() = CL_FALSE; break; case CL_DEVICE_PROFILING_TIMER_RESOLUTION: buf.as_scalar<size_t>() = 0; break; case CL_DEVICE_ENDIAN_LITTLE: buf.as_scalar<cl_bool>() = (dev.endianness() == PIPE_ENDIAN_LITTLE); break; case CL_DEVICE_AVAILABLE: case CL_DEVICE_COMPILER_AVAILABLE: buf.as_scalar<cl_bool>() = CL_TRUE; break; case CL_DEVICE_EXECUTION_CAPABILITIES: buf.as_scalar<cl_device_exec_capabilities>() = CL_EXEC_KERNEL; break; case CL_DEVICE_QUEUE_PROPERTIES: buf.as_scalar<cl_command_queue_properties>() = CL_QUEUE_PROFILING_ENABLE; break; case CL_DEVICE_NAME: buf.as_string() = dev.device_name(); break; case CL_DEVICE_VENDOR: buf.as_string() = dev.vendor_name(); break; case CL_DRIVER_VERSION: buf.as_string() = PACKAGE_VERSION; break; case CL_DEVICE_PROFILE: buf.as_string() = "FULL_PROFILE"; break; case CL_DEVICE_VERSION: buf.as_string() = "OpenCL 1.1 MESA " PACKAGE_VERSION; break; case CL_DEVICE_EXTENSIONS: buf.as_string() = dev.has_doubles() ? "cl_khr_fp64" : ""; break; case CL_DEVICE_PLATFORM: buf.as_scalar<cl_platform_id>() = desc(dev.platform); break; case CL_DEVICE_HOST_UNIFIED_MEMORY: buf.as_scalar<cl_bool>() = CL_TRUE; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR: buf.as_scalar<cl_uint>() = 16; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT: buf.as_scalar<cl_uint>() = 8; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_INT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG: buf.as_scalar<cl_uint>() = 2; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE: buf.as_scalar<cl_uint>() = dev.has_doubles() ? 2 : 0; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_OPENCL_C_VERSION: buf.as_string() = "OpenCL C 1.1"; break; case CL_DEVICE_PARENT_DEVICE: buf.as_scalar<cl_device_id>() = NULL; break; case CL_DEVICE_PARTITION_MAX_SUB_DEVICES: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_PARTITION_PROPERTIES: buf.as_vector<cl_device_partition_property>() = desc(property_list<cl_device_partition_property>()); break; case CL_DEVICE_PARTITION_AFFINITY_DOMAIN: buf.as_scalar<cl_device_affinity_domain>() = 0; break; case CL_DEVICE_PARTITION_TYPE: buf.as_vector<cl_device_partition_property>() = desc(property_list<cl_device_partition_property>()); break; case CL_DEVICE_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = 1; break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); }
// // Copyright 2012 Francisco Jerez // // 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 "api/util.hpp" #include "core/platform.hpp" #include "core/device.hpp" using namespace clover; CLOVER_API cl_int clGetDeviceIDs(cl_platform_id d_platform, cl_device_type device_type, cl_uint num_entries, cl_device_id *rd_devices, cl_uint *rnum_devices) try { auto &platform = obj(d_platform); std::vector<cl_device_id> d_devs; if ((!num_entries && rd_devices) || (!rnum_devices && !rd_devices)) throw error(CL_INVALID_VALUE); // Collect matching devices for (device &dev : platform) { if (((device_type & CL_DEVICE_TYPE_DEFAULT) && dev == platform.front()) || (device_type & dev.type())) d_devs.push_back(desc(dev)); } if (d_devs.empty()) throw error(CL_DEVICE_NOT_FOUND); // ...and return the requested data. if (rnum_devices) *rnum_devices = d_devs.size(); if (rd_devices) copy(range(d_devs.begin(), std::min((unsigned)d_devs.size(), num_entries)), rd_devices); return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clCreateSubDevices(cl_device_id d_dev, const cl_device_partition_property *props, cl_uint num_devs, cl_device_id *rd_devs, cl_uint *rnum_devs) { // There are no currently supported partitioning schemes. return CL_INVALID_VALUE; } CLOVER_API cl_int clRetainDevice(cl_device_id d_dev) try { obj(d_dev); // The reference count doesn't change for root devices. return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clReleaseDevice(cl_device_id d_dev) try { obj(d_dev); // The reference count doesn't change for root devices. return CL_SUCCESS; } catch (error &e) { return e.get(); } CLOVER_API cl_int clGetDeviceInfo(cl_device_id d_dev, cl_device_info param, size_t size, void *r_buf, size_t *r_size) try { property_buffer buf { r_buf, size, r_size }; auto &dev = obj(d_dev); switch (param) { case CL_DEVICE_TYPE: buf.as_scalar<cl_device_type>() = dev.type(); break; case CL_DEVICE_VENDOR_ID: buf.as_scalar<cl_uint>() = dev.vendor_id(); break; case CL_DEVICE_MAX_COMPUTE_UNITS: buf.as_scalar<cl_uint>() = dev.max_compute_units(); break; case CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS: buf.as_scalar<cl_uint>() = dev.max_block_size().size(); break; case CL_DEVICE_MAX_WORK_ITEM_SIZES: buf.as_vector<size_t>() = dev.max_block_size(); break; case CL_DEVICE_MAX_WORK_GROUP_SIZE: buf.as_scalar<size_t>() = dev.max_threads_per_block(); break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR: buf.as_scalar<cl_uint>() = 16; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT: buf.as_scalar<cl_uint>() = 8; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG: buf.as_scalar<cl_uint>() = 2; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE: buf.as_scalar<cl_uint>() = dev.has_doubles() ? 2 : 0; break; case CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_MAX_CLOCK_FREQUENCY: buf.as_scalar<cl_uint>() = dev.max_clock_frequency(); break; case CL_DEVICE_ADDRESS_BITS: buf.as_scalar<cl_uint>() = 32; break; case CL_DEVICE_MAX_READ_IMAGE_ARGS: buf.as_scalar<cl_uint>() = dev.max_images_read(); break; case CL_DEVICE_MAX_WRITE_IMAGE_ARGS: buf.as_scalar<cl_uint>() = dev.max_images_write(); break; case CL_DEVICE_MAX_MEM_ALLOC_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_alloc_size(); break; case CL_DEVICE_IMAGE2D_MAX_WIDTH: case CL_DEVICE_IMAGE2D_MAX_HEIGHT: buf.as_scalar<size_t>() = 1 << dev.max_image_levels_2d(); break; case CL_DEVICE_IMAGE3D_MAX_WIDTH: case CL_DEVICE_IMAGE3D_MAX_HEIGHT: case CL_DEVICE_IMAGE3D_MAX_DEPTH: buf.as_scalar<size_t>() = 1 << dev.max_image_levels_3d(); break; case CL_DEVICE_IMAGE_SUPPORT: buf.as_scalar<cl_bool>() = dev.image_support(); break; case CL_DEVICE_MAX_PARAMETER_SIZE: buf.as_scalar<size_t>() = dev.max_mem_input(); break; case CL_DEVICE_MAX_SAMPLERS: buf.as_scalar<cl_uint>() = dev.max_samplers(); break; case CL_DEVICE_MEM_BASE_ADDR_ALIGN: case CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE: buf.as_scalar<cl_uint>() = 128; break; case CL_DEVICE_SINGLE_FP_CONFIG: // This is the "mandated minimum single precision floating-point // capability" for OpenCL 1.1. In OpenCL 1.2, nothing is required for // custom devices. buf.as_scalar<cl_device_fp_config>() = CL_FP_INF_NAN | CL_FP_ROUND_TO_NEAREST; break; case CL_DEVICE_DOUBLE_FP_CONFIG: if (dev.has_doubles()) // This is the "mandated minimum double precision floating-point // capability" buf.as_scalar<cl_device_fp_config>() = CL_FP_FMA | CL_FP_ROUND_TO_NEAREST | CL_FP_ROUND_TO_ZERO | CL_FP_ROUND_TO_INF | CL_FP_INF_NAN | CL_FP_DENORM; else buf.as_scalar<cl_device_fp_config>() = 0; break; case CL_DEVICE_GLOBAL_MEM_CACHE_TYPE: buf.as_scalar<cl_device_mem_cache_type>() = CL_NONE; break; case CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_GLOBAL_MEM_CACHE_SIZE: buf.as_scalar<cl_ulong>() = 0; break; case CL_DEVICE_GLOBAL_MEM_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_global(); break; case CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE: buf.as_scalar<cl_ulong>() = dev.max_const_buffer_size(); break; case CL_DEVICE_MAX_CONSTANT_ARGS: buf.as_scalar<cl_uint>() = dev.max_const_buffers(); break; case CL_DEVICE_LOCAL_MEM_TYPE: buf.as_scalar<cl_device_local_mem_type>() = CL_LOCAL; break; case CL_DEVICE_LOCAL_MEM_SIZE: buf.as_scalar<cl_ulong>() = dev.max_mem_local(); break; case CL_DEVICE_ERROR_CORRECTION_SUPPORT: buf.as_scalar<cl_bool>() = CL_FALSE; break; case CL_DEVICE_PROFILING_TIMER_RESOLUTION: buf.as_scalar<size_t>() = 0; break; case CL_DEVICE_ENDIAN_LITTLE: buf.as_scalar<cl_bool>() = (dev.endianness() == PIPE_ENDIAN_LITTLE); break; case CL_DEVICE_AVAILABLE: case CL_DEVICE_COMPILER_AVAILABLE: buf.as_scalar<cl_bool>() = CL_TRUE; break; case CL_DEVICE_EXECUTION_CAPABILITIES: buf.as_scalar<cl_device_exec_capabilities>() = CL_EXEC_KERNEL; break; case CL_DEVICE_QUEUE_PROPERTIES: buf.as_scalar<cl_command_queue_properties>() = CL_QUEUE_PROFILING_ENABLE; break; case CL_DEVICE_NAME: buf.as_string() = dev.device_name(); break; case CL_DEVICE_VENDOR: buf.as_string() = dev.vendor_name(); break; case CL_DRIVER_VERSION: buf.as_string() = PACKAGE_VERSION; break; case CL_DEVICE_PROFILE: buf.as_string() = "FULL_PROFILE"; break; case CL_DEVICE_VERSION: buf.as_string() = "OpenCL 1.1 MESA " PACKAGE_VERSION; break; case CL_DEVICE_EXTENSIONS: buf.as_string() = dev.has_doubles() ? "cl_khr_fp64" : ""; break; case CL_DEVICE_PLATFORM: buf.as_scalar<cl_platform_id>() = desc(dev.platform); break; case CL_DEVICE_HOST_UNIFIED_MEMORY: buf.as_scalar<cl_bool>() = CL_TRUE; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR: buf.as_scalar<cl_uint>() = 16; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT: buf.as_scalar<cl_uint>() = 8; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_INT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG: buf.as_scalar<cl_uint>() = 2; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT: buf.as_scalar<cl_uint>() = 4; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE: buf.as_scalar<cl_uint>() = dev.has_doubles() ? 2 : 0; break; case CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_OPENCL_C_VERSION: buf.as_string() = "OpenCL C 1.1 "; break; case CL_DEVICE_PARENT_DEVICE: buf.as_scalar<cl_device_id>() = NULL; break; case CL_DEVICE_PARTITION_MAX_SUB_DEVICES: buf.as_scalar<cl_uint>() = 0; break; case CL_DEVICE_PARTITION_PROPERTIES: buf.as_vector<cl_device_partition_property>() = desc(property_list<cl_device_partition_property>()); break; case CL_DEVICE_PARTITION_AFFINITY_DOMAIN: buf.as_scalar<cl_device_affinity_domain>() = 0; break; case CL_DEVICE_PARTITION_TYPE: buf.as_vector<cl_device_partition_property>() = desc(property_list<cl_device_partition_property>()); break; case CL_DEVICE_REFERENCE_COUNT: buf.as_scalar<cl_uint>() = 1; break; default: throw error(CL_INVALID_VALUE); } return CL_SUCCESS; } catch (error &e) { return e.get(); }
Add a space at the end of CL_DEVICE_OPENCL_C_VERSION
clover: Add a space at the end of CL_DEVICE_OPENCL_C_VERSION This is required by the spec. Reviewed-by: Jan Vesely <[email protected]> Reviewed-by: Francisco Jerez <[email protected]>
C++
mit
metora/MesaGLSLCompiler,metora/MesaGLSLCompiler,metora/MesaGLSLCompiler
a73619f5a7d6b54f725ad33859fc3d3ce51ff92a
html_generator/cpp_syntax_highlighting.hpp
html_generator/cpp_syntax_highlighting.hpp
#pragma once #include <silicium/html/tree.hpp> #include "tags.hpp" inline bool is_brace(char const c) { static boost::string_ref const braces = "(){}<>[]"; return std::find(braces.begin(), braces.end(), c) != braces.end(); } enum class token_type { identifier, string, double_colon, brace, space, eof, other }; struct token { std::string content; token_type type; }; template <class RandomAccessIterator> token find_next_token(RandomAccessIterator begin, RandomAccessIterator end) { if (begin == end) { return {"", token_type::eof}; } if (isalnum(*begin)) { return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return !isalnum(c) && c != '_'; })), token_type::identifier}; } if (*begin == ':') { if (begin + 1 == end) { return {":", token_type::other}; } if (begin[1] != ':') { return {std::string(begin, begin + 2), token_type::other}; } return {"::", token_type::double_colon}; } if (!isprint(*begin)) { return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return isprint(c); })), token_type::space}; } if (is_brace(*begin)) { return {std::string(begin, begin + 1), token_type::brace}; } if (*begin == '"' || *begin == '\'') { char first = *begin; bool escaped = false; RandomAccessIterator end_index = std::find_if(begin + 1, end, [&escaped, first](char c) { if (escaped) { escaped = false; return false; } if (c == '\\') { escaped = true; return false; } return (c == first); }); if (end_index == end) { throw std::invalid_argument("Number of quotes must be even"); } return {std::string(begin, end_index + 1), token_type::string}; } return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return isalnum(c) || c == '"' || c == ':' || c == '\''; })), token_type::other}; } inline auto render_code_raw(std::string code) { using namespace Si::html; return dynamic([code = std::move(code)](code_sink & sink) { static const boost::string_ref keywords[] = { "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq", "override", "final"}; auto i = code.begin(); for (;;) { token t = find_next_token(i, code.end()); token_switch: switch (t.type) { case token_type::eof: return; case token_type::string: tags::span(attribute("class", "stringLiteral"), text(t.content)) .generate(sink); break; case token_type::identifier: if (std::find(std::begin(keywords), std::end(keywords), t.content) != std::end(keywords)) { tags::span(attribute("class", "keyword"), text(t.content)) .generate(sink); } else { i += t.content.size(); token next = find_next_token(i, code.end()); if (next.type == token_type::double_colon) { tags::span(attribute("class", "names"), text(t.content)) .generate(sink); } else { text(t.content).generate(sink); } t = next; goto token_switch; } case token_type::double_colon: while (t.type == token_type::identifier || t.type == token_type::double_colon) { tags::span(attribute("class", "names"), text(t.content)) .generate(sink); i += t.content.size(); t = find_next_token(i, code.end()); } goto token_switch; case token_type::space: case token_type::other: case token_type::brace: text(t.content).generate(sink); } i += t.content.size(); } }); } inline auto render_code(std::string code) { using namespace Si::html; return tag("code", render_code_raw(std::move(code))); }
#pragma once #include <silicium/html/tree.hpp> #include "tags.hpp" inline bool is_brace(char const c) { static boost::string_ref const braces = "(){}<>[]"; return std::find(braces.begin(), braces.end(), c) != braces.end(); } enum class token_type { identifier, string, double_colon, brace, space, eof, other }; struct token { std::string content; token_type type; }; template <class RandomAccessIterator> token find_next_token(RandomAccessIterator begin, RandomAccessIterator end) { if (begin == end) { return {"", token_type::eof}; } if (isalnum(*begin)) { return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return !isalnum(c) && c != '_'; })), token_type::identifier}; } if (*begin == ':') { if (begin + 1 == end) { return {":", token_type::other}; } if (begin[1] != ':') { return {std::string(begin, begin + 2), token_type::other}; } return {"::", token_type::double_colon}; } if (!isprint(*begin)) { return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return isprint(c); })), token_type::space}; } if (is_brace(*begin)) { return {std::string(begin, begin + 1), token_type::brace}; } if (*begin == '"' || *begin == '\'') { char first = *begin; bool escaped = false; RandomAccessIterator end_index = std::find_if(begin + 1, end, [&escaped, first](char c) { if (escaped) { escaped = false; return false; } if (c == '\\') { escaped = true; return false; } return (c == first); }); if (end_index == end) { throw std::invalid_argument("Number of quotes must be even"); } return {std::string(begin, end_index + 1), token_type::string}; } return {std::string(begin, std::find_if(begin + 1, end, [](char c) { return isalnum(c) || c == '"' || c == ':' || c == '\''; })), token_type::other}; } inline auto render_code_raw(std::string code) { using namespace Si::html; return dynamic([code = std::move(code)](code_sink & sink) { static const boost::string_ref keywords[] = { "alignas", "alignof", "and", "and_eq", "asm", "auto", "bitand", "bitor", "bool", "break", "case", "catch", "char", "char16_t", "char32_t", "class", "compl", "const", "constexpr", "const_cast", "continue", "decltype", "default", "delete", "do", "double", "dynamic_cast", "else", "enum", "explicit", "export", "extern", "false", "float", "for", "friend", "goto", "if", "inline", "int", "long", "mutable", "namespace", "new", "noexcept", "not", "not_eq", "nullptr", "operator", "or", "or_eq", "private", "protected", "public", "register", "reinterpret_cast", "return", "short", "signed", "sizeof", "static", "static_assert", "static_cast", "struct", "switch", "template", "this", "thread_local", "throw", "true", "try", "typedef", "typeid", "typename", "union", "unsigned", "using", "virtual", "void", "volatile", "wchar_t", "while", "xor", "xor_eq", "override", "final"}; auto i = code.begin(); for (;;) { token t = find_next_token(i, code.end()); token_switch: switch (t.type) { case token_type::eof: return; case token_type::string: tags::span(attribute("class", "stringLiteral"), text(t.content)) .generate(sink); break; case token_type::identifier: if (std::find(std::begin(keywords), std::end(keywords), t.content) != std::end(keywords)) { tags::span(attribute("class", "keyword"), text(t.content)) .generate(sink); } else { i += t.content.size(); token next = find_next_token(i, code.end()); if (next.type == token_type::double_colon) { tags::span(attribute("class", "names"), text(t.content)) .generate(sink); } else { text(t.content).generate(sink); } t = next; goto token_switch; } // fall through case token_type::double_colon: while (t.type == token_type::identifier || t.type == token_type::double_colon) { tags::span(attribute("class", "names"), text(t.content)) .generate(sink); i += t.content.size(); t = find_next_token(i, code.end()); } goto token_switch; case token_type::space: case token_type::other: case token_type::brace: text(t.content).generate(sink); break; } i += t.content.size(); } }); } inline auto render_code(std::string code) { using namespace Si::html; return tag("code", render_code_raw(std::move(code))); }
clarify control flow in switch statement
clarify control flow in switch statement
C++
mit
mamazu/tyroxx-blog-generator,TyRoXx/tyroxx-blog-generator,mamazu/tyroxx-blog-generator,TyRoXx/tyroxx-blog-generator
29a6e80bf3ba0ccda61c81259bf47672ef6c22e1
ext/ruby_mapnik/_mapnik_expression.rb.cpp
ext/ruby_mapnik/_mapnik_expression.rb.cpp
/***************************************************************************** Copyright (C) 2011 Elliot Laster 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 "_mapnik_expression.rb.h" // Rice #include <rice/Data_Type.hpp> #include <rice/Constructor.hpp> #include <rice/Class.hpp> #include <rice/Enum.hpp> // Mapnik #include <mapnik/feature.hpp> #include <mapnik/filter_factory.hpp> #include <mapnik/expression_node.hpp> #include <mapnik/expression_string.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/parse_path.hpp> namespace { boost::shared_ptr<mapnik::expr_node> parse_expression_(std::string const& wkt){ return mapnik::parse_expression(wkt,"utf8"); } std::string expr_node_to_string_(boost::shared_ptr<mapnik::expr_node> node_ptr){ return mapnik::to_expression_string(*node_ptr); } // path expression mapnik::path_expression_ptr parse_path_(std::string const& path){ return mapnik::parse_path(path); } } void register_expression(Rice::Module rb_mapnik){ /* @@Module_var rb_mapnik = Mapnik */ Rice::Data_Type< boost::shared_ptr<mapnik::expr_node> > rb_cexpression = Rice::define_class_under< boost::shared_ptr<mapnik::expr_node> >(rb_mapnik, "Expression"); /* * Document-method: parse * call-seq: * parse(expression_string) * * @param [String] * * @return [Mapnk::Expression] a new expression */ rb_cexpression.define_singleton_method("parse", &parse_expression_); /* * Document-method: to_s * @return [String] a string representation of the expression */ rb_cexpression.define_method("to_s",&expr_node_to_string_); Rice::Data_Type< mapnik::path_expression_ptr > rb_cpath_expression = Rice::define_class_under< mapnik::path_expression_ptr >(rb_mapnik, "PathExpression"); // rb_cpath_expression.define_singleton_method("evaluate", &path_evaluate_); // rb_cpath_expression.define_method("to_s",&path_to_string_); /* * Document-method: parse * call-seq: * parse(path_expression_string) * * @param [String] * * @return [Mapnk::PathExpression] a new expression */ rb_cpath_expression.define_singleton_method("parse", &parse_path_); }
/***************************************************************************** Copyright (C) 2011 Elliot Laster 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 "_mapnik_expression.rb.h" // Rice #include <rice/Data_Type.hpp> #include <rice/Constructor.hpp> #include <rice/Class.hpp> #include <rice/Enum.hpp> // Mapnik #include <mapnik/feature.hpp> #include <mapnik/expression.hpp> #include <mapnik/expression_node.hpp> #include <mapnik/expression_string.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/parse_path.hpp> namespace { boost::shared_ptr<mapnik::expr_node> parse_expression_(std::string const& wkt){ return mapnik::parse_expression(wkt,"utf8"); } std::string expr_node_to_string_(boost::shared_ptr<mapnik::expr_node> node_ptr){ return mapnik::to_expression_string(*node_ptr); } // path expression mapnik::path_expression_ptr parse_path_(std::string const& path){ return mapnik::parse_path(path); } } void register_expression(Rice::Module rb_mapnik){ /* @@Module_var rb_mapnik = Mapnik */ Rice::Data_Type< boost::shared_ptr<mapnik::expr_node> > rb_cexpression = Rice::define_class_under< boost::shared_ptr<mapnik::expr_node> >(rb_mapnik, "Expression"); /* * Document-method: parse * call-seq: * parse(expression_string) * * @param [String] * * @return [Mapnk::Expression] a new expression */ rb_cexpression.define_singleton_method("parse", &parse_expression_); /* * Document-method: to_s * @return [String] a string representation of the expression */ rb_cexpression.define_method("to_s",&expr_node_to_string_); Rice::Data_Type< mapnik::path_expression_ptr > rb_cpath_expression = Rice::define_class_under< mapnik::path_expression_ptr >(rb_mapnik, "PathExpression"); // rb_cpath_expression.define_singleton_method("evaluate", &path_evaluate_); // rb_cpath_expression.define_method("to_s",&path_to_string_); /* * Document-method: parse * call-seq: * parse(path_expression_string) * * @param [String] * * @return [Mapnk::PathExpression] a new expression */ rb_cpath_expression.define_singleton_method("parse", &parse_path_); }
update header name
update header name
C++
mit
gravitystorm/Ruby-Mapnik,mapnik/Ruby-Mapnik,mapnik/Ruby-Mapnik,gravitystorm/Ruby-Mapnik,gravitystorm/Ruby-Mapnik,gravitystorm/Ruby-Mapnik,mapnik/Ruby-Mapnik,mapnik/Ruby-Mapnik,mapnik/Ruby-Mapnik,mapnik/Ruby-Mapnik,gravitystorm/Ruby-Mapnik,gravitystorm/Ruby-Mapnik
ff696cc1fca94be3ace7de2eb3b9e52734149161
lib/VMCore/AutoUpgrade.cpp
lib/VMCore/AutoUpgrade.cpp
//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the auto-upgrade helper functions // //===----------------------------------------------------------------------===// #include "llvm/Assembly/AutoUpgrade.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/SymbolTable.h" #include <iostream> using namespace llvm; // Utility function for getting the correct suffix given a type static inline const char* get_suffix(const Type* Ty) { if (Ty == Type::UIntTy) return ".i32"; if (Ty == Type::UShortTy) return ".i16"; if (Ty == Type::UByteTy) return ".i8"; if (Ty == Type::ULongTy) return ".i64"; if (Ty == Type::FloatTy) return ".f32"; if (Ty == Type::DoubleTy) return ".f64"; return 0; } static inline const Type* get_type(Function* F) { // If there's no function, we can't get the argument type. if (!F) return 0; // Get the Function's name. const std::string& Name = F->getName(); // Quickly eliminate it, if it's not a candidate. if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.') return 0; switch (Name[5]) { case 'b': if (Name == "llvm.bswap") return F->getReturnType(); break; case 'c': if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz") return F->getReturnType(); break; case 'i': if (Name == "llvm.isunordered") { Function::const_arg_iterator ArgIt = F->arg_begin(); if (ArgIt != F->arg_end()) return ArgIt->getType(); } break; case 's': if (Name == "llvm.sqrt") return F->getReturnType(); break; default: break; } return 0; } bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) { // Quickly eliminate it, if it's not a candidate. if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.') return false; switch (Name[5]) { case 'b': if (Name == "llvm.bswap") return true; break; case 'c': if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz") return true; break; case 'i': if (Name == "llvm.isunordered") return true; break; case 's': if (Name == "llvm.sqrt") return true; break; default: break; } return false; } // UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to // their non-overloaded variants by appending the appropriate suffix based on // the argument types. Function* llvm::UpgradeIntrinsicFunction(Function* F) { // See if its one of the name's we're interested in. if (const Type* Ty = get_type(F)) { const char* suffix = get_suffix(Ty); if (Ty->isSigned()) suffix = get_suffix(Ty->getUnsignedVersion()); assert(suffix && "Intrinsic parameter type not recognized"); const std::string& Name = F->getName(); std::string new_name = Name + suffix; std::cerr << "WARNING: change " << Name << " to " << new_name << "\n"; SymbolTable& SymTab = F->getParent()->getSymbolTable(); if (Value* V = SymTab.lookup(F->getType(),new_name)) if (Function* OtherF = dyn_cast<Function>(V)) return OtherF; // There wasn't an existing function for the intrinsic, so now make sure the // signedness of the arguments is correct. if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); std::vector<const Type*> Params; Params.push_back(newTy); FunctionType* FT = FunctionType::get(newTy, Params,false); return new Function(FT, GlobalValue::ExternalLinkage, new_name, F->getParent()); } // The argument was the correct type (unsigned or floating), so just // rename the function to its correct name and return it. F->setName(new_name); return F; } return 0; } CallInst* llvm::UpgradeIntrinsicCall(CallInst *CI) { Function *F = CI->getCalledFunction(); if (const Type* Ty = get_type(F)) { Function* newF = UpgradeIntrinsicFunction(F); std::vector<Value*> Oprnds; for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end(); OI != OE; ++OI) Oprnds.push_back(CI); CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI); if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy, "autoupgrade_cast", newCI)); } return newCI; } return 0; } bool llvm::UpgradeCallsToIntrinsic(Function* F) { if (Function* newF = UpgradeIntrinsicFunction(F)) { for (Value::use_iterator UI = F->use_begin(), UE = F->use_end(); UI != UE; ++UI) { if (CallInst* CI = dyn_cast<CallInst>(*UI)) { std::vector<Value*> Oprnds; User::op_iterator OI = CI->op_begin(); ++OI; for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI) Oprnds.push_back(*OI); CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI); const Type* Ty = Oprnds[0]->getType(); if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy, "autoupgrade_cast", newCI)); CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI); newCI->moveBefore(final); CI->replaceAllUsesWith(final); } else { CI->replaceAllUsesWith(newCI); } CI->eraseFromParent(); } } if (newF != F) F->eraseFromParent(); return true; } return false; }
//===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===// // // The LLVM Compiler Infrastructure // // This file was developed by Reid Spencer and is distributed under the // University of Illinois Open Source License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements the auto-upgrade helper functions // //===----------------------------------------------------------------------===// #include "llvm/Assembly/AutoUpgrade.h" #include "llvm/DerivedTypes.h" #include "llvm/Function.h" #include "llvm/Module.h" #include "llvm/Instructions.h" #include "llvm/Intrinsics.h" #include "llvm/SymbolTable.h" #include <iostream> using namespace llvm; // Utility function for getting the correct suffix given a type static inline const char* get_suffix(const Type* Ty) { switch (Ty->getTypeID()) { case Type::UIntTyID: return ".i32"; case Type::UShortTyID: return ".i16"; case Type::UByteTyID: return ".i8"; case Type::ULongTyID: return ".i64"; case Type::FloatTyID: return ".f32"; case Type::DoubleTyID: return ".f64"; default: break; } return 0; } static inline const Type* get_type(Function* F) { // If there's no function, we can't get the argument type. if (!F) return 0; // Get the Function's name. const std::string& Name = F->getName(); // Quickly eliminate it, if it's not a candidate. if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.') return 0; switch (Name[5]) { case 'b': if (Name == "llvm.bswap") return F->getReturnType(); break; case 'c': if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz") return F->getReturnType(); break; case 'i': if (Name == "llvm.isunordered") { Function::const_arg_iterator ArgIt = F->arg_begin(); if (ArgIt != F->arg_end()) return ArgIt->getType(); } break; case 's': if (Name == "llvm.sqrt") return F->getReturnType(); break; default: break; } return 0; } bool llvm::IsUpgradeableIntrinsicName(const std::string& Name) { // Quickly eliminate it, if it's not a candidate. if (Name.length() <= 5 || Name[0] != 'l' || Name[1] != 'l' || Name[2] != 'v' || Name[3] != 'm' || Name[4] != '.') return false; switch (Name[5]) { case 'b': if (Name == "llvm.bswap") return true; break; case 'c': if (Name == "llvm.ctpop" || Name == "llvm.ctlz" || Name == "llvm.cttz") return true; break; case 'i': if (Name == "llvm.isunordered") return true; break; case 's': if (Name == "llvm.sqrt") return true; break; default: break; } return false; } // UpgradeIntrinsicFunction - Convert overloaded intrinsic function names to // their non-overloaded variants by appending the appropriate suffix based on // the argument types. Function* llvm::UpgradeIntrinsicFunction(Function* F) { // See if its one of the name's we're interested in. if (const Type* Ty = get_type(F)) { const char* suffix = get_suffix(Ty); if (Ty->isSigned()) suffix = get_suffix(Ty->getUnsignedVersion()); assert(suffix && "Intrinsic parameter type not recognized"); const std::string& Name = F->getName(); std::string new_name = Name + suffix; std::cerr << "WARNING: change " << Name << " to " << new_name << "\n"; SymbolTable& SymTab = F->getParent()->getSymbolTable(); if (Value* V = SymTab.lookup(F->getType(),new_name)) if (Function* OtherF = dyn_cast<Function>(V)) return OtherF; // There wasn't an existing function for the intrinsic, so now make sure the // signedness of the arguments is correct. if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); std::vector<const Type*> Params; Params.push_back(newTy); FunctionType* FT = FunctionType::get(newTy, Params,false); return new Function(FT, GlobalValue::ExternalLinkage, new_name, F->getParent()); } // The argument was the correct type (unsigned or floating), so just // rename the function to its correct name and return it. F->setName(new_name); return F; } return 0; } CallInst* llvm::UpgradeIntrinsicCall(CallInst *CI) { Function *F = CI->getCalledFunction(); if (const Type* Ty = get_type(F)) { Function* newF = UpgradeIntrinsicFunction(F); std::vector<Value*> Oprnds; for (User::op_iterator OI = CI->op_begin(), OE = CI->op_end(); OI != OE; ++OI) Oprnds.push_back(CI); CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI); if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy, "autoupgrade_cast", newCI)); } return newCI; } return 0; } bool llvm::UpgradeCallsToIntrinsic(Function* F) { if (Function* newF = UpgradeIntrinsicFunction(F)) { for (Value::use_iterator UI = F->use_begin(), UE = F->use_end(); UI != UE; ++UI) { if (CallInst* CI = dyn_cast<CallInst>(*UI)) { std::vector<Value*> Oprnds; User::op_iterator OI = CI->op_begin(); ++OI; for (User::op_iterator OE = CI->op_end(); OI != OE; ++OI) Oprnds.push_back(*OI); CallInst* newCI = new CallInst(newF,Oprnds,"autoupgrade_call",CI); const Type* Ty = Oprnds[0]->getType(); if (Ty->isSigned()) { const Type* newTy = Ty->getUnsignedVersion(); newCI->setOperand(1,new CastInst(newCI->getOperand(1), newTy, "autoupgrade_cast", newCI)); CastInst* final = new CastInst(newCI, Ty, "autoupgrade_uncast",newCI); newCI->moveBefore(final); CI->replaceAllUsesWith(final); } else { CI->replaceAllUsesWith(newCI); } CI->eraseFromParent(); } } if (newF != F) F->eraseFromParent(); return true; } return false; }
Make get_suffix faster by using a switch on getTypeID rather than a series of comparisons on the various type objects.
Make get_suffix faster by using a switch on getTypeID rather than a series of comparisons on the various type objects. git-svn-id: 0ff597fd157e6f4fc38580e8d64ab130330d2411@25441 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
apple/swift-llvm,apple/swift-llvm,dslab-epfl/asap,llvm-mirror/llvm,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,llvm-mirror/llvm,chubbymaggie/asap,llvm-mirror/llvm,dslab-epfl/asap,dslab-epfl/asap,GPUOpen-Drivers/llvm,apple/swift-llvm,llvm-mirror/llvm,dslab-epfl/asap,apple/swift-llvm,llvm-mirror/llvm,llvm-mirror/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,dslab-epfl/asap,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,GPUOpen-Drivers/llvm,apple/swift-llvm,GPUOpen-Drivers/llvm,dslab-epfl/asap,chubbymaggie/asap,GPUOpen-Drivers/llvm,llvm-mirror/llvm,chubbymaggie/asap,chubbymaggie/asap,apple/swift-llvm,apple/swift-llvm
d5b82cd1c62e29d2c6314a1704c01d8593a552da
src/game/console_pane.cc
src/game/console_pane.cc
/* console_pane.cc -- Copyright (c) 2013 Noel Cower. All rights reserved. See COPYING under the project root for the source code license. If this file is not present, refer to <https://raw.github.com/nilium/snow/master/COPYING>. */ #include "console_pane.hh" #include "../renderer/material.hh" #include "../renderer/draw_2d.hh" #include "../renderer/font.hh" #include "../console.hh" #include "../event_queue.hh" #include "resources.hh" #define VERTEX_OFFSET (0) #define INDEX_OFFSET (0) #define CONSOLE_HEIGHT (300) #define CONSOLE_SPEED (30) namespace snow { bool console_pane_t::event(const event_t &event) { bool propagate = true; switch (event.kind) { case KEY_EVENT: switch (event.key.button) { case GLFW_KEY_BACKSPACE: if (event.key.action == GLFW_RELEASE) { break; } if (!buffer_.empty()) { auto end = buffer_.cend(); auto iter = buffer_.cbegin(); auto codes = utf8::distance(iter, end); if (codes > 1) { utf8::advance(iter, end, codes - 1); buffer_.erase(iter, end); } else { buffer_.clear(); } } propagate = false; break; case GLFW_KEY_WORLD_1: if (event.key.action == GLFW_PRESS && event.key.mods == GLFW_MOD_SHIFT) { open_ = !open_; #if HIDE_CURSOR_ON_CONSOLE_CLOSE if (wnd_mouseMode) { wnd_mouseMode->seti(open_); } #endif propagate = false; } break; case GLFW_KEY_ENTER: case GLFW_KEY_KP_ENTER: if (!open_) { break; } propagate = false; if (!event.key.action) { break; } else if (cvars_) { cvars_->execute(buffer_); } buffer_.clear(); break; default: propagate = !open_; break; } break; case CHAR_EVENT: if (!open_) { break; } if (event.character >= ' ' && event.character < '~') { // FIXME: handle non-ASCII characters utf8::put_code(std::back_inserter(buffer_), event.character); propagate = false; } break; default: break; } return propagate; } void console_pane_t::frame(double step, double timeslice) { if (open_ && top_ != CONSOLE_HEIGHT) { if (top_ < CONSOLE_HEIGHT) { top_ += CONSOLE_SPEED; } if (top_ > CONSOLE_HEIGHT) { top_ = CONSOLE_HEIGHT; } } else if (!open_ && top_) { top_ -= CONSOLE_SPEED; if (top_ == 1) { top_ = 0; } } } void console_pane_t::draw(double timeslice) { resources_t &res = resources_t::default_resources(); if (!bg_mat_) { bg_mat_ = res.load_material("console/background"); } if (!font_) { font_ = res.load_font("console"); if (font_) { font_scale_ = 20.0f / font_->line_height(); } } drawer_.clear(); const float alpha = float(top_) / float(CONSOLE_HEIGHT); const vec4f_t tint = { 1.0, 1.0, 1.0, alpha }; const vec2f_t screen_size = drawer_.offset_to_screen({ 1, 1 }); vec2f_t size = screen_size; vec2f_t pos = { 0, size.y - top_ }; if (bg_mat_ != nullptr && top_) { size.y = CONSOLE_HEIGHT; drawer_.draw_rect_raw(pos, size, tint, bg_mat_); } if (font_ != nullptr && top_ != 0) { const float line_height = std::ceil(font_->line_height() * font_scale_); vec2f_t buffer_pos = { 4, pos.y + std::ceil(font_->descent() * font_scale_) + 4}; font_->draw_text(drawer_, buffer_pos, buffer_, tint, true, font_scale_); buffer_pos.y += line_height + 10; for (const string &log_message : log_) { font_->draw_text(drawer_, buffer_pos, log_message, tint, true, font_scale_); buffer_pos.y += line_height; if (buffer_pos.y > screen_size.y) { break; } } } drawer_.buffer_vertices(vbuffer_, VERTEX_OFFSET); drawer_.buffer_indices(ibuffer_, INDEX_OFFSET); if (!vao_.generated()) { vao_ = drawer_.build_vertex_array(ATTRIB_POSITION, ATTRIB_TEXCOORD0, ATTRIB_COLOR, vbuffer_, VERTEX_OFFSET, ibuffer_); } drawer_.draw_with_vertex_array(vao_, INDEX_OFFSET); } void console_pane_t::set_cvar_set(cvar_set_t *cvars) { cvars_ = cvars; #if HIDE_CURSOR_ON_CONSOLE_CLOSE if (cvars_) { wnd_mouseMode = cvars_->get_cvar("wnd_mouseMode", true, CVAR_DELAYED | CVAR_INVISIBLE); } else { wnd_mouseMode = nullptr; } #endif } cvar_set_t *console_pane_t::cvar_set() const { return cvars_; } void console_pane_t::write_log(const string &message) { if (log_.size() == log_max_) { log_.pop_back(); } log_.push_front(message); } namespace { console_pane_t g_default_console_pane; } // namespace <anon> console_pane_t &default_console() { return g_default_console_pane; } } // namespace snow
/* console_pane.cc -- Copyright (c) 2013 Noel Cower. All rights reserved. See COPYING under the project root for the source code license. If this file is not present, refer to <https://raw.github.com/nilium/snow/master/COPYING>. */ #include "console_pane.hh" #include "../renderer/material.hh" #include "../renderer/draw_2d.hh" #include "../renderer/font.hh" #include "../console.hh" #include "../event_queue.hh" #include "resources.hh" #define VERTEX_OFFSET (0) #define INDEX_OFFSET (0) #define CONSOLE_HEIGHT (300) #define CONSOLE_SPEED (30) namespace snow { bool console_pane_t::event(const event_t &event) { bool propagate = true; switch (event.kind) { case KEY_EVENT: switch (event.key.button) { case GLFW_KEY_BACKSPACE: if (event.key.action == GLFW_RELEASE) { break; } if (!buffer_.empty()) { auto end = buffer_.cend(); auto iter = utf8::before(end); if (iter == buffer_.cbegin()) { buffer_.clear(); } else { buffer_.erase(iter, end); } } propagate = false; break; case GLFW_KEY_WORLD_1: if (event.key.action == GLFW_PRESS && event.key.mods == GLFW_MOD_SHIFT) { open_ = !open_; #if HIDE_CURSOR_ON_CONSOLE_CLOSE if (wnd_mouseMode) { wnd_mouseMode->seti(open_); } #endif propagate = false; } break; case GLFW_KEY_ENTER: case GLFW_KEY_KP_ENTER: if (!open_) { break; } propagate = false; if (!event.key.action) { break; } else if (cvars_) { cvars_->execute(buffer_); } buffer_.clear(); break; default: propagate = !open_; break; } break; case CHAR_EVENT: if (!open_) { break; } if (event.character >= ' ' && event.character < '~') { // FIXME: handle non-ASCII characters utf8::put_code(std::back_inserter(buffer_), event.character); propagate = false; } break; default: break; } return propagate; } void console_pane_t::frame(double step, double timeslice) { if (open_ && top_ != CONSOLE_HEIGHT) { if (top_ < CONSOLE_HEIGHT) { top_ += CONSOLE_SPEED; } if (top_ > CONSOLE_HEIGHT) { top_ = CONSOLE_HEIGHT; } } else if (!open_ && top_) { top_ -= CONSOLE_SPEED; if (top_ == 1) { top_ = 0; } } } void console_pane_t::draw(double timeslice) { resources_t &res = resources_t::default_resources(); if (!bg_mat_) { bg_mat_ = res.load_material("console/background"); } if (!font_) { font_ = res.load_font("console"); if (font_) { font_scale_ = 20.0f / font_->line_height(); } } drawer_.clear(); const float alpha = float(top_) / float(CONSOLE_HEIGHT); const vec4f_t tint = { 1.0, 1.0, 1.0, alpha }; const vec2f_t screen_size = drawer_.offset_to_screen({ 1, 1 }); vec2f_t size = screen_size; vec2f_t pos = { 0, size.y - top_ }; if (bg_mat_ != nullptr && top_) { size.y = CONSOLE_HEIGHT; drawer_.draw_rect_raw(pos, size, tint, bg_mat_); } if (font_ != nullptr && top_ != 0) { const float line_height = std::ceil(font_->line_height() * font_scale_); vec2f_t buffer_pos = { 4, pos.y + std::ceil(font_->descent() * font_scale_) + 4}; font_->draw_text(drawer_, buffer_pos, buffer_, tint, true, font_scale_); buffer_pos.y += line_height + 10; for (const string &log_message : log_) { font_->draw_text(drawer_, buffer_pos, log_message, tint, true, font_scale_); buffer_pos.y += line_height; if (buffer_pos.y > screen_size.y) { break; } } } drawer_.buffer_vertices(vbuffer_, VERTEX_OFFSET); drawer_.buffer_indices(ibuffer_, INDEX_OFFSET); if (!vao_.generated()) { vao_ = drawer_.build_vertex_array(ATTRIB_POSITION, ATTRIB_TEXCOORD0, ATTRIB_COLOR, vbuffer_, VERTEX_OFFSET, ibuffer_); } drawer_.draw_with_vertex_array(vao_, INDEX_OFFSET); } void console_pane_t::set_cvar_set(cvar_set_t *cvars) { cvars_ = cvars; #if HIDE_CURSOR_ON_CONSOLE_CLOSE if (cvars_) { wnd_mouseMode = cvars_->get_cvar("wnd_mouseMode", true, CVAR_DELAYED | CVAR_INVISIBLE); } else { wnd_mouseMode = nullptr; } #endif } cvar_set_t *console_pane_t::cvar_set() const { return cvars_; } void console_pane_t::write_log(const string &message) { if (log_.size() == log_max_) { log_.pop_back(); } log_.push_front(message); } namespace { console_pane_t g_default_console_pane; } // namespace <anon> console_pane_t &default_console() { return g_default_console_pane; } } // namespace snow
Use utf8::before for deleting a range.
console_pane: Use utf8::before for deleting a range. Much simpler than using advance to get an iterator to the N-1th code, and avoids a distance call which is effectively just the same loop twice. Might be a good idea to get the end using find_invalid (again).
C++
bsd-2-clause
nilium/snow,nilium/snow,nilium/snow
57ddc5678353b20a994c15145478672fdacf8b58
include/distortos/estd/ContiguousRange.hpp
include/distortos/estd/ContiguousRange.hpp
/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-10 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) noexcept { return begin_[i]; } /** * \param [in] i is the index of element that will be accessed * * \return const reference to element at given index */ const_reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_
/** * \file * \brief ContiguousRange template class header. * * \author Copyright (C) 2014-2015 Kamil Szczygiel http://www.distortec.com http://www.freddiechopin.info * * \par License * This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not * distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. * * \date 2015-04-10 */ #ifndef ESTD_CONTIGUOUSRANGE_HPP_ #define ESTD_CONTIGUOUSRANGE_HPP_ #include <iterator> namespace estd { /** * \brief ContiguousRange template class is a pair of iterators to contiguous sequence of elements in memory * * \param T is the type of data in the range */ template<typename T> class ContiguousRange { public: /// value_type type using value_type = T; /// pointer type using pointer = value_type*; /// const_pointer type using const_pointer = const value_type*; /// reference type using reference = value_type&; /// const_reference type using const_reference = const value_type&; /// iterator type using iterator = value_type*; /// const_iterator type using const_iterator = const value_type*; /// size_type type using size_type = std::size_t; /// difference_type type using difference_type = std::ptrdiff_t; /// reverse_iterator type using reverse_iterator = std::reverse_iterator<iterator>; /// const_reverse_iterator type using const_reverse_iterator = std::reverse_iterator<const_iterator>; /** * \brief ContiguousRange's constructor. * * \param [in] beginn is an iterator to first element in the range * \param [in] endd is an iterator to "one past the last" element in the range */ constexpr ContiguousRange(const iterator beginn, const iterator endd) noexcept : begin_{beginn}, end_{endd} { } /** * \brief Empty ContiguousRange's constructor. */ constexpr explicit ContiguousRange() noexcept : ContiguousRange{nullptr, nullptr} { } /** * \brief ContiguousRange's constructor using C-style array. * * \param N is the number of elements in the array * * \param [in] array is the array used to initialize the range */ template<size_t N> constexpr explicit ContiguousRange(T (&array)[N]) noexcept : ContiguousRange{array, array + N} { } /** * \brief ContiguousRange's constructor using single value * * \param [in] value is a reference to variable used to initialize the range */ constexpr explicit ContiguousRange(T& value) noexcept : ContiguousRange{&value, &value + 1} { } /** * \return iterator to first element in the range */ constexpr iterator begin() const noexcept { return begin_; } /** * \return iterator to "one past the last" element in the range */ constexpr iterator end() const noexcept { return end_; } /** * \return number of elements in the range */ constexpr size_type size() const noexcept { return end_ - begin_; } /** * \param [in] i is the index of element that will be accessed * * \return reference to element at given index */ reference operator[](const size_type i) const noexcept { return begin_[i]; } private: /// iterator to first element in the range const iterator begin_; /// iterator to "one past the last" element in the range const iterator end_; }; } // namespace estd #endif // ESTD_CONTIGUOUSRANGE_HPP_
remove non-const variant of subscript operator - this class is only a wrapper for real storage, only member variables are two iterators
estd::ContiguousRange: remove non-const variant of subscript operator - this class is only a wrapper for real storage, only member variables are two iterators
C++
mpl-2.0
CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,DISTORTEC/distortos,CezaryGapinski/distortos,jasmin-j/distortos,jasmin-j/distortos,CezaryGapinski/distortos,DISTORTEC/distortos,jasmin-j/distortos
207168fafcdcf7a63d02895d355be59014c44888
include/mapnik/feature_style_processor.hpp
include/mapnik/feature_style_processor.hpp
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->set_size(m_.width(), m_.height()); metaItr->second->set_map_srs(proj); metaItr->second->start(m_.metawriter_output_properties); } double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom); } } metaItr = m_.begin_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif boost::shared_ptr<datasource> ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); // todo: only display raster if src and dest proj are matched // todo: add raster re-projection as an optional feature if (ds->type() == datasource::Raster && !prj_trans.equal()) return; // box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height()); query q(bbox,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; std::set<std::string> names; attribute_collector collector(names); std::vector<std::string> const& style_names = lay.styles(); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule_type>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(rule); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = style_names.size()>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; std::vector<rule_type> const& rules=style->get_rules(); BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { if (rule.has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&rule)); } else { if_rules.push_back(const_cast<rule_type*>(&rule)); } if (ds->type() == datasource::Raster ) { if (ds->params().get<double>("filter_factor",0.0) == 0.0) { rule_type::symbolizers const& symbols = rule.get_symbolizers(); rule_type::symbolizers::const_iterator symIter = symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter != symEnd;++symIter) { try { raster_symbolizer const& sym = boost::get<raster_symbolizer>(*symIter); std::string const& scaling = sym.get_scaling(); if (scaling == "bilinear" || scaling == "bilinear8" ) { // todo - allow setting custom value in symbolizer property? q.filter_factor(2.0); } } catch (const boost::bad_get &v) { // case where useless symbolizer is attached to raster layer //throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported"); } } } } } } // process features featureset_ptr fs; if (cache_features) { if (first) { first = false; fs = ds->features(q); } else { fs = cache.features(q); } } else { fs = ds->features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule_type * rule, if_rules ) { expression_ptr const& expr=rule->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule_type::symbolizers const& symbols = rule->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } if (do_else) { BOOST_FOREACH( rule_type * rule, else_rules ) { rule_type::symbolizers const& symbols = rule->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } } cache_features = false; } } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP
/***************************************************************************** * * This file is part of Mapnik (c++ mapping toolkit) * * Copyright (C) 2006 Artem Pavlenko * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * *****************************************************************************/ //$Id$ #ifndef FEATURE_STYLE_PROCESSOR_HPP #define FEATURE_STYLE_PROCESSOR_HPP // mapnik #include <mapnik/box2d.hpp> #include <mapnik/datasource.hpp> #include <mapnik/layer.hpp> #include <mapnik/map.hpp> #include <mapnik/attribute_collector.hpp> #include <mapnik/expression_evaluator.hpp> #include <mapnik/utils.hpp> #include <mapnik/projection.hpp> #include <mapnik/scale_denominator.hpp> #include <mapnik/memory_datasource.hpp> #ifdef MAPNIK_DEBUG //#include <mapnik/wall_clock_timer.hpp> #endif // boost #include <boost/foreach.hpp> //stl #include <vector> namespace mapnik { template <typename Processor> class feature_style_processor { /** Calls the renderer's process function, * \param output Renderer * \param f Feature to process * \param prj_trans Projection * \param sym Symbolizer object */ struct symbol_dispatch : public boost::static_visitor<> { symbol_dispatch (Processor & output, Feature const& f, proj_transform const& prj_trans) : output_(output), f_(f), prj_trans_(prj_trans) {} template <typename T> void operator () (T const& sym) const { output_.process(sym,f_,prj_trans_); } Processor & output_; Feature const& f_; proj_transform const& prj_trans_; }; public: explicit feature_style_processor(Map const& m, double scale_factor = 1.0) : m_(m), scale_factor_(scale_factor) {} void apply() { #ifdef MAPNIK_DEBUG //mapnik::wall_clock_progress_timer t(std::clog, "map rendering took: "); #endif Processor & p = static_cast<Processor&>(*this); p.start_map_processing(m_); try { projection proj(m_.srs()); // map projection Map::const_metawriter_iterator metaItr = m_.begin_metawriters(); Map::const_metawriter_iterator metaItrEnd = m_.end_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->set_size(m_.width(), m_.height()); metaItr->second->set_map_srs(proj); metaItr->second->start(m_.metawriter_output_properties); } double scale_denom = mapnik::scale_denominator(m_,proj.is_geographic()); scale_denom *= scale_factor_; #ifdef MAPNIK_DEBUG std::clog << "scale denominator = " << scale_denom << "\n"; #endif BOOST_FOREACH ( layer const& lyr, m_.layers() ) { if (lyr.isVisible(scale_denom)) { apply_to_layer(lyr, p, proj, scale_denom); } } metaItr = m_.begin_metawriters(); for (;metaItr!=metaItrEnd; ++metaItr) { metaItr->second->stop(); } } catch (proj_init_error& ex) { std::clog << "proj_init_error:" << ex.what() << "\n"; } p.end_map_processing(m_); } private: void apply_to_layer(layer const& lay, Processor & p, projection const& proj0, double scale_denom) { #ifdef MAPNIK_DEBUG //wall_clock_progress_timer timer(clog, "end layer rendering: "); #endif boost::shared_ptr<datasource> ds = lay.datasource(); if (!ds) { std::clog << "WARNING: No datasource for layer '" << lay.name() << "'\n"; return; } p.start_layer_processing(lay); if (ds) { box2d<double> ext = m_.get_buffered_extent(); projection proj1(lay.srs()); proj_transform prj_trans(proj0,proj1); // todo: only display raster if src and dest proj are matched // todo: add raster re-projection as an optional feature if (ds->type() == datasource::Raster && !prj_trans.equal()) return; // box2d<double> layer_ext = lay.envelope(); double lx0 = layer_ext.minx(); double ly0 = layer_ext.miny(); double lz0 = 0.0; double lx1 = layer_ext.maxx(); double ly1 = layer_ext.maxy(); double lz1 = 0.0; // back project layers extent into main map projection prj_trans.backward(lx0,ly0,lz0); prj_trans.backward(lx1,ly1,lz1); // if no intersection then nothing to do for layer if ( lx0 > ext.maxx() || lx1 < ext.minx() || ly0 > ext.maxy() || ly1 < ext.miny() ) { return; } // clip query bbox lx0 = std::max(ext.minx(),lx0); ly0 = std::max(ext.miny(),ly0); lx1 = std::min(ext.maxx(),lx1); ly1 = std::min(ext.maxy(),ly1); prj_trans.forward(lx0,ly0,lz0); prj_trans.forward(lx1,ly1,lz1); box2d<double> bbox(lx0,ly0,lx1,ly1); query::resolution_type res(m_.width()/m_.get_current_extent().width(),m_.height()/m_.get_current_extent().height()); query q(bbox,res,scale_denom); //BBOX query std::vector<feature_type_style*> active_styles; std::set<std::string> names; attribute_collector collector(names); std::vector<std::string> const& style_names = lay.styles(); // iterate through all named styles collecting active styles and attribute names BOOST_FOREACH(std::string const& style_name, style_names) { boost::optional<feature_type_style const&> style=m_.find_style(style_name); if (!style) { std::clog << "WARNING: style '" << style_name << "' required for layer '" << lay.name() << "' does not exist.\n"; continue; } const std::vector<rule_type>& rules=(*style).get_rules(); bool active_rules=false; BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { active_rules = true; if (ds->type() == datasource::Vector) { collector(rule); } // TODO - in the future rasters should be able to be filtered. } } if (active_rules) { active_styles.push_back(const_cast<feature_type_style*>(&(*style))); } } // push all property names BOOST_FOREACH(std::string const& name, names) { q.add_property_name(name); } memory_datasource cache; bool cache_features = style_names.size()>1?true:false; bool first = true; BOOST_FOREACH (feature_type_style * style, active_styles) { std::vector<rule_type*> if_rules; std::vector<rule_type*> else_rules; std::vector<rule_type> const& rules=style->get_rules(); BOOST_FOREACH(rule_type const& rule, rules) { if (rule.active(scale_denom)) { if (rule.has_else_filter()) { else_rules.push_back(const_cast<rule_type*>(&rule)); } else { if_rules.push_back(const_cast<rule_type*>(&rule)); } if (ds->type() == datasource::Raster ) { if (ds->params().get<double>("filter_factor",0.0) == 0.0) { rule_type::symbolizers const& symbols = rule.get_symbolizers(); rule_type::symbolizers::const_iterator symIter = symbols.begin(); rule_type::symbolizers::const_iterator symEnd = symbols.end(); for (;symIter != symEnd;++symIter) { try { raster_symbolizer const& sym = boost::get<raster_symbolizer>(*symIter); std::string const& scaling = sym.get_scaling(); if (scaling == "bilinear" || scaling == "bilinear8" ) { // todo - allow setting custom value in symbolizer property? q.filter_factor(2.0); } } catch (const boost::bad_get &v) { // case where useless symbolizer is attached to raster layer //throw config_error("Invalid Symbolizer type supplied, only RasterSymbolizer is supported"); } } } } } } // process features featureset_ptr fs; if (first) { first = false; fs = ds->features(q); } else { fs = cache.features(q); } if (fs) { feature_ptr feature; while ((feature = fs->next())) { bool do_else=true; if (cache_features) { cache.push(feature); } BOOST_FOREACH(rule_type * rule, if_rules ) { expression_ptr const& expr=rule->get_filter(); value_type result = boost::apply_visitor(evaluate<Feature,value_type>(*feature),*expr); if (result.to_bool()) { do_else=false; rule_type::symbolizers const& symbols = rule->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } if (do_else) { BOOST_FOREACH( rule_type * rule, else_rules ) { rule_type::symbolizers const& symbols = rule->get_symbolizers(); // if the underlying renderer is not able to process the complete set of symbolizers, // process one by one. #ifdef SVG_RENDERER if(!p.process(symbols,*feature,prj_trans)) #endif { BOOST_FOREACH (symbolizer const& sym, symbols) { boost::apply_visitor(symbol_dispatch(p,*feature,prj_trans),sym); } } } } } } cache_features = false; } } p.end_layer_processing(lay); } Map const& m_; double scale_factor_; }; } #endif //FEATURE_STYLE_PROCESSOR_HPP
fix broken feature caching - #624
fix broken feature caching - #624
C++
lgpl-2.1
jwomeara/mapnik,sebastic/python-mapnik,jwomeara/mapnik,mbrukman/mapnik,whuaegeanse/mapnik,tomhughes/python-mapnik,yiqingj/work,yohanboniface/python-mapnik,naturalatlas/mapnik,Mappy/mapnik,kapouer/mapnik,mapycz/mapnik,davenquinn/python-mapnik,Mappy/mapnik,cjmayo/mapnik,whuaegeanse/mapnik,mapnik/mapnik,mapycz/mapnik,kapouer/mapnik,pnorman/mapnik,whuaegeanse/mapnik,CartoDB/mapnik,mbrukman/mapnik,mapycz/python-mapnik,lightmare/mapnik,Uli1/mapnik,garnertb/python-mapnik,Mappy/mapnik,jwomeara/mapnik,tomhughes/python-mapnik,Airphrame/mapnik,mapycz/mapnik,rouault/mapnik,mapnik/python-mapnik,lightmare/mapnik,pramsey/mapnik,cjmayo/mapnik,jwomeara/mapnik,qianwenming/mapnik,naturalatlas/mapnik,mbrukman/mapnik,sebastic/python-mapnik,mapnik/mapnik,manz/python-mapnik,strk/mapnik,yohanboniface/python-mapnik,mapnik/mapnik,zerebubuth/mapnik,tomhughes/mapnik,zerebubuth/mapnik,stefanklug/mapnik,naturalatlas/mapnik,lightmare/mapnik,mapnik/mapnik,mapnik/python-mapnik,mapnik/python-mapnik,manz/python-mapnik,Uli1/mapnik,kapouer/mapnik,qianwenming/mapnik,yiqingj/work,yohanboniface/python-mapnik,tomhughes/mapnik,CartoDB/mapnik,mbrukman/mapnik,strk/mapnik,pramsey/mapnik,pnorman/mapnik,davenquinn/python-mapnik,strk/mapnik,strk/mapnik,garnertb/python-mapnik,cjmayo/mapnik,qianwenming/mapnik,pnorman/mapnik,tomhughes/mapnik,zerebubuth/mapnik,yiqingj/work,rouault/mapnik,Airphrame/mapnik,garnertb/python-mapnik,kapouer/mapnik,pnorman/mapnik,tomhughes/mapnik,stefanklug/mapnik,mapycz/python-mapnik,Airphrame/mapnik,manz/python-mapnik,cjmayo/mapnik,qianwenming/mapnik,pramsey/mapnik,stefanklug/mapnik,tomhughes/python-mapnik,pramsey/mapnik,sebastic/python-mapnik,rouault/mapnik,Mappy/mapnik,whuaegeanse/mapnik,qianwenming/mapnik,lightmare/mapnik,Airphrame/mapnik,CartoDB/mapnik,Uli1/mapnik,stefanklug/mapnik,davenquinn/python-mapnik,Uli1/mapnik,rouault/mapnik,yiqingj/work,naturalatlas/mapnik
d0e881ba39a43aead3010a49601e3f44dd164779
network_epoll.cpp
network_epoll.cpp
#include "network_epoll.hpp" #include "unistd.h" #include <sys/epoll.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/eventfd.h> #include <sys/signal.h> #include <linux/sockios.h> #include <netinet/in.h> #include <string.h> #include <assert.h> #include <iostream> #include <fstream> #include <sstream> #ifdef USE_EDGE_TRIGGERED_EPOLL #define PRE_MODE EPOLLET #define READ while #define BREAK_IF_ET break #else #define PRE_MODE 0 #define READ if #define BREAK_IF_ET #endif #ifdef USE_ONESHOT_EPOLL #define MODE PRE_MODE | EPOLLONESHOT #define MAX_EVENTS 1 #else #define MODE PRE_MODE #define MAX_EVENTS 16 #endif #define INITIAL_STATE 0 #define CLOSED_STATE 1 // invalid because comb = 0 => col = 0 static void errno_exit(const char *s) { std::ostringstream os; os << s << " error " << errno << ", " << strerror(errno); throw std::runtime_error(os.str()); } NetworkHandler::NetworkHandler(Canvas& canvas, uint16_t port, unsigned threadCount) : canvas(canvas) , sizeStr([&canvas] () { std::ostringstream os; os << "SIZE " << canvas.width << ' ' << canvas.height << '\n'; return os.str(); } ()) { signal(SIGPIPE, SIG_IGN); { std::ifstream fd_max_stream("/proc/sys/fs/file-max"); if (!(fd_max_stream >> fd_max)) { throw std::runtime_error("Can not read /proc/sys/fs/file-max"); } } state = new uint64_t[fd_max + 1]; std::fill_n(state, fd_max + 1, CLOSED_STATE); epollfd = epoll_create1(0); if (epollfd == -1) errno_exit("epoll_create1"); evfd = eventfd(0, SOCK_NONBLOCK); struct epoll_event evee = { .events = EPOLLIN, .data = { .fd = evfd } }; epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &evee); struct sockaddr_in6 destAddr = {}; destAddr.sin6_family = AF_INET6; destAddr.sin6_port = htons(port); serverfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP); int one = 1; setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (serverfd == -1) errno_exit("socket"); int err; err = bind(serverfd, (sockaddr*)&destAddr, sizeof(destAddr)); if (err < 0) errno_exit("bind"); err = listen(serverfd, 1); if (err < 0) errno_exit("listen"); struct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } }; err = epoll_ctl(epollfd, EPOLL_CTL_ADD, serverfd, &serveree); if (err < 0) errno_exit("epoll_ctl add server"); #ifdef USE_ONESHOT_EPOLL for (unsigned i = 0; i < threadCount; i++) { #endif threads.emplace(&NetworkHandler::work, this); #ifdef USE_ONESHOT_EPOLL } #endif } NetworkHandler::~NetworkHandler() { uint64_t one = 1; write(evfd, &one, sizeof one); while (!threads.empty()) { threads.top().join(); threads.pop(); } uint64_t devnull; read(evfd, &devnull, sizeof devnull); close(epollfd); close(evfd); close(serverfd); for (int i = 0; i < fd_max; i++) { if (state[i] != CLOSED_STATE) { close(i); } } delete[] state; } void NetworkHandler::work() { const unsigned xmax = canvas.width, ymax = canvas.height; const char* sizeData = sizeStr.data(); int sizeLen = sizeStr.length(); for (;;) { struct epoll_event event[MAX_EVENTS]; int eventCnt = epoll_wait(epollfd, event, MAX_EVENTS, -1); for (int i = 0; i < eventCnt; i++) { int fd = event[i].data.fd; if (fd == evfd) { return; } else if (fd == serverfd) { int clientfd; READ ((clientfd = accept4(serverfd, nullptr, nullptr, SOCK_NONBLOCK)) >= 0) { state[clientfd] = INITIAL_STATE; struct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = clientfd } }; int err; err = epoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ee); if (err < 0) errno_exit("epoll_ctl add client"); #ifdef USE_ONESHOT_EPOLL struct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } }; err = epoll_ctl(epollfd, EPOLL_CTL_MOD, serverfd, &serveree); if (err < 0) errno_exit("epoll_ctl rearm server"); #endif } } else { char buf[32768]; int size; READ ((size = read(fd, &buf, sizeof buf - 1)) > 0) { buf[size] = '\0'; char* c = buf; uint64_t ss = state[fd]; unsigned col = (ss >> 0) & 0xFFFFFFFF; unsigned x = (ss >> 32) & 0x1FFF; unsigned y = (ss >> 45) & 0x1FFF; unsigned comb = (ss >> 58) & 0x3F; unsigned s = comb / 9; unsigned dc = comb % 9; if (!s) { s = dc; dc = 0; } else { s += 2; } switch (s) { case0: case 0: if (*c == 'P') c++; else if (*c == 'S') { dc = 0; s = 7; c++; goto case7; } else { s = 0; break; } case 1: if (*c == 'X') c++; else { s = 1; break; } case 2: if (*c == ' ') c++; else { s = 2; break; } case 3: while (*c >= '0' && *c <= '9' && dc < 4) { x = 10 * x + (*c - '0'); if (x >= xmax) break; dc++; c++; } if (dc && *c == ' ') { dc = 0; c++; } else { s = 3; break; } case 4: while (*c >= '0' && *c <= '9' && dc < 4) { y = 10 * y + (*c - '0'); if (y >= ymax) break; dc++; c++; } if (dc && *c == ' ') { dc = 0; c++; } else { s = 4; break; } case 5: s = 5; while (dc < 8) { if (*c >= '0' && *c <= '9') { col = (col << 4) | (*c - '0'); } else if (*c >= 'a' && *c <= 'f') { col = (col << 4) | (*c - 'a' + 0xA); } else if (*c >= 'A' && *c <= 'F') { col = (col << 4) | (*c - 'A' + 0xA); } else { break; } dc++; c++; } if (*c == '\r') { c++; s = 6; } case 6: if (*c == '\n' && (dc == 6 || dc == 8)) { c++; if (dc == 6) { canvas.set(x, y, col << 8); } else { canvas.blend(x, y, col); } s = x = y = col = dc = 0; goto case0; } else { break; } case7: case 7: switch (dc) { case 0: if (*c == 'I') c++; else { dc = 0; break; } case 1: if (*c == 'Z') c++; else { dc = 1; break; } case 2: if (*c == 'E') c++; else { dc = 2; break; } case 3: if (*c != '\n') { if (*c == '\r') c++; else { dc = 3; break; } } case 4: if (*c == '\n') { int pending; int err = ioctl(fd, SIOCOUTQ, &pending); if (err || pending) { break; } if (write(fd, sizeData, sizeLen) != sizeLen) { break; } s = x = y = col = dc = 0; c++; goto case0; } else { dc = 4; break; } } } if (s <= 2) { dc = s; s = 0; } else { s -= 2; } if (c == buf + size) { comb = s * 9 + dc; assert(!(col & ~0xFFFFFFFF)); assert(!(x & ~0x1FFF)); assert(!(y & ~0x1FFF)); assert(!(comb & ~0x3F)); state[fd] = col | (uint64_t(x) << 32) | (uint64_t(y) << 45) | (uint64_t(comb) << 58); } else { size = 0; BREAK_IF_ET; } } if (size == 0) { state[fd] = CLOSED_STATE; close(fd); #ifdef USE_ONESHOT_EPOLL } else { struct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = fd } }; int err = epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ee); if (err < 0) errno_exit("epoll_ctl rearm client"); #endif } } } } }
#include "network_epoll.hpp" #include "unistd.h" #include <sys/epoll.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/time.h> #include <sys/mman.h> #include <sys/ioctl.h> #include <sys/epoll.h> #include <sys/socket.h> #include <sys/eventfd.h> #include <sys/signal.h> #include <linux/sockios.h> #include <netinet/in.h> #include <string.h> #include <assert.h> #include <iostream> #include <sstream> #ifdef USE_EDGE_TRIGGERED_EPOLL #define PRE_MODE EPOLLET #define READ while #define BREAK_IF_ET break #else #define PRE_MODE 0 #define READ if #define BREAK_IF_ET #endif #ifdef USE_ONESHOT_EPOLL #define MODE PRE_MODE | EPOLLONESHOT #define MAX_EVENTS 1 #else #define MODE PRE_MODE #define MAX_EVENTS 16 #endif #define INITIAL_STATE 0 #define CLOSED_STATE 1 // invalid because comb = 0 => col = 0 static void errno_exit(const char *s) { std::ostringstream os; os << s << " error " << errno << ", " << strerror(errno); throw std::runtime_error(os.str()); } NetworkHandler::NetworkHandler(Canvas& canvas, uint16_t port, unsigned threadCount) : canvas(canvas) , sizeStr([&canvas] () { std::ostringstream os; os << "SIZE " << canvas.width << ' ' << canvas.height << '\n'; return os.str(); } ()) { signal(SIGPIPE, SIG_IGN); if ((fd_max = sysconf(_SC_OPEN_MAX)) < 1024) { std::cerr << "OPEN_MAX is very low (" << fd_max << "), assuming 1024." << std::endl; fd_max = 1024; } state = new uint64_t[fd_max]; std::fill_n(state, fd_max, CLOSED_STATE); epollfd = epoll_create1(0); if (epollfd == -1) errno_exit("epoll_create1"); evfd = eventfd(0, SOCK_NONBLOCK); struct epoll_event evee = { .events = EPOLLIN, .data = { .fd = evfd } }; epoll_ctl(epollfd, EPOLL_CTL_ADD, evfd, &evee); struct sockaddr_in6 destAddr = {}; destAddr.sin6_family = AF_INET6; destAddr.sin6_port = htons(port); serverfd = socket(AF_INET6, SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP); int one = 1; setsockopt(serverfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); if (serverfd == -1) errno_exit("socket"); int err; err = bind(serverfd, (sockaddr*)&destAddr, sizeof(destAddr)); if (err < 0) errno_exit("bind"); err = listen(serverfd, 1); if (err < 0) errno_exit("listen"); struct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } }; err = epoll_ctl(epollfd, EPOLL_CTL_ADD, serverfd, &serveree); if (err < 0) errno_exit("epoll_ctl add server"); #ifdef USE_ONESHOT_EPOLL for (unsigned i = 0; i < threadCount; i++) { #endif threads.emplace(&NetworkHandler::work, this); #ifdef USE_ONESHOT_EPOLL } #endif } NetworkHandler::~NetworkHandler() { uint64_t one = 1; write(evfd, &one, sizeof one); while (!threads.empty()) { threads.top().join(); threads.pop(); } uint64_t devnull; read(evfd, &devnull, sizeof devnull); close(epollfd); close(evfd); close(serverfd); for (int i = 0; i < fd_max; i++) { if (state[i] != CLOSED_STATE) { close(i); } } delete[] state; } void NetworkHandler::work() { const unsigned xmax = canvas.width, ymax = canvas.height; const char* sizeData = sizeStr.data(); int sizeLen = sizeStr.length(); for (;;) { struct epoll_event event[MAX_EVENTS]; int eventCnt = epoll_wait(epollfd, event, MAX_EVENTS, -1); for (int i = 0; i < eventCnt; i++) { int fd = event[i].data.fd; if (fd == evfd) { return; } else if (fd == serverfd) { int clientfd; READ ((clientfd = accept4(serverfd, nullptr, nullptr, SOCK_NONBLOCK)) >= 0) { if (clientfd >= fd_max) { throw std::runtime_error("invalid fd"); } state[clientfd] = INITIAL_STATE; struct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = clientfd } }; int err; err = epoll_ctl(epollfd, EPOLL_CTL_ADD, clientfd, &ee); if (err < 0) errno_exit("epoll_ctl add client"); #ifdef USE_ONESHOT_EPOLL struct epoll_event serveree = { .events = EPOLLIN | MODE, .data = { .fd = serverfd } }; err = epoll_ctl(epollfd, EPOLL_CTL_MOD, serverfd, &serveree); if (err < 0) errno_exit("epoll_ctl rearm server"); #endif } } else { char buf[32768]; int size; READ ((size = read(fd, &buf, sizeof buf - 1)) > 0) { buf[size] = '\0'; char* c = buf; uint64_t ss = state[fd]; unsigned col = (ss >> 0) & 0xFFFFFFFF; unsigned x = (ss >> 32) & 0x1FFF; unsigned y = (ss >> 45) & 0x1FFF; unsigned comb = (ss >> 58) & 0x3F; unsigned s = comb / 9; unsigned dc = comb % 9; if (!s) { s = dc; dc = 0; } else { s += 2; } switch (s) { case0: case 0: if (*c == 'P') c++; else if (*c == 'S') { dc = 0; s = 7; c++; goto case7; } else { s = 0; break; } case 1: if (*c == 'X') c++; else { s = 1; break; } case 2: if (*c == ' ') c++; else { s = 2; break; } case 3: while (*c >= '0' && *c <= '9' && dc < 4) { x = 10 * x + (*c - '0'); if (x >= xmax) break; dc++; c++; } if (dc && *c == ' ') { dc = 0; c++; } else { s = 3; break; } case 4: while (*c >= '0' && *c <= '9' && dc < 4) { y = 10 * y + (*c - '0'); if (y >= ymax) break; dc++; c++; } if (dc && *c == ' ') { dc = 0; c++; } else { s = 4; break; } case 5: s = 5; while (dc < 8) { if (*c >= '0' && *c <= '9') { col = (col << 4) | (*c - '0'); } else if (*c >= 'a' && *c <= 'f') { col = (col << 4) | (*c - 'a' + 0xA); } else if (*c >= 'A' && *c <= 'F') { col = (col << 4) | (*c - 'A' + 0xA); } else { break; } dc++; c++; } if (*c == '\r') { c++; s = 6; } case 6: if (*c == '\n' && (dc == 6 || dc == 8)) { c++; if (dc == 6) { canvas.set(x, y, col << 8); } else { canvas.blend(x, y, col); } s = x = y = col = dc = 0; goto case0; } else { break; } case7: case 7: switch (dc) { case 0: if (*c == 'I') c++; else { dc = 0; break; } case 1: if (*c == 'Z') c++; else { dc = 1; break; } case 2: if (*c == 'E') c++; else { dc = 2; break; } case 3: if (*c != '\n') { if (*c == '\r') c++; else { dc = 3; break; } } case 4: if (*c == '\n') { int pending; int err = ioctl(fd, SIOCOUTQ, &pending); if (err || pending) { break; } if (write(fd, sizeData, sizeLen) != sizeLen) { break; } s = x = y = col = dc = 0; c++; goto case0; } else { dc = 4; break; } } } if (s <= 2) { dc = s; s = 0; } else { s -= 2; } if (c == buf + size) { comb = s * 9 + dc; assert(!(col & ~0xFFFFFFFF)); assert(!(x & ~0x1FFF)); assert(!(y & ~0x1FFF)); assert(!(comb & ~0x3F)); state[fd] = col | (uint64_t(x) << 32) | (uint64_t(y) << 45) | (uint64_t(comb) << 58); } else { size = 0; BREAK_IF_ET; } } if (size == 0) { state[fd] = CLOSED_STATE; close(fd); #ifdef USE_ONESHOT_EPOLL } else { struct epoll_event ee = { .events = EPOLLIN | MODE, .data = { .fd = fd } }; int err = epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ee); if (err < 0) errno_exit("epoll_ctl rearm client"); #endif } } } } }
Use _SC_OPEN_MAX instead of /proc/sys/fs/file-max
Use _SC_OPEN_MAX instead of /proc/sys/fs/file-max
C++
agpl-3.0
lukaslihotzki/pixelflood,lukaslihotzki/pixelflood
c99983b9f0b8ab0291c74c0d32a0b833c7a900ed
src/usr/isteps/istep10/call_proc_pcie_scominit.C
src/usr/isteps/istep10/call_proc_pcie_scominit.C
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep10/call_proc_pcie_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** @file call_proc_pcie_scominit.C * * Support file for IStep: call_proc_pcie_scominit * This istep will do 2 things: * 1) Perform PCIE SCOM initialization * 2) Setup necessary PCIe Attributes for later HWPs/FW * to properly enable PCIe devices * * HWP_IGNORE_VERSION_CHECK * */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> #include <initservice/initserviceif.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <istepHelperFuncs.H> // captureError #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include "host_proc_pcie_scominit.H" #include <p10_pcie_scominit.H> namespace ISTEP_10 { using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; //***************************************************************************** // wrapper function to call proc_pcie_scominit //****************************************************************************** void* call_proc_pcie_scominit( void *io_pArgs ) { errlHndl_t l_err(nullptr); IStepError l_stepError; TARGETING::TargetHandleList l_procTargetList; TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_pcie_scominit enter" ); // Get a list of all proc chips getAllChips(l_procTargetList, TYPE_PROC); // Loop through all proc chips, set PCIe attributes, // convert to fap2 target, and execute hwp for (const auto & curproc : l_procTargetList) { /* TODO RTC:249139 -- Need to set necessary PCIe attributes for later HWPs/FW to enable the PCIe devices. Discussions still underway on how MRW + HWPs want this data represented l_errl = computeProcPcieConfigAttrs(l_cpu_target); if(l_errl != nullptr) { // Any failure to configure PCIE that makes it to this handler // implies a firmware bug that should be fixed, everything else // is tolerated internally (usually as disabled PHBs) TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK "call_proc_pcie_scominit> Failed in call to " "computeProcPcieConfigAttrs for target with HUID = " "0x%08X", l_cpu_target->getAttr<TARGETING::ATTR_HUID>() ); l_StepError.addErrorDetails(l_errl); errlCommit( l_errl, ISTEP_COMP_ID ); } **/ const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_proc_target( curproc); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p10_pcie_scominit HWP on " "target HUID %.8X", TARGETING::get_huid(curproc) ); FAPI_INVOKE_HWP(l_err, p10_pcie_scominit, l_fapi2_proc_target); if (l_err) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call p10_pcie_scominit HWP(): failed on target 0x%08X. " TRACE_ERR_FMT, get_huid(curproc), TRACE_ERR_ARGS(l_err)); // Capture Error captureError(l_err, l_stepError, HWPF_COMP_ID, curproc); // Run HWP on all procs even if one reports an error continue; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : proc_pcie_scominit HWP" ); } } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_pcie_scominit exit" ); // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } };
/* IBM_PROLOG_BEGIN_TAG */ /* This is an automatically generated prolog. */ /* */ /* $Source: src/usr/isteps/istep10/call_proc_pcie_scominit.C $ */ /* */ /* OpenPOWER HostBoot Project */ /* */ /* Contributors Listed Below - COPYRIGHT 2015,2020 */ /* [+] International Business Machines Corp. */ /* */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); */ /* you may not use this file except in compliance with the License. */ /* You may obtain a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or */ /* implied. See the License for the specific language governing */ /* permissions and limitations under the License. */ /* */ /* IBM_PROLOG_END_TAG */ /** @file call_proc_pcie_scominit.C * * Support file for IStep: call_proc_pcie_scominit * This istep will do 2 things: * 1) Perform PCIE SCOM initialization * 2) Setup necessary PCIe Attributes for later HWPs/FW * to properly enable PCIe devices * * HWP_IGNORE_VERSION_CHECK * */ /******************************************************************************/ // Includes /******************************************************************************/ #include <stdint.h> #include <trace/interface.H> #include <initservice/taskargs.H> #include <errl/errlentry.H> #include <isteps/hwpisteperror.H> #include <errl/errludtarget.H> #include <initservice/isteps_trace.H> #include <initservice/initserviceif.H> // targeting support #include <targeting/common/commontargeting.H> #include <targeting/common/utilFilter.H> #include <istepHelperFuncs.H> // captureError #include <fapi2/target.H> #include <fapi2/plat_hwp_invoker.H> #include "host_proc_pcie_scominit.H" #include <p10_pcie_scominit.H> namespace ISTEP_10 { using namespace ISTEP; using namespace ISTEP_ERROR; using namespace ERRORLOG; using namespace TARGETING; //***************************************************************************** // wrapper function to call proc_pcie_scominit //****************************************************************************** void* call_proc_pcie_scominit( void *io_pArgs ) { IStepError l_stepError; /* TODO RTC:249139 -- Need to set necessary PCIe attributes * for later HWPs/FW to enable the PCIe devices. Discussions * still underway on how MRW + HWPs want this data represented errlHndl_t l_err(nullptr); IStepError l_stepError; TARGETING::TargetHandleList l_procTargetList; TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_pcie_scominit enter" ); // Get a list of all proc chips getAllChips(l_procTargetList, TYPE_PROC); // Loop through all proc chips, set PCIe attributes, // convert to fap2 target, and execute hwp for (const auto & curproc : l_procTargetList) { l_errl = computeProcPcieConfigAttrs(l_cpu_target); if(l_errl != nullptr) { // Any failure to configure PCIE that makes it to this handler // implies a firmware bug that should be fixed, everything else // is tolerated internally (usually as disabled PHBs) TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK "call_proc_pcie_scominit> Failed in call to " "computeProcPcieConfigAttrs for target with HUID = " "0x%08X", l_cpu_target->getAttr<TARGETING::ATTR_HUID>() ); l_StepError.addErrorDetails(l_errl); errlCommit( l_errl, ISTEP_COMP_ID ); } const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2_proc_target( curproc); TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "Running p10_pcie_scominit HWP on " "target HUID %.8X", TARGETING::get_huid(curproc) ); FAPI_INVOKE_HWP(l_err, p10_pcie_scominit, l_fapi2_proc_target); if (l_err) { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "ERROR : call p10_pcie_scominit HWP(): failed on target 0x%08X. " TRACE_ERR_FMT, get_huid(curproc), TRACE_ERR_ARGS(l_err)); // Capture Error captureError(l_err, l_stepError, HWPF_COMP_ID, curproc); // Run HWP on all procs even if one reports an error continue; } else { TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "SUCCESS : proc_pcie_scominit HWP" ); } } TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace, "call_proc_pcie_scominit exit" ); **/ // end task, returning any errorlogs to IStepDisp return l_stepError.getErrorHandle(); } };
Disable call to p10_proc_pciescominit HWP Temporarily
Disable call to p10_proc_pciescominit HWP Temporarily - This HWP is going to be refactored, so will wait for updated version before re-enabling Change-Id: I020805525cc91f4421fb9dc5559b8115daa67116 Reviewed-on: http://rchgit01.rchland.ibm.com/gerrit1/91565 Tested-by: Jenkins Server <[email protected]> Reviewed-by: Ilya Smirnov <[email protected]> Reviewed-by: Michael Baiocchi <[email protected]> Tested-by: Jenkins OP Build CI <[email protected]> Reviewed-by: Nicholas E Bofferding <[email protected]>
C++
apache-2.0
open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot,open-power/hostboot
d80bb8de9c93c7c19fcf2eae6ecd355027dac764
src/xalanc/PlatformSupport/XalanOutputStream.hpp
src/xalanc/PlatformSupport/XalanOutputStream.hpp
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALANOUTPUTSTREAM_HEADER_GUARD_1357924680) #define XALANOUTPUTSTREAM_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <vector> #include <xalanc/XalanDOM/XalanDOMString.hpp> #include <xalanc/PlatformSupport/XSLException.hpp> XALAN_CPP_NAMESPACE_BEGIN class XalanOutputTranscoder; class XALAN_PLATFORMSUPPORT_EXPORT XalanOutputStream { public : enum { eDefaultBufferSize = 512, eDefaultTranscoderBlockSize = 1024 }; #if defined(XALAN_NO_STD_NAMESPACE) typedef vector<XalanDOMChar> BufferType; typedef vector<char> TranscodeVectorType; #else typedef std::vector<XalanDOMChar> BufferType; typedef std::vector<char> TranscodeVectorType; #endif typedef BufferType::size_type size_type; /** * Constructor. * * @param theBufferSize the size of the transcoding buffer * @param theTranscoderBlockSize the size of the block used by the transcoder * @param fThrowTranscodeException If true, an error transcoding will result in an exception being thrown. */ explicit XalanOutputStream( BufferType::size_type theBufferSize = eDefaultBufferSize, TranscodeVectorType::size_type theTranscoderBlockSize = eDefaultTranscoderBlockSize, bool fThrowTranscodeException = true); virtual ~XalanOutputStream(); static const XalanDOMChar* defaultNewlineString() { #if defined(XALAN_NEWLINE_IS_CRLF) return s_nlCRString; #else return s_nlString; #endif } /** * Write the appropriate newline character(s) to the stream. */ virtual void newline(); /** * Get the string which is appropriate for inserting a line feed in the stream. */ virtual const XalanDOMChar* getNewlineString() const; /** * Flush the stream's buffer. */ void flush() { flushBuffer(); doFlush(); } /** * Write a character to the output stream. The character * will not be transcoded. * * @param theChar the character to write */ void write(char theChar) { write(&theChar, 1); } /** * Write a wide character to the output stream. The character * will be transcoded, if an output encoding is specified. * * @param theChar the character to write */ void write(XalanDOMChar theChar) { assert(m_bufferSize > 0); if (m_buffer.size() == m_bufferSize) { flushBuffer(); } m_buffer.push_back(theChar); } /** * Write a null-terminated string to the output file. The character * will not be transcoded. * * @param theBuffer character buffer to write */ void write(const char* theBuffer) { assert(theBuffer != 0); write(theBuffer, length(theBuffer)); } /** * Write a null-terminated wide string to the output file. The string * will be transcoded, if an output encoding is specified. * * @param theBuffer character buffer to write */ void write(const XalanDOMChar* theBuffer) { write(theBuffer, length(theBuffer)); } /** * Write a specified number of characters to the output stream. The string * will not be transcoded. * * @param theBuffer character buffer to write * @param theBufferLength number of characters to write */ void write( const char* theBuffer, size_type theBufferLength) { assert(theBuffer != 0); flushBuffer(); writeData(theBuffer, theBufferLength); } /** * Write a specified number of characters to the output stream. The string * will be transcoded, if an output encoding is specified. * * @param theBuffer character buffer to write * @param theBufferLength number of characters to write */ void write( const XalanDOMChar* theBuffer, size_type theBufferLength); /** * Get the output encoding for the stream. * * @return The encoding name */ const XalanDOMString& getOutputEncoding() const { return m_encoding; } /** * Set the output encoding for the stream. * * @param theEncoding The encoding name */ void setOutputEncoding(const XalanDOMString& theEncoding); /** * Determine if a given value can be represented in * the output encoding. * * @return true if the value can be represented, and false if not. */ bool canTranscodeTo(unsigned int theChar) const; const XalanOutputTranscoder* getTranscoder() const { return m_transcoder; } /** * Set the flag that indicates whether a transcoding * error should throw an exception. The default is * to throw an exception. If this flag is false, and * and an error occurs transcoding, then data will * likely be lost. * * @return the value of the flag. */ bool getThrowTranscodeException() const { return m_throwTranscodeException; } /** * Set the flag that indicates whether a transcoding * error should throw an exception. The default is * to throw an exception. If this flag is false, and * and an error occurs transcoding, then data will * likely be lost. * * @param the new value of the flag. */ void setThrowTranscodeException(bool flag) { m_throwTranscodeException = flag; } /** * Set the size of the output buffer. * * @param theBufferSize The buffer size. */ void setBufferSize(BufferType::size_type theBufferSize); class XALAN_PLATFORMSUPPORT_EXPORT XalanOutputStreamException : public XSLException { public: XalanOutputStreamException( const XalanDOMString& theMessage, const XalanDOMString& theType); virtual ~XalanOutputStreamException(); }; class XALAN_PLATFORMSUPPORT_EXPORT UnknownEncodingException : public XalanOutputStreamException { public: explicit UnknownEncodingException(); virtual ~UnknownEncodingException(); }; class XALAN_PLATFORMSUPPORT_EXPORT UnsupportedEncodingException : public XalanOutputStreamException { public: UnsupportedEncodingException(const XalanDOMString& theEncoding); virtual ~UnsupportedEncodingException(); const XalanDOMString& getEncoding() const { return m_encoding; } private: const XalanDOMString m_encoding; }; class XALAN_PLATFORMSUPPORT_EXPORT TranscoderInternalFailureException : public XalanOutputStreamException { public: TranscoderInternalFailureException(const XalanDOMString& theEncoding); virtual ~TranscoderInternalFailureException(); const XalanDOMString& getEncoding() const { return m_encoding; } private: const XalanDOMString m_encoding; }; class XALAN_PLATFORMSUPPORT_EXPORT TranscodingException : public XalanOutputStreamException { public: explicit TranscodingException(); virtual ~TranscodingException(); }; protected: /** * Transcode a wide string. * * @param theBuffer The string to transcode. * @param theBufferLength The length of the string. * @param theDestination The destination vector. */ void transcode( const XalanDOMChar* theBuffer, size_type theBufferLength, TranscodeVectorType& theDestination); /** * Write the data in the buffer * * @param theBuffer The data to write * @param theBufferLength The length of theBuffer. */ virtual void writeData( const char* theBuffer, size_type theBufferLength) = 0; /** * Flush the stream. */ virtual void doFlush() = 0; static const XalanDOMChar s_nlString[]; static const XalanDOMChar s_nlCRString[]; static const XalanDOMString::size_type s_nlStringLength; static const XalanDOMString::size_type s_nlCRStringLength; private: // These are not implemented... XalanOutputStream(const XalanOutputStream&); XalanOutputStream& operator=(const XalanOutputStream&); bool operator==(const XalanOutputStream&) const; // Utility functions... void flushBuffer(); void doWrite( const XalanDOMChar* theBuffer, size_t theBufferLength); const TranscodeVectorType::size_type m_transcoderBlockSize; XalanOutputTranscoder* m_transcoder; BufferType::size_type m_bufferSize; BufferType m_buffer; XalanDOMString m_encoding; bool m_writeAsUTF16; bool m_throwTranscodeException; TranscodeVectorType m_transcodingBuffer; }; XALAN_CPP_NAMESPACE_END #endif // XALANOUTPUTSTREAM_HEADER_GUARD_1357924680
/* * The Apache Software License, Version 1.1 * * * Copyright (c) 1999-2003 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, * if any, must include the following acknowledgment: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowledgment may appear in the software itself, * if and wherever such third-party acknowledgments normally appear. * * 4. The names "Xalan" and "Apache Software Foundation" must * not be used to endorse or promote products derived from this * software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache", * nor may "Apache" appear in their name, without prior written * permission of the Apache Software Foundation. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation and was * originally based on software copyright (c) 1999, International * Business Machines, Inc., http://www.ibm.com. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ #if !defined(XALANOUTPUTSTREAM_HEADER_GUARD_1357924680) #define XALANOUTPUTSTREAM_HEADER_GUARD_1357924680 // Base include file. Must be first. #include <xalanc/PlatformSupport/PlatformSupportDefinitions.hpp> #include <vector> #include <xalanc/XalanDOM/XalanDOMString.hpp> #include <xalanc/PlatformSupport/XSLException.hpp> XALAN_CPP_NAMESPACE_BEGIN class XalanOutputTranscoder; class XALAN_PLATFORMSUPPORT_EXPORT XalanOutputStream { public : enum { eDefaultBufferSize = 512, eDefaultTranscoderBlockSize = 1024 }; #if defined(XALAN_NO_STD_NAMESPACE) typedef vector<XalanDOMChar> BufferType; typedef vector<char> TranscodeVectorType; #else typedef std::vector<XalanDOMChar> BufferType; typedef std::vector<char> TranscodeVectorType; #endif typedef BufferType::size_type size_type; /** * Constructor. * * @param theBufferSize the size of the transcoding buffer * @param theTranscoderBlockSize the size of the block used by the transcoder * @param fThrowTranscodeException If true, an error transcoding will result in an exception being thrown. */ explicit XalanOutputStream( BufferType::size_type theBufferSize = eDefaultBufferSize, TranscodeVectorType::size_type theTranscoderBlockSize = eDefaultTranscoderBlockSize, bool fThrowTranscodeException = true); virtual ~XalanOutputStream(); static const XalanDOMChar* defaultNewlineString() { #if defined(XALAN_NEWLINE_IS_CRLF) return s_nlCRString; #else return s_nlString; #endif } /** * Write the appropriate newline character(s) to the stream. */ virtual void newline(); /** * Get the string which is appropriate for inserting a line feed in the stream. */ virtual const XalanDOMChar* getNewlineString() const; /** * Flush the stream's buffer. */ void flush() { flushBuffer(); doFlush(); } /** * Write a character to the output stream. The character * will not be transcoded. * * @param theChar the character to write */ void write(char theChar) { write(&theChar, 1); } /** * Write a wide character to the output stream. The character * will be transcoded, if an output encoding is specified. * * @param theChar the character to write */ void write(XalanDOMChar theChar) { assert(m_bufferSize > 0); if (m_buffer.size() == m_bufferSize) { flushBuffer(); } m_buffer.push_back(theChar); } /** * Write a null-terminated string to the output file. The character * will not be transcoded. The caller is responsible for making sure the * buffer is flushed before calling this member function. * * @param theBuffer character buffer to write */ void write(const char* theBuffer) { assert(theBuffer != 0); assert(m_buffer.empty() == true); write(theBuffer, length(theBuffer)); } /** * Write a null-terminated wide string to the output file. The string * will be transcoded, if an output encoding is specified. * * @param theBuffer character buffer to write */ void write(const XalanDOMChar* theBuffer) { write(theBuffer, length(theBuffer)); } /** * Write a specified number of characters to the output stream. The string * will not be transcoded. The caller is responsible for making sure the * buffer is flushed before calling this member function. * * @param theBuffer character buffer to write * @param theBufferLength number of characters to write */ void write( const char* theBuffer, size_type theBufferLength) { assert(theBuffer != 0); assert(m_buffer.empty() == true); writeData(theBuffer, theBufferLength); } /** * Write a specified number of characters to the output stream. The string * will be transcoded, if an output encoding is specified. * * @param theBuffer character buffer to write * @param theBufferLength number of characters to write */ void write( const XalanDOMChar* theBuffer, size_type theBufferLength); /** * Get the output encoding for the stream. * * @return The encoding name */ const XalanDOMString& getOutputEncoding() const { return m_encoding; } /** * Set the output encoding for the stream. * * @param theEncoding The encoding name */ void setOutputEncoding(const XalanDOMString& theEncoding); /** * Determine if a given value can be represented in * the output encoding. * * @return true if the value can be represented, and false if not. */ bool canTranscodeTo(unsigned int theChar) const; const XalanOutputTranscoder* getTranscoder() const { return m_transcoder; } /** * Set the flag that indicates whether a transcoding * error should throw an exception. The default is * to throw an exception. If this flag is false, and * and an error occurs transcoding, then data will * likely be lost. * * @return the value of the flag. */ bool getThrowTranscodeException() const { return m_throwTranscodeException; } /** * Set the flag that indicates whether a transcoding * error should throw an exception. The default is * to throw an exception. If this flag is false, and * and an error occurs transcoding, then data will * likely be lost. * * @param the new value of the flag. */ void setThrowTranscodeException(bool flag) { m_throwTranscodeException = flag; } /** * Set the size of the output buffer. * * @param theBufferSize The buffer size. */ void setBufferSize(BufferType::size_type theBufferSize); class XALAN_PLATFORMSUPPORT_EXPORT XalanOutputStreamException : public XSLException { public: XalanOutputStreamException( const XalanDOMString& theMessage, const XalanDOMString& theType); virtual ~XalanOutputStreamException(); }; class XALAN_PLATFORMSUPPORT_EXPORT UnknownEncodingException : public XalanOutputStreamException { public: explicit UnknownEncodingException(); virtual ~UnknownEncodingException(); }; class XALAN_PLATFORMSUPPORT_EXPORT UnsupportedEncodingException : public XalanOutputStreamException { public: UnsupportedEncodingException(const XalanDOMString& theEncoding); virtual ~UnsupportedEncodingException(); const XalanDOMString& getEncoding() const { return m_encoding; } private: const XalanDOMString m_encoding; }; class XALAN_PLATFORMSUPPORT_EXPORT TranscoderInternalFailureException : public XalanOutputStreamException { public: TranscoderInternalFailureException(const XalanDOMString& theEncoding); virtual ~TranscoderInternalFailureException(); const XalanDOMString& getEncoding() const { return m_encoding; } private: const XalanDOMString m_encoding; }; class XALAN_PLATFORMSUPPORT_EXPORT TranscodingException : public XalanOutputStreamException { public: explicit TranscodingException(); virtual ~TranscodingException(); }; protected: /** * Transcode a wide string. * * @param theBuffer The string to transcode. * @param theBufferLength The length of the string. * @param theDestination The destination vector. */ void transcode( const XalanDOMChar* theBuffer, size_type theBufferLength, TranscodeVectorType& theDestination); /** * Write the data in the buffer * * @param theBuffer The data to write * @param theBufferLength The length of theBuffer. */ virtual void writeData( const char* theBuffer, size_type theBufferLength) = 0; /** * Flush the stream. */ virtual void doFlush() = 0; static const XalanDOMChar s_nlString[]; static const XalanDOMChar s_nlCRString[]; static const XalanDOMString::size_type s_nlStringLength; static const XalanDOMString::size_type s_nlCRStringLength; private: // These are not implemented... XalanOutputStream(const XalanOutputStream&); XalanOutputStream& operator=(const XalanOutputStream&); bool operator==(const XalanOutputStream&) const; // Utility functions... void flushBuffer(); void doWrite( const XalanDOMChar* theBuffer, size_t theBufferLength); const TranscodeVectorType::size_type m_transcoderBlockSize; XalanOutputTranscoder* m_transcoder; BufferType::size_type m_bufferSize; BufferType m_buffer; XalanDOMString m_encoding; bool m_writeAsUTF16; bool m_throwTranscodeException; TranscodeVectorType m_transcodingBuffer; }; XALAN_CPP_NAMESPACE_END #endif // XALANOUTPUTSTREAM_HEADER_GUARD_1357924680
Modify write() function to assume buffer has been flushed.
Modify write() function to assume buffer has been flushed.
C++
apache-2.0
apache/xalan-c,apache/xalan-c,apache/xalan-c,apache/xalan-c
94d09faa9332ca48c0b958b088fbb9c6ca59bd7f
test/std/numerics/cfenv/cfenv.syn/cfenv.pass.cpp
test/std/numerics/cfenv/cfenv.syn/cfenv.pass.cpp
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: newlib // <cfenv> #include <cfenv> #include <type_traits> #ifndef FE_DIVBYZERO #error FE_DIVBYZERO not defined #endif #ifndef FE_INEXACT #error FE_INEXACT not defined #endif #ifndef FE_INVALID #error FE_INVALID not defined #endif #ifndef FE_OVERFLOW #error FE_OVERFLOW not defined #endif #ifndef FE_UNDERFLOW #error FE_UNDERFLOW not defined #endif #ifndef FE_ALL_EXCEPT #error FE_ALL_EXCEPT not defined #endif #ifndef FE_DOWNWARD #error FE_DOWNWARD not defined #endif #ifndef FE_TONEAREST #error FE_TONEAREST not defined #endif #ifndef FE_TOWARDZERO #error FE_TOWARDZERO not defined #endif #ifndef FE_UPWARD #error FE_UPWARD not defined #endif #ifndef FE_DFL_ENV #error FE_DFL_ENV not defined #endif int main() { std::fenv_t fenv = {0}; std::fexcept_t fex = 0; static_assert((std::is_same<decltype(std::feclearexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetexceptflag(&fex, 0)), int>::value), ""); static_assert((std::is_same<decltype(std::feraiseexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fesetexceptflag(&fex, 0)), int>::value), ""); static_assert((std::is_same<decltype(std::fetestexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetround()), int>::value), ""); static_assert((std::is_same<decltype(std::fesetround(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetenv(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::feholdexcept(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::fesetenv(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::feupdateenv(&fenv)), int>::value), ""); }
//===----------------------------------------------------------------------===// // // The LLVM Compiler Infrastructure // // This file is dual licensed under the MIT and the University of Illinois Open // Source Licenses. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // UNSUPPORTED: newlib // <cfenv> #include <cfenv> #include <type_traits> #ifndef FE_DIVBYZERO #error FE_DIVBYZERO not defined #endif #ifndef FE_INEXACT #error FE_INEXACT not defined #endif #ifndef FE_INVALID #error FE_INVALID not defined #endif #ifndef FE_OVERFLOW #error FE_OVERFLOW not defined #endif #ifndef FE_UNDERFLOW #error FE_UNDERFLOW not defined #endif #ifndef FE_ALL_EXCEPT #error FE_ALL_EXCEPT not defined #endif #ifndef FE_DOWNWARD #error FE_DOWNWARD not defined #endif #ifndef FE_TONEAREST #error FE_TONEAREST not defined #endif #ifndef FE_TOWARDZERO #error FE_TOWARDZERO not defined #endif #ifndef FE_UPWARD #error FE_UPWARD not defined #endif #ifndef FE_DFL_ENV #error FE_DFL_ENV not defined #endif int main() { std::fenv_t fenv; std::fexcept_t fex; static_assert((std::is_same<decltype(std::feclearexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetexceptflag(&fex, 0)), int>::value), ""); static_assert((std::is_same<decltype(std::feraiseexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fesetexceptflag(&fex, 0)), int>::value), ""); static_assert((std::is_same<decltype(std::fetestexcept(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetround()), int>::value), ""); static_assert((std::is_same<decltype(std::fesetround(0)), int>::value), ""); static_assert((std::is_same<decltype(std::fegetenv(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::feholdexcept(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::fesetenv(&fenv)), int>::value), ""); static_assert((std::is_same<decltype(std::feupdateenv(&fenv)), int>::value), ""); }
Remove unneeded initialisation of fenv_t and fexcept_t.
Remove unneeded initialisation of fenv_t and fexcept_t. Though common, there is no requirement that fenv_t and fexcept_t are structure and integer types, respectively. fexcept_t is a structure on CloudABI. git-svn-id: 756ef344af921d95d562d9e9f9389127a89a6314@232329 91177308-0d34-0410-b5e6-96231b3b80d8
C++
apache-2.0
llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx,llvm-mirror/libcxx
5175939d1edc87ba5ccc9e57c06bc98258d41dec
tutorials/dataframe/df030_SQliteVersionsOfROOT.C
tutorials/dataframe/df030_SQliteVersionsOfROOT.C
/// \file /// \ingroup tutorial_dataframe /// \notebook -js /// Plot the downloads of different ROOT versions reading a remote sqlite3 file with RSqliteDS. /// Then a TH1F histogram is created and filled /// using a lambda expression which receives the recorded /// values in the “version” column of the sqlite3 database. /// The histogram shows the usage of the ROOT development version. /// /// \macro_code /// \macro_image /// /// \date August 2018 /// \author Alexandra-Maria Dobrescu void df030_SQliteVersionsOfROOT() { auto rdf = ROOT::RDF::MakeSqliteDataFrame("http://root.cern/files/root_download_stats.sqlite", "SELECT Version FROM accesslog;"); TH1F hVersionOfRoot("hVersionOfRoot", "Development Versions of ROOT", 8, 0, -1); auto fillVersionHisto = [&hVersionOfRoot] (const std::string &version) { TString copyVersion = version; TString shortVersion(copyVersion(0,4)); hVersionOfRoot.Fill(shortVersion, 1); }; rdf.Foreach( fillVersionHisto, { "Version" } ); auto VersionOfRootHistogram = new TCanvas(); gStyle->SetOptStat(0); hVersionOfRoot.GetXaxis()->LabelsOption("a"); hVersionOfRoot.LabelsDeflate("X"); hVersionOfRoot.DrawClone(""); }
/// \file /// \ingroup tutorial_dataframe /// \notebook -js /// Plot the downloads of different ROOT versions reading a remote sqlite3 file with RSqliteDS. /// Then a TH1F histogram is created and filled /// using a lambda expression which receives the recorded /// values in the "version" column of the sqlite3 database. /// The histogram shows the usage of the ROOT development version. /// /// \macro_code /// \macro_image /// /// \date August 2018 /// \author Alexandra-Maria Dobrescu void df030_SQliteVersionsOfROOT() { auto rdf = ROOT::RDF::MakeSqliteDataFrame("http://root.cern/files/root_download_stats.sqlite", "SELECT Version FROM accesslog;"); TH1F hVersionOfRoot("hVersionOfRoot", "Development Versions of ROOT", 8, 0, -1); auto fillVersionHisto = [&hVersionOfRoot] (const std::string &version) { TString copyVersion = version; TString shortVersion(copyVersion(0,4)); hVersionOfRoot.Fill(shortVersion, 1); }; rdf.Foreach( fillVersionHisto, { "Version" } ); auto VersionOfRootHistogram = new TCanvas(); gStyle->SetOptStat(0); hVersionOfRoot.GetXaxis()->LabelsOption("a"); hVersionOfRoot.LabelsDeflate("X"); hVersionOfRoot.DrawClone(""); }
Remove non-ascii character from sql tutorial
[DF][NFC] Remove non-ascii character from sql tutorial
C++
lgpl-2.1
karies/root,olifre/root,root-mirror/root,olifre/root,karies/root,root-mirror/root,olifre/root,karies/root,olifre/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,olifre/root,root-mirror/root,root-mirror/root,root-mirror/root,olifre/root,olifre/root,root-mirror/root,karies/root,root-mirror/root,karies/root,olifre/root,karies/root,karies/root,karies/root,olifre/root,karies/root,karies/root,root-mirror/root,karies/root,root-mirror/root
6587fbb89675af9083bd33a331582898eb7ec9fc
omaha_request_params.cc
omaha_request_params.cc
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "update_engine/omaha_request_params.h" #include <errno.h> #include <fcntl.h> #include <sys/utsname.h> #include <map> #include <string> #include <vector> #include <base/file_util.h> #include <policy/device_policy.h> #include "update_engine/simple_key_value_store.h" #include "update_engine/system_state.h" #include "update_engine/utils.h" #define CALL_MEMBER_FN(object, member) ((object).*(member)) using std::map; using std::string; using std::vector; namespace chromeos_update_engine { const char* const OmahaRequestParams::kAppId( "{e96281a6-d1af-4bde-9a0a-97b76e56dc57}"); const char* const OmahaRequestParams::kOsPlatform("CoreOS"); const char* const OmahaRequestParams::kOsVersion("Chateau"); const char* const OmahaRequestParams::kDefaultChannel("stable"); const char* const kProductionOmahaUrl( "https://public.update.core-os.net/v1/update/"); bool OmahaRequestParams::Init(bool interactive) { os_platform_ = OmahaRequestParams::kOsPlatform; os_version_ = OmahaRequestParams::kOsVersion; oemid_ = GetOemValue("ID", ""); app_version_ = GetConfValue("COREOS_RELEASE_VERSION", ""); os_sp_ = app_version_ + "_" + GetMachineType(); os_board_ = GetConfValue("COREOS_RELEASE_BOARD", ""); app_id_ = GetConfValue("COREOS_RELEASE_APPID", OmahaRequestParams::kAppId); app_lang_ = "en-US"; bootid_ = utils::GetBootId(); machineid_ = utils::GetMachineId(); update_url_ = GetConfValue("SERVER", kProductionOmahaUrl); interactive_ = interactive; app_channel_ = GetConfValue("GROUP", kDefaultChannel); LOG(INFO) << "Current group set to " << app_channel_; // TODO: deltas can only be enabled if verity is active. delta_okay_ = false; return true; } string OmahaRequestParams::SearchConfValue(const vector<string>& files, const string& key, const string& default_value) const { for (vector<string>::const_iterator it = files.begin(); it != files.end(); ++it) { string file_data; if (!utils::ReadFile(root_ + *it, &file_data)) continue; map<string, string> data = simple_key_value_store::ParseString(file_data); if (utils::MapContainsKey(data, key)) { const string& value = data[key]; return value; } } // not found return default_value; } string OmahaRequestParams::GetConfValue(const string& key, const string& default_value) const { vector<string> files; files.push_back("/etc/coreos/update.conf"); files.push_back("/usr/share/coreos/update.conf"); files.push_back("/usr/share/coreos/release"); return SearchConfValue(files, key, default_value); } string OmahaRequestParams::GetOemValue(const string& key, const string& default_value) const { vector<string> files; files.push_back("/etc/coreos/update.conf"); return SearchConfValue(files, key, default_value); } string OmahaRequestParams::GetMachineType() const { struct utsname buf; string ret; if (uname(&buf) == 0) ret = buf.machine; return ret; } void OmahaRequestParams::set_root(const std::string& root) { root_ = root; Init(false); } } // namespace chromeos_update_engine
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "update_engine/omaha_request_params.h" #include <errno.h> #include <fcntl.h> #include <sys/utsname.h> #include <map> #include <string> #include <vector> #include <base/file_util.h> #include <policy/device_policy.h> #include "update_engine/simple_key_value_store.h" #include "update_engine/system_state.h" #include "update_engine/utils.h" #define CALL_MEMBER_FN(object, member) ((object).*(member)) using std::map; using std::string; using std::vector; namespace chromeos_update_engine { const char* const OmahaRequestParams::kAppId( "{e96281a6-d1af-4bde-9a0a-97b76e56dc57}"); const char* const OmahaRequestParams::kOsPlatform("CoreOS"); const char* const OmahaRequestParams::kOsVersion("Chateau"); const char* const OmahaRequestParams::kDefaultChannel("stable"); const char* const kProductionOmahaUrl( "https://public.update.core-os.net/v1/update/"); bool OmahaRequestParams::Init(bool interactive) { os_platform_ = OmahaRequestParams::kOsPlatform; os_version_ = OmahaRequestParams::kOsVersion; oemid_ = GetOemValue("ID", ""); app_version_ = GetConfValue("COREOS_RELEASE_VERSION", ""); os_sp_ = app_version_ + "_" + GetMachineType(); os_board_ = GetConfValue("COREOS_RELEASE_BOARD", ""); app_id_ = GetConfValue("COREOS_RELEASE_APPID", OmahaRequestParams::kAppId); app_lang_ = "en-US"; bootid_ = utils::GetBootId(); machineid_ = utils::GetMachineId(); update_url_ = GetConfValue("SERVER", kProductionOmahaUrl); interactive_ = interactive; app_channel_ = GetConfValue("GROUP", kDefaultChannel); LOG(INFO) << "Current group set to " << app_channel_; // TODO: deltas can only be enabled if verity is active. delta_okay_ = false; return true; } string OmahaRequestParams::SearchConfValue(const vector<string>& files, const string& key, const string& default_value) const { for (vector<string>::const_iterator it = files.begin(); it != files.end(); ++it) { string file_data; if (!utils::ReadFile(root_ + *it, &file_data)) continue; map<string, string> data = simple_key_value_store::ParseString(file_data); if (utils::MapContainsKey(data, key)) { const string& value = data[key]; return value; } } // not found return default_value; } string OmahaRequestParams::GetConfValue(const string& key, const string& default_value) const { vector<string> files; files.push_back("/etc/coreos/update.conf"); files.push_back("/usr/share/coreos/update.conf"); files.push_back("/usr/share/coreos/release"); return SearchConfValue(files, key, default_value); } string OmahaRequestParams::GetOemValue(const string& key, const string& default_value) const { vector<string> files; files.push_back("/etc/oem-release"); return SearchConfValue(files, key, default_value); } string OmahaRequestParams::GetMachineType() const { struct utsname buf; string ret; if (uname(&buf) == 0) ret = buf.machine; return ret; } void OmahaRequestParams::set_root(const std::string& root) { root_ = root; Init(false); } } // namespace chromeos_update_engine
fix reading OEM attributes
omaha_request_params: fix reading OEM attributes This was broken in commit 92dae274 during some refactoring.
C++
bsd-3-clause
mjg59/update_engine,mjg59/update_engine,mjg59/update_engine,endocode/update_engine,endocode/update_engine,endocode/update_engine
fd5bf16a902849bf304357fc65dbbf5ba9620f3a
include/Nazara/Renderer/ShaderBuilder.hpp
include/Nazara/Renderer/ShaderBuilder.hpp
// Copyright (C) 2016 Jérôme Leclercq // This file is part of the "Nazara Engine - Renderer module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_SHADER_BUILDER_HPP #define NAZARA_SHADER_BUILDER_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Renderer/ShaderAst.hpp> #include <memory> namespace Nz { namespace ShaderBuilder { template<ShaderAst::AssignType op> struct AssignOpBuilder { constexpr AssignOpBuilder() = default; std::shared_ptr<ShaderAst::AssignOp> operator()(const ShaderAst::VariablePtr& left, const ShaderAst::ExpressionPtr& right) const; }; template<ShaderAst::BinaryType op> struct BinOpBuilder { constexpr BinOpBuilder() = default; std::shared_ptr<ShaderAst::BinaryOp> operator()(const ShaderAst::ExpressionPtr& left, const ShaderAst::ExpressionPtr& right) const; }; struct BuiltinBuilder { constexpr BuiltinBuilder() = default; std::shared_ptr<ShaderAst::Variable> operator()(ShaderAst::BuiltinEntry builtin) const; }; template<typename T> struct GenBuilder { constexpr GenBuilder() = default; template<typename... Args> std::shared_ptr<T> operator()(Args&&... args) const; }; template<ShaderAst::VariableType type> struct VarBuilder { constexpr VarBuilder() = default; template<typename... Args> std::shared_ptr<ShaderAst::Variable> operator()(Args&&... args) const; }; constexpr BinOpBuilder<ShaderAst::BinaryType::Add> Add; constexpr AssignOpBuilder<ShaderAst::AssignType::Simple> Assign; constexpr BuiltinBuilder Builtin; constexpr GenBuilder<ShaderAst::StatementBlock> Block; constexpr GenBuilder<ShaderAst::Branch> Branch; constexpr GenBuilder<ShaderAst::Constant> Constant; constexpr BinOpBuilder<ShaderAst::BinaryType::Divide> Divide; constexpr BinOpBuilder<ShaderAst::BinaryType::Equality> Equal; constexpr GenBuilder<ShaderAst::ExpressionStatement> ExprStatement; constexpr VarBuilder<ShaderAst::VariableType::Input> Input; constexpr BinOpBuilder<ShaderAst::BinaryType::Multiply> Multiply; constexpr VarBuilder<ShaderAst::VariableType::Output> Output; constexpr VarBuilder<ShaderAst::VariableType::Parameter> Parameter; constexpr BinOpBuilder<ShaderAst::BinaryType::Substract> Substract; constexpr VarBuilder<ShaderAst::VariableType::Uniform> Uniform; constexpr VarBuilder<ShaderAst::VariableType::Variable> Variable; template<ShaderAst::ExpressionType Type, typename... Args> std::shared_ptr<ShaderAst::Cast> Cast(Args&&... args); } } #include <Nazara/Renderer/ShaderBuilder.inl> #endif // NAZARA_SHADER_BUILDER_HPP
// Copyright (C) 2016 Jérôme Leclercq // This file is part of the "Nazara Engine - Renderer module" // For conditions of distribution and use, see copyright notice in Config.hpp #pragma once #ifndef NAZARA_SHADER_BUILDER_HPP #define NAZARA_SHADER_BUILDER_HPP #include <Nazara/Prerequesites.hpp> #include <Nazara/Renderer/ShaderAst.hpp> #include <memory> namespace Nz { namespace ShaderBuilder { template<ShaderAst::AssignType op> struct AssignOpBuilder { constexpr AssignOpBuilder() {} std::shared_ptr<ShaderAst::AssignOp> operator()(const ShaderAst::VariablePtr& left, const ShaderAst::ExpressionPtr& right) const; }; template<ShaderAst::BinaryType op> struct BinOpBuilder { constexpr BinOpBuilder() {} std::shared_ptr<ShaderAst::BinaryOp> operator()(const ShaderAst::ExpressionPtr& left, const ShaderAst::ExpressionPtr& right) const; }; struct BuiltinBuilder { constexpr BuiltinBuilder() {} std::shared_ptr<ShaderAst::Variable> operator()(ShaderAst::BuiltinEntry builtin) const; }; template<typename T> struct GenBuilder { constexpr GenBuilder() {} template<typename... Args> std::shared_ptr<T> operator()(Args&&... args) const; }; template<ShaderAst::VariableType type> struct VarBuilder { constexpr VarBuilder() {} template<typename... Args> std::shared_ptr<ShaderAst::Variable> operator()(Args&&... args) const; }; constexpr BinOpBuilder<ShaderAst::BinaryType::Add> Add; constexpr AssignOpBuilder<ShaderAst::AssignType::Simple> Assign; constexpr BuiltinBuilder Builtin; constexpr GenBuilder<ShaderAst::StatementBlock> Block; constexpr GenBuilder<ShaderAst::Branch> Branch; constexpr GenBuilder<ShaderAst::Constant> Constant; constexpr BinOpBuilder<ShaderAst::BinaryType::Divide> Divide; constexpr BinOpBuilder<ShaderAst::BinaryType::Equality> Equal; constexpr GenBuilder<ShaderAst::ExpressionStatement> ExprStatement; constexpr VarBuilder<ShaderAst::VariableType::Input> Input; constexpr BinOpBuilder<ShaderAst::BinaryType::Multiply> Multiply; constexpr VarBuilder<ShaderAst::VariableType::Output> Output; constexpr VarBuilder<ShaderAst::VariableType::Parameter> Parameter; constexpr BinOpBuilder<ShaderAst::BinaryType::Substract> Substract; constexpr VarBuilder<ShaderAst::VariableType::Uniform> Uniform; constexpr VarBuilder<ShaderAst::VariableType::Variable> Variable; template<ShaderAst::ExpressionType Type, typename... Args> std::shared_ptr<ShaderAst::Cast> Cast(Args&&... args); } } #include <Nazara/Renderer/ShaderBuilder.inl> #endif // NAZARA_SHADER_BUILDER_HPP
Fix build?
Renderer/ShaderBuild: Fix build?
C++
mit
DigitalPulseSoftware/NazaraEngine
a268cf0269b8781c05f3f7f3e6077e34b5d177d5
include/cppurses/widget/layouts/stack.hpp
include/cppurses/widget/layouts/stack.hpp
#ifndef CPPURSES_WIDGET_LAYOUTS_STACK_HPP #define CPPURSES_WIDGET_LAYOUTS_STACK_HPP #include <algorithm> #include <cstddef> #include <iterator> #include <memory> #include <stdexcept> #include <type_traits> #include <utility> #include <vector> #include <signals/signals.hpp> #include <cppurses/system/events/move_event.hpp> #include <cppurses/system/events/resize_event.hpp> #include <cppurses/system/system.hpp> #include <cppurses/widget/layout.hpp> namespace cppurses { namespace layout { /// A Layout enabling only a single Widget at a time. /** A Stack is made up of pages, which are child Widgets that can be displayed * one at a time within the Stack. The active page determines which child * Widget is currently displayed. */ template <typename Child_t = Widget> class Stack : public Layout<Child_t> { public: /// Emitted when the active page is changed, sends the new index along. sig::Signal<void(std::size_t)> page_changed; public: /// Set child Widget to be enabled/visible via its index into child vector. /** The index is typically the same order as child Widgets were added. * Throws std::out_of_range if \p index is invalid. */ void set_active_page(std::size_t index) { if (index > this->Stack::size()) throw std::out_of_range{"Stack::set_active_page: index is invalid"}; active_page_ = &(this->Layout<Child_t>::get_children()[index]); this->enable(this->enabled(), false); // sends enable/disable events this->move_active_page(); this->resize_active_page(); if (sets_focus_) System::set_focus(*active_page_); this->page_changed(index); } /// Set whether Focus is given to a child Widget when it becomes active. /** Enabled by default. */ void give_focus_on_change(bool sets_focus = true) { sets_focus_ = sets_focus; } /// Construct and append a page to the Stack. /** This will construct a child Widget of type T, using \p args passed to * T's constructor, and then automatically disable it. Returns a reference * to the created child Widget. */ template <typename Widget_t = Child_t, typename... Args> auto make_page(Args&&... args) -> Widget_t& { static_assert(std::is_base_of<Child_t, Widget_t>::value, "Stack::make_page: Widget_t must be a Child_t type"); return static_cast<Widget_t&>(this->append_page( std::make_unique<Widget_t>(std::forward<Args>(args)...))); } /// Add an existing Widget as a page to the end of the Stack. /** Returns a reference to the appended Widget as Child_t&. */ auto append_page(std::unique_ptr<Child_t> child) -> Child_t& { auto& result = this->Layout<Child_t>::append_child(std::move(child)); result.disable(); return result; } /// Insert an existing Widget \p child at \p index. /** Throws std::invalid_argument if \p child is nullptr. * Throws std::out_of_range if \p index > number of children. * Returns a reference to the inserted Child_t object. */ auto insert_page(std::unique_ptr<Child_t> child, std::size_t index) -> Child_t& { auto& result = this->Layout<Child_t>::insert_child(std::move(child), index); result.disable(); return result; } /// Remove a page from the list, by \p index value, and delete it. /** Throws std::out_of_range if \p index is invalid. Sets active page to * nullptr if the active page is being deleted. */ void delete_page(std::size_t index) { if (index >= this->Stack::size()) throw std::out_of_range{"Stack::delete_page: index is invalid"}; auto* page_to_delete = &(this->Layout<Child_t>::get_children()[index]); if (page_to_delete == this->active_page()) active_page_ = nullptr; page_to_delete->close(); } /// Remove page at \p index from the list and return it. /** Useful if you need to move a page into another Widget. Use * Stack::delete_page() if you want to remove a page and destroy it. * Letting the returned Widget destroy itself will potentially leave * dangling pointers in the event system. Throws std::out_of_range if \p * index is invalid. Sets active page to nullptr if active page removed. */ auto remove_page(std::size_t index) -> std::unique_ptr<Widget> { if (index >= this->size()) throw std::out_of_range{"Stack::remove_page: index is invalid."}; auto* page_to_remove = &(this->Layout<Child_t>::get_children()[index]); if (page_to_remove == this->active_page()) active_page_ = nullptr; return this->Layout<Child_t>::remove_child(page_to_remove); } /// Remove and delete all pages. void clear() { // Can't use a range-for loop, Widget::close modifies the child_list_ while (!this->get_children().empty()) this->delete_page(0); } /// Return number of pages in this Stack. // TODO change to page_count() auto size() const -> std::size_t { return this->child_count(); } /// Return a pointer to the current active page, or nullptr if none. auto active_page() const -> Child_t* { return active_page_; } /// Return the index of the current active page. /** Returns Stack::invalid_index if active_page_ is nullptr. */ auto active_page_index() const -> std::size_t { if (active_page_ == nullptr) return Stack::invalid_index; auto const begin = std::cbegin(this->get_children()); auto const end = std::cbegin(this->get_children()); auto iter = std::find_if( begin, end, [this](auto const& w) { return &w == active_page_; }); return std::distance(begin, iter); } /// Post an Enable_event or Disable_event to the active page. void enable(bool enable = true, bool post_child_polished_event = true) override { this->Widget::enable_and_post_events(enable, post_child_polished_event); for (auto& child : this->get_children()) { if (&child == active_page_) child.enable(enable, post_child_polished_event); else child.disable(); } } /// Used to indicate an error on return values of index type. static auto constexpr invalid_index = static_cast<std::size_t>(-1); protected: auto move_event(Point new_position, Point old_position) -> bool override { this->move_active_page(); return Layout<Child_t>::move_event(new_position, old_position); } auto resize_event(Area new_size, Area old_size) -> bool override { this->resize_active_page(); return Layout<Child_t>::resize_event(new_size, old_size); } void update_geometry() override {} private: Child_t* active_page_ = nullptr; bool sets_focus_ = true; private: void move_active_page() { if (active_page_ != nullptr) System::post_event<Move_event>(*active_page_, this->top_left()); } void resize_active_page() { if (active_page_ != nullptr) System::post_event<Resize_event>(*active_page_, this->outer_area()); } }; } // namespace layout // - - - - - - - - - - - - - - - - Slots - - - - - - - - - - - - - - - - - - - - namespace slot { template <typename Child_t> auto set_active_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t)> { auto slot = sig::Slot<void(std::size_t)>{ [&stack](auto index) { stack.set_active_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto set_active_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void()> { auto slot = sig::Slot<void()>{[&stack, index] { stack.set_active_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto delete_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t)> { auto slot = sig::Slot<void(std::size_t)>{ [&stack](auto index) { stack.delete_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto delete_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void()> { auto slot = sig::Slot<void()>{[&stack, index] { stack.delete_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto insert_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t, std::unique_ptr<Widget>)> { auto slot = sig::Slot<void(std::size_t, std::unique_ptr<Widget>)>{ [&stack](auto index, auto widget) { stack.insert_page(index, std::move(widget)); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto insert_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void(std::unique_ptr<Widget>)> { auto slot = sig::Slot<void(std::unique_ptr<Widget>)>{[&stack, index](auto widget) { stack.insert_page(index, std::move(widget)); }}; slot.track(stack.destroyed); return slot; } } // namespace slot } // namespace cppurses #endif // CPPURSES_WIDGET_LAYOUTS_STACK_HPP
#ifndef CPPURSES_WIDGET_LAYOUTS_STACK_HPP #define CPPURSES_WIDGET_LAYOUTS_STACK_HPP #include <algorithm> #include <cstddef> #include <iterator> #include <memory> #include <stdexcept> #include <type_traits> #include <utility> #include <vector> #include <signals/signals.hpp> #include <cppurses/system/events/move_event.hpp> #include <cppurses/system/events/resize_event.hpp> #include <cppurses/system/system.hpp> #include <cppurses/widget/layout.hpp> namespace cppurses { namespace layout { /// A Layout enabling only a single Widget at a time. /** A Stack is made up of pages, which are child Widgets that can be displayed * one at a time within the Stack. The active page determines which child * Widget is currently displayed. */ template <typename Child_t = Widget> class Stack : public Layout<Child_t> { public: /// Emitted when the active page is changed, sends the new index along. sig::Signal<void(std::size_t)> page_changed; public: /// Set child Widget to be enabled/visible via its index into child vector. /** The index is typically the same order as child Widgets were added. * Throws std::out_of_range if \p index is invalid. */ void set_active_page(std::size_t index) { if (index > this->Stack::size()) throw std::out_of_range{"Stack::set_active_page: index is invalid"}; active_page_ = &(this->Layout<Child_t>::get_children()[index]); this->enable(this->enabled(), false); // sends enable/disable events this->move_active_page(); this->resize_active_page(); if (sets_focus_) System::set_focus(*active_page_); this->page_changed(index); } /// Set whether Focus is given to a child Widget when it becomes active. /** Enabled by default. */ void give_focus_on_change(bool sets_focus = true) { sets_focus_ = sets_focus; } /// Construct and append a page to the Stack. /** This will construct a child Widget of type T, using \p args passed to * T's constructor, and then automatically disable it. Returns a reference * to the created child Widget. */ template <typename Widget_t = Child_t, typename... Args> auto make_page(Args&&... args) -> Widget_t& { static_assert(std::is_base_of<Child_t, Widget_t>::value, "Stack::make_page: Widget_t must be a Child_t type"); return static_cast<Widget_t&>(this->append_page( std::make_unique<Widget_t>(std::forward<Args>(args)...))); } /// Add an existing Widget as a page to the end of the Stack. /** Returns a reference to the appended Widget as Child_t&. */ auto append_page(std::unique_ptr<Child_t> child) -> Child_t& { auto& result = this->Layout<Child_t>::append_child(std::move(child)); result.disable(); return result; } /// Insert an existing Widget \p child at \p index. /** Throws std::invalid_argument if \p child is nullptr. * Throws std::out_of_range if \p index > number of children. * Returns a reference to the inserted Child_t object. */ auto insert_page(std::unique_ptr<Child_t> child, std::size_t index) -> Child_t& { auto& result = this->Layout<Child_t>::insert_child(std::move(child), index); result.disable(); return result; } /// Remove a page from the list, by \p index value, and delete it. /** Throws std::out_of_range if \p index is invalid. Sets active page to * nullptr if the active page is being deleted. */ void delete_page(std::size_t index) { if (index >= this->Stack::size()) throw std::out_of_range{"Stack::delete_page: index is invalid"}; auto* page_to_delete = &(this->Layout<Child_t>::get_children()[index]); if (page_to_delete == this->active_page()) active_page_ = nullptr; page_to_delete->close(); } /// Remove page at \p index from the list and return it. /** Useful if you need to move a page into another Widget. Use * Stack::delete_page() if you want to remove a page and destroy it. * Letting the returned Widget destroy itself will potentially leave * dangling pointers in the event system. Throws std::out_of_range if \p * index is invalid. Sets active page to nullptr if active page removed. */ auto remove_page(std::size_t index) -> std::unique_ptr<Widget> { if (index >= this->size()) throw std::out_of_range{"Stack::remove_page: index is invalid."}; auto* page_to_remove = &(this->Layout<Child_t>::get_children()[index]); if (page_to_remove == this->active_page()) active_page_ = nullptr; return this->Layout<Child_t>::remove_child(page_to_remove); } /// Remove and delete all pages. void clear() { // Can't use a range-for loop, Widget::close modifies the child_list_ while (!this->get_children().empty()) this->delete_page(0); } /// Return number of pages in this Stack. // TODO change to page_count() auto size() const -> std::size_t { return this->child_count(); } /// Return a pointer to the current active page, or nullptr if none. auto active_page() const -> Child_t* { return active_page_; } /// Return the index of the current active page. /** Returns Stack::invalid_index if active_page_ is nullptr. */ auto active_page_index() const -> std::size_t { if (active_page_ == nullptr) return Stack::invalid_index; auto const begin = std::cbegin(this->get_children()); auto const end = std::cend(this->get_children()); auto iter = std::find_if( begin, end, [this](auto const& w) { return &w == active_page_; }); return std::distance(begin, iter); } /// Post an Enable_event or Disable_event to the active page. void enable(bool enable = true, bool post_child_polished_event = true) override { this->Widget::enable_and_post_events(enable, post_child_polished_event); for (auto& child : this->get_children()) { if (&child == active_page_) child.enable(enable, post_child_polished_event); else child.disable(); } } /// Used to indicate an error on return values of index type. static auto constexpr invalid_index = static_cast<std::size_t>(-1); protected: auto move_event(Point new_position, Point old_position) -> bool override { this->move_active_page(); return Layout<Child_t>::move_event(new_position, old_position); } auto resize_event(Area new_size, Area old_size) -> bool override { this->resize_active_page(); return Layout<Child_t>::resize_event(new_size, old_size); } void update_geometry() override {} private: Child_t* active_page_ = nullptr; bool sets_focus_ = true; private: void move_active_page() { if (active_page_ != nullptr) System::post_event<Move_event>(*active_page_, this->top_left()); } void resize_active_page() { if (active_page_ != nullptr) System::post_event<Resize_event>(*active_page_, this->outer_area()); } }; } // namespace layout // - - - - - - - - - - - - - - - - Slots - - - - - - - - - - - - - - - - - - - - namespace slot { template <typename Child_t> auto set_active_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t)> { auto slot = sig::Slot<void(std::size_t)>{ [&stack](auto index) { stack.set_active_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto set_active_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void()> { auto slot = sig::Slot<void()>{[&stack, index] { stack.set_active_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto delete_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t)> { auto slot = sig::Slot<void(std::size_t)>{ [&stack](auto index) { stack.delete_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto delete_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void()> { auto slot = sig::Slot<void()>{[&stack, index] { stack.delete_page(index); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto insert_page(layout::Stack<Child_t>& stack) -> sig::Slot<void(std::size_t, std::unique_ptr<Widget>)> { auto slot = sig::Slot<void(std::size_t, std::unique_ptr<Widget>)>{ [&stack](auto index, auto widget) { stack.insert_page(index, std::move(widget)); }}; slot.track(stack.destroyed); return slot; } template <typename Child_t> auto insert_page(layout::Stack<Child_t>& stack, std::size_t index) -> sig::Slot<void(std::unique_ptr<Widget>)> { auto slot = sig::Slot<void(std::unique_ptr<Widget>)>{[&stack, index](auto widget) { stack.insert_page(index, std::move(widget)); }}; slot.track(stack.destroyed); return slot; } } // namespace slot } // namespace cppurses #endif // CPPURSES_WIDGET_LAYOUTS_STACK_HPP
Fix Stack::active_page_index bug
Fix Stack::active_page_index bug
C++
mit
a-n-t-h-o-n-y/CPPurses
8f49d54aa5b18f325a9c267dcb6bb2bada809b1e
include/visionaray/detail/pathtracing.inl
include/visionaray/detail/pathtracing.inl
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_DETAIL_PATHTRACING_INL #define VSNRAY_DETAIL_PATHTRACING_INL 1 #include <visionaray/get_area.h> #include <visionaray/get_surface.h> #include <visionaray/result_record.h> #include <visionaray/sampling.h> #include <visionaray/spectrum.h> #include <visionaray/surface_interaction.h> #include <visionaray/traverse.h> namespace visionaray { namespace pathtracing { template <typename Params> struct kernel { Params params; template <typename Intersector, typename R, typename Generator> VSNRAY_FUNC result_record<typename R::scalar_type> operator()( Intersector& isect, R ray, Generator& gen ) const { using S = typename R::scalar_type; using I = simd::int_type_t<S>; using V = typename result_record<S>::vec_type; using C = spectrum<S>; simd::mask_type_t<S> active_rays = true; simd::mask_type_t<S> last_specular = true; C intensity(0.0); C throughput(1.0); result_record<S> result; result.color = params.bg_color; for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce) { auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect); // Handle rays that just exited auto exited = active_rays & !hit_rec.hit; intensity += select( exited, C(from_rgba(params.ambient_color)) * throughput, C(0.0) ); // Exit if no ray is active anymore active_rays &= hit_rec.hit; if (!any(active_rays)) { break; } // Special handling for first bounce if (bounce == 0) { result.hit = hit_rec.hit; result.isect_pos = ray.ori + ray.dir * hit_rec.t; } // Process the current bounce V refl_dir; V view_dir = -ray.dir; hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t; auto surf = get_surface(hit_rec, params); S brdf_pdf(0.0); // Remember the last type of surface interaction. // If the last interaction was not diffuse, we have // to include light from emissive surfaces. I inter = 0; auto src = surf.sample(view_dir, refl_dir, brdf_pdf, inter, gen); auto zero_pdf = brdf_pdf <= S(0.0); S light_pdf(0.0); auto num_lights = params.lights.end - params.lights.begin; if (num_lights > 0 && any(inter == surface_interaction::Emission)) { auto A = get_area(params.prims.begin, hit_rec); auto ld = length(hit_rec.isect_pos - ray.ori); auto L = normalize(hit_rec.isect_pos - ray.ori); auto n = surf.geometric_normal; auto ldotln = abs(dot(-L, n)); auto solid_angle = (ldotln * A) / (ld * ld); light_pdf = select( inter == surface_interaction::Emission, S(1.0) / solid_angle, S(0.0) ); } S mis_weight = select( bounce > 0 && num_lights > 0 && !last_specular, power_heuristic(brdf_pdf, light_pdf / static_cast<float>(num_lights)), S(1.0) ); intensity += select( active_rays && inter == surface_interaction::Emission, mis_weight * throughput * src, C(0.0) ); active_rays &= inter != surface_interaction::Emission; active_rays &= !zero_pdf; auto n = surf.shading_normal; #if 1 n = faceforward( n, view_dir, surf.geometric_normal ); #endif if (num_lights > 0) { auto ls = sample_random_light(params.lights.begin, params.lights.end, gen); auto ld = select(ls.delta_light, S(1.0), length(ls.pos - hit_rec.isect_pos)); auto L = normalize(ls.pos - hit_rec.isect_pos); auto ln = select(ls.delta_light, -L, ls.normal); #if 1 ln = faceforward( ln, -L, ln ); #endif auto ldotn = dot(L, n); auto ldotln = abs(dot(-L, ln)); R shadow_ray( hit_rec.isect_pos + L * S(params.epsilon), L ); auto lhr = any_hit(shadow_ray, params.prims.begin, params.prims.end, ld - S(2.0f * params.epsilon), isect); auto brdf_pdf = surf.pdf(view_dir, L, inter); auto prob = max_element(throughput.samples()); brdf_pdf *= prob; // TODO: inv_pi / dot(n, wi) factor only valid for plastic and matte auto src = surf.shade(view_dir, L, ls.intensity) * constants::inv_pi<S>() / ldotn; auto solid_angle = (ldotln * ls.area) / (ld * ld); auto light_pdf = S(1.0) / solid_angle; S mis_weight = power_heuristic(light_pdf / static_cast<float>(num_lights), brdf_pdf); intensity += select( active_rays && !lhr.hit && ldotn > S(0.0) && ldotln > S(0.0), mis_weight * throughput * src * (ldotn / light_pdf) * S(static_cast<float>(num_lights)), C(0.0) ); } throughput *= src * (dot(n, refl_dir) / brdf_pdf); throughput = select(zero_pdf, C(0.0), throughput); // Russian roulette auto prob = max_element(throughput.samples()); auto terminate = gen.next() > prob; active_rays &= !terminate; throughput /= prob; if (!any(active_rays)) { break; } ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon); ray.dir = refl_dir; last_specular = inter == surface_interaction::SpecularReflection || inter == surface_interaction::SpecularTransmission; } result.color = select( result.hit, to_rgba(intensity), result.color ); return result; } template <typename R, typename Generator> VSNRAY_FUNC result_record<typename R::scalar_type> operator()( R ray, Generator& gen ) const { default_intersector ignore; return (*this)(ignore, ray, gen); } }; } // pathtracing } // visionaray #endif // VSNRAY_DETAIL_PATHTRACING_INL
// This file is distributed under the MIT license. // See the LICENSE file for details. #pragma once #ifndef VSNRAY_DETAIL_PATHTRACING_INL #define VSNRAY_DETAIL_PATHTRACING_INL 1 #include <visionaray/get_area.h> #include <visionaray/get_surface.h> #include <visionaray/result_record.h> #include <visionaray/sampling.h> #include <visionaray/spectrum.h> #include <visionaray/surface_interaction.h> #include <visionaray/traverse.h> namespace visionaray { namespace pathtracing { template <typename Params> struct kernel { Params params; template <typename Intersector, typename R, typename Generator> VSNRAY_FUNC result_record<typename R::scalar_type> operator()( Intersector& isect, R ray, Generator& gen ) const { using S = typename R::scalar_type; using I = simd::int_type_t<S>; using V = typename result_record<S>::vec_type; using C = spectrum<S>; simd::mask_type_t<S> active_rays = true; simd::mask_type_t<S> last_specular = true; C intensity(0.0); C throughput(1.0); result_record<S> result; result.color = params.bg_color; for (unsigned bounce = 0; bounce < params.num_bounces; ++bounce) { auto hit_rec = closest_hit(ray, params.prims.begin, params.prims.end, isect); // Handle rays that just exited auto exited = active_rays & !hit_rec.hit; intensity += select( exited, C(from_rgba(params.ambient_color)) * throughput, C(0.0) ); // Exit if no ray is active anymore active_rays &= hit_rec.hit; if (!any(active_rays)) { break; } // Special handling for first bounce if (bounce == 0) { result.hit = hit_rec.hit; result.isect_pos = ray.ori + ray.dir * hit_rec.t; } // Process the current bounce V refl_dir; V view_dir = -ray.dir; hit_rec.isect_pos = ray.ori + ray.dir * hit_rec.t; auto surf = get_surface(hit_rec, params); S brdf_pdf(0.0); // Remember the last type of surface interaction. // If the last interaction was not diffuse, we have // to include light from emissive surfaces. I inter = 0; auto src = surf.sample(view_dir, refl_dir, brdf_pdf, inter, gen); auto zero_pdf = brdf_pdf <= S(0.0); S light_pdf(0.0); auto num_lights = params.lights.end - params.lights.begin; if (num_lights > 0 && any(inter == surface_interaction::Emission)) { auto A = get_area(params.prims.begin, hit_rec); auto ld = length(hit_rec.isect_pos - ray.ori); auto L = normalize(hit_rec.isect_pos - ray.ori); auto n = surf.geometric_normal; auto ldotln = abs(dot(-L, n)); auto solid_angle = (ldotln * A) / (ld * ld); light_pdf = select( inter == surface_interaction::Emission, S(1.0) / solid_angle, S(0.0) ); } S mis_weight = select( bounce > 0 && num_lights > 0 && !last_specular, power_heuristic(brdf_pdf, light_pdf / static_cast<float>(num_lights)), S(1.0) ); intensity += select( active_rays && inter == surface_interaction::Emission, mis_weight * throughput * src, C(0.0) ); active_rays &= inter != surface_interaction::Emission; active_rays &= !zero_pdf; auto n = surf.shading_normal; #if 1 n = faceforward( n, view_dir, surf.geometric_normal ); #endif if (num_lights > 0) { auto ls = sample_random_light(params.lights.begin, params.lights.end, gen); auto ld = length(ls.pos - hit_rec.isect_pos); auto L = normalize(ls.pos - hit_rec.isect_pos); auto ln = select(ls.delta_light, -L, ls.normal); #if 1 ln = faceforward( ln, -L, ln ); #endif auto ldotn = dot(L, n); auto ldotln = abs(dot(-L, ln)); R shadow_ray( hit_rec.isect_pos + L * S(params.epsilon), L ); auto lhr = any_hit(shadow_ray, params.prims.begin, params.prims.end, ld - S(2.0f * params.epsilon), isect); auto brdf_pdf = surf.pdf(view_dir, L, inter); auto prob = max_element(throughput.samples()); brdf_pdf *= prob; // TODO: inv_pi / dot(n, wi) factor only valid for plastic and matte auto src = surf.shade(view_dir, L, ls.intensity) * constants::inv_pi<S>() / ldotn; auto solid_angle = (ldotln * ls.area); solid_angle = select(!ls.delta_light, solid_angle / (ld * ld), solid_angle); auto light_pdf = S(1.0) / solid_angle; S mis_weight = power_heuristic(light_pdf / static_cast<float>(num_lights), brdf_pdf); intensity += select( active_rays && !lhr.hit && ldotn > S(0.0) && ldotln > S(0.0), mis_weight * throughput * src * (ldotn / light_pdf) * S(static_cast<float>(num_lights)), C(0.0) ); } throughput *= src * (dot(n, refl_dir) / brdf_pdf); throughput = select(zero_pdf, C(0.0), throughput); // Russian roulette auto prob = max_element(throughput.samples()); auto terminate = gen.next() > prob; active_rays &= !terminate; throughput /= prob; if (!any(active_rays)) { break; } ray.ori = hit_rec.isect_pos + refl_dir * S(params.epsilon); ray.dir = refl_dir; last_specular = inter == surface_interaction::SpecularReflection || inter == surface_interaction::SpecularTransmission; } result.color = select( result.hit, to_rgba(intensity), result.color ); return result; } template <typename R, typename Generator> VSNRAY_FUNC result_record<typename R::scalar_type> operator()( R ray, Generator& gen ) const { default_intersector ignore; return (*this)(ignore, ray, gen); } }; } // pathtracing } // visionaray #endif // VSNRAY_DETAIL_PATHTRACING_INL
Fix #29
Fix #29 Shadow rays always had length 1-2*EPSILON when sampling delta lights
C++
mit
szellmann/visionaray,szellmann/visionaray
10c4ba18c2a897c74284018e16f4ea6f1d645b43
optimizer/tsp_simple.cc
optimizer/tsp_simple.cc
// Copyright © Mapotempo, 2013-2015 // // This file is part of Mapotempo. // // Mapotempo is free software. You can redistribute it and/or // modify since you respect the terms of the GNU Affero General // Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Mapotempo is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the Licenses for more details. // // You should have received a copy of the GNU Affero General Public License // along with Mapotempo. If not, see: // <http://www.gnu.org/licenses/agpl.html> // #include <iostream> #include "base/commandlineflags.h" #include "constraint_solver/routing.h" #include "base/join.h" #include "base/timer.h" #include <base/callback.h> #include "tsptw_data_dt.h" #include "limits.h" #include "constraint_solver/routing.h" #include "constraint_solver/routing_flags.h" DEFINE_int64(time_limit_in_ms, 0, "Time limit in ms, no option means no limit."); DEFINE_int64(no_solution_improvement_limit, -1,"Iterations whitout improvement"); DEFINE_int64(initial_time_out_no_solution_improvement, 30000, "Initial time whitout improvement in ms"); DEFINE_int64(time_out_multiplier, 2, "Multiplier for the nexts time out"); DEFINE_bool(nearby, false, "Short segment priority"); #define DISJUNCTION_COST std::pow(2, 32) #define NO_LATE_MULTIPLIER (DISJUNCTION_COST+1) #define NO_OVERLOAD_MULTIPLIER (DISJUNCTION_COST+1) namespace operations_research { void TWBuilder(const TSPTWDataDT &data, RoutingModel &routing, Solver *solver, int64 begin_index, int64 size) { for (RoutingModel::NodeIndex i(begin_index); i < begin_index + size; ++i) { int64 const first_ready = data.FirstTWReadyTime(i); int64 const first_due = data.FirstTWDueTime(i); int64 const second_ready = data.SecondTWReadyTime(i); int64 const second_due = data.SecondTWDueTime(i); int64 const late_multiplier = data.LateMultiplier(i); std::vector<int64> sticky_vehicle = data.VehicleIndices(i); int64 index = routing.NodeToIndex(i); if (first_ready > -2147483648 || first_due < 2147483647) { IntVar *const cumul_var = routing.CumulVar(index, "time"); if (first_ready > -2147483648) { cumul_var->SetMin(first_ready); } if (late_multiplier > 0) { if (second_ready > -2147483648) { IntVar* const cost_var = solver->MakeSum( solver->MakeConditionalExpression(solver->MakeIsLessOrEqualCstVar(cumul_var, second_ready), solver->MakeSemiContinuousExpr(solver->MakeSum(cumul_var, -first_due), 0, late_multiplier), 0), solver->MakeConditionalExpression(solver->MakeIsGreaterOrEqualCstVar(cumul_var, second_due), solver->MakeSemiContinuousExpr(solver->MakeSum(cumul_var, -second_due), 0, late_multiplier), 0) )->Var(); routing.AddVariableMinimizedByFinalizer(cost_var); } else if (first_due < 2147483647) { routing.SetCumulVarSoftUpperBound(i, "time", first_due, late_multiplier); } } else { if (second_ready > -2147483648) { cumul_var->SetMax(second_due); //Simplify at next ORtools release 09/16 std::vector<int64> forbid_starts(1, first_due); std::vector<int64> forbid_ends(1, second_ready); solver->AddConstraint(solver->MakeNotMemberCt(cumul_var, forbid_starts, forbid_ends)); } else if(first_due < 2147483647) { cumul_var->SetMax(first_due); } } } if(sticky_vehicle.size() > 0) { int v = 0; for(TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { IntVar *const vehicle_var = routing.VehicleVar(v); if(std::find(sticky_vehicle.begin(), sticky_vehicle.end(), v) != sticky_vehicle.end()) { vehicle_var->RemoveValue(index); } ++v; } } std::vector<RoutingModel::NodeIndex> *vect = new std::vector<RoutingModel::NodeIndex>(1); (*vect)[0] = i; routing.AddDisjunction(*vect, DISJUNCTION_COST); } } void TSPTWSolver(const TSPTWDataDT &data) { const int size_vehicles = data.Vehicles().size(); const int size = data.Size(); const int size_matrix = data.SizeMatrix(); const int size_rest = data.SizeRest(); std::vector<std::pair<RoutingModel::NodeIndex, RoutingModel::NodeIndex>> *start_ends = new std::vector<std::pair<RoutingModel::NodeIndex, RoutingModel::NodeIndex>>(size_vehicles); for(int v = 0; v < size_vehicles; ++v) { (*start_ends)[v] = std::make_pair(data.Vehicles().at(v)->start, data.Vehicles().at(v)->stop); } RoutingModel routing(size, size_vehicles, *start_ends); // Dimensions const int64 horizon = data.Horizon(); std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> time_evaluators; std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> distance_evaluators; std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> order_evaluators; for (TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { time_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::TimePlusServiceTime)); distance_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::Distance)); if (FLAGS_nearby) { order_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::TimeOrder)); } } routing.AddDimensionWithVehicleTransits(time_evaluators, horizon, horizon, false, "time"); routing.GetMutableDimension("time")->SetSpanCostCoefficientForAllVehicles(5); routing.AddDimensionWithVehicleTransits(distance_evaluators, 0, LLONG_MAX, true, "distance"); if (FLAGS_nearby) { routing.AddDimensionWithVehicleTransits(order_evaluators, horizon, horizon, true, "order"); routing.GetMutableDimension("order")->SetSpanCostCoefficientForAllVehicles(1); } for (int64 i = 0; i < data.Vehicles().at(0)->capacity.size(); ++i) { routing.AddDimension(NewPermanentCallback(&data, &TSPTWDataDT::Quantity, NewPermanentCallback(&routing, &RoutingModel::NodeToIndex), i), 0, LLONG_MAX, true, "quantity" + std::to_string(i)); } Solver *solver = routing.solver(); // Setting visit time windows TWBuilder(data, routing, solver, 0, size_matrix - 2); // Setting rest time windows TWBuilder(data, routing, solver, size_matrix, size_rest); // Vehicle time windows int64 v = 0; for(TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { if (vehicle->time_start > -2147483648) { int64 index = routing.Start(v); IntVar *const cumul_var = routing.CumulVar(index, "time"); cumul_var->SetMin(vehicle->time_start); } if (vehicle->time_end < 2147483647) { int64 coef = vehicle->late_multiplier; if(coef > 0) { routing.GetMutableDimension("time")->SetEndCumulVarSoftUpperBound(v, vehicle->time_end, coef); } else { int64 index = routing.End(v); IntVar *const cumul_var = routing.CumulVar(index, "time"); cumul_var->SetMax(vehicle->time_end); } } for (int64 i = 0; i < vehicle->capacity.size(); ++i) { int64 coef = vehicle->overload_multiplier[i]; if(vehicle->capacity[i] >= 0) { if(coef > 0) { routing.GetMutableDimension("quantity" + std::to_string(i))->SetEndCumulVarSoftUpperBound(v, vehicle->capacity[i], coef); } else { int64 index = routing.End(v); IntVar *const cumul_var = routing.CumulVar(index, "quantity" + std::to_string(i)); cumul_var->SetMax(vehicle->capacity[i]); } } } ++v; } RoutingSearchParameters parameters = BuildSearchParametersFromFlags(); // Search strategy // parameters.set_first_solution_strategy(FirstSolutionStrategy::FIRST_UNBOUND_MIN_VALUE); // Default // parameters.set_first_solution_strategy(FirstSolutionStrategy::PATH_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::PATH_MOST_CONSTRAINED_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::CHRISTOFIDES); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ALL_UNPERFORMED); // parameters.set_first_solution_strategy(FirstSolutionStrategy::BEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ROUTING_BEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::PARALLEL_CHEAPEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::LOCAL_CHEAPEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::GLOBAL_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::LOCAL_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ROUTING_BEST_INSERTION); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_GREEDY_DESCENT); parameters.set_local_search_metaheuristic(LocalSearchMetaheuristic::GUIDED_LOCAL_SEARCH); // parameters.set_guided_local_search_lambda_coefficient(0.5); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_SIMULATED_ANNEALING); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_TABU_SEARCH); // routing.SetCommandLineOption("routing_no_lns", "true"); if (FLAGS_time_limit_in_ms > 0) { parameters.set_time_limit_ms(FLAGS_time_limit_in_ms); } routing.CloseModelWithParameters(parameters); LoggerMonitor * const logger = MakeLoggerMonitor(routing.solver(), routing.CostVar(), true); routing.AddSearchMonitor(logger); if (data.Size() > 3) { if (FLAGS_no_solution_improvement_limit > 0) { NoImprovementLimit * const no_improvement_limit = MakeNoImprovementLimit(routing.solver(), routing.CostVar(), FLAGS_no_solution_improvement_limit, FLAGS_initial_time_out_no_solution_improvement, FLAGS_time_out_multiplier, true); routing.AddSearchMonitor(no_improvement_limit); } } else { SearchLimit * const limit = solver->MakeLimit(kint64max,kint64max,kint64max,1); routing.AddSearchMonitor(limit); } const Assignment *solution = routing.SolveWithParameters(parameters); if (solution != NULL) { float cost = solution->ObjectiveValue() / 500.0; // Back to original cost value after GetMutableDimension("time")->SetSpanCostCoefficientForAllVehicles(5) logger->GetFinalLog(); for (int route_nbr = 0; route_nbr < routing.vehicles(); route_nbr++) { for (int64 index = routing.Start(route_nbr); !routing.IsEnd(index); index = solution->Value(routing.NextVar(index))) { RoutingModel::NodeIndex nodeIndex = routing.IndexToNode(index); std::cout << nodeIndex << ","; } std::cout << routing.IndexToNode(routing.End(route_nbr)) << ";"; } std::cout << std::endl; } else { std::cout << "No solution found..." << std::endl; } } } // namespace operations_research int main(int argc, char **argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); if(FLAGS_time_limit_in_ms > 0 || FLAGS_no_solution_improvement_limit > 0) { operations_research::TSPTWDataDT tsptw_data(FLAGS_instance_file); operations_research::TSPTWSolver(tsptw_data); } else { std::cout << "No Stop condition" << std::endl; } return 0; }
// Copyright © Mapotempo, 2013-2015 // // This file is part of Mapotempo. // // Mapotempo is free software. You can redistribute it and/or // modify since you respect the terms of the GNU Affero General // Public License as published by the Free Software Foundation, // either version 3 of the License, or (at your option) any later version. // // Mapotempo is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY // or FITNESS FOR A PARTICULAR PURPOSE. See the Licenses for more details. // // You should have received a copy of the GNU Affero General Public License // along with Mapotempo. If not, see: // <http://www.gnu.org/licenses/agpl.html> // #include <iostream> #include "base/commandlineflags.h" #include "constraint_solver/routing.h" #include "base/join.h" #include "base/timer.h" #include <base/callback.h> #include "tsptw_data_dt.h" #include "limits.h" #include "constraint_solver/routing.h" #include "constraint_solver/routing_flags.h" DEFINE_int64(time_limit_in_ms, 0, "Time limit in ms, no option means no limit."); DEFINE_int64(no_solution_improvement_limit, -1,"Iterations whitout improvement"); DEFINE_int64(initial_time_out_no_solution_improvement, 30000, "Initial time whitout improvement in ms"); DEFINE_int64(time_out_multiplier, 2, "Multiplier for the nexts time out"); DEFINE_bool(nearby, false, "Short segment priority"); #define DISJUNCTION_COST std::pow(2, 56) namespace operations_research { void TWBuilder(const TSPTWDataDT &data, RoutingModel &routing, Solver *solver, int64 begin_index, int64 size) { for (RoutingModel::NodeIndex i(begin_index); i < begin_index + size; ++i) { int64 const first_ready = data.FirstTWReadyTime(i); int64 const first_due = data.FirstTWDueTime(i); int64 const second_ready = data.SecondTWReadyTime(i); int64 const second_due = data.SecondTWDueTime(i); int64 const late_multiplier = data.LateMultiplier(i); std::vector<int64> sticky_vehicle = data.VehicleIndices(i); int64 index = routing.NodeToIndex(i); if (first_ready > -2147483648 || first_due < 2147483647) { IntVar *const cumul_var = routing.CumulVar(index, "time"); if (first_ready > -2147483648) { cumul_var->SetMin(first_ready); } if (late_multiplier > 0) { if (second_ready > -2147483648) { IntVar* const cost_var = solver->MakeSum( solver->MakeConditionalExpression(solver->MakeIsLessOrEqualCstVar(cumul_var, second_ready), solver->MakeSemiContinuousExpr(solver->MakeSum(cumul_var, -first_due), 0, late_multiplier), 0), solver->MakeConditionalExpression(solver->MakeIsGreaterOrEqualCstVar(cumul_var, second_due), solver->MakeSemiContinuousExpr(solver->MakeSum(cumul_var, -second_due), 0, late_multiplier), 0) )->Var(); routing.AddVariableMinimizedByFinalizer(cost_var); } else if (first_due < 2147483647) { routing.SetCumulVarSoftUpperBound(i, "time", first_due, late_multiplier); } } else { if (second_ready > -2147483648) { cumul_var->SetMax(second_due); //Simplify at next ORtools release 09/16 std::vector<int64> forbid_starts(1, first_due); std::vector<int64> forbid_ends(1, second_ready); solver->AddConstraint(solver->MakeNotMemberCt(cumul_var, forbid_starts, forbid_ends)); } else if(first_due < 2147483647) { cumul_var->SetMax(first_due); } } } if(sticky_vehicle.size() > 0) { int v = 0; for(TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { IntVar *const vehicle_var = routing.VehicleVar(v); if(std::find(sticky_vehicle.begin(), sticky_vehicle.end(), v) != sticky_vehicle.end()) { vehicle_var->RemoveValue(index); } ++v; } } std::vector<RoutingModel::NodeIndex> *vect = new std::vector<RoutingModel::NodeIndex>(1); (*vect)[0] = i; routing.AddDisjunction(*vect, DISJUNCTION_COST); } } void TSPTWSolver(const TSPTWDataDT &data) { const int size_vehicles = data.Vehicles().size(); const int size = data.Size(); const int size_matrix = data.SizeMatrix(); const int size_rest = data.SizeRest(); std::vector<std::pair<RoutingModel::NodeIndex, RoutingModel::NodeIndex>> *start_ends = new std::vector<std::pair<RoutingModel::NodeIndex, RoutingModel::NodeIndex>>(size_vehicles); for(int v = 0; v < size_vehicles; ++v) { (*start_ends)[v] = std::make_pair(data.Vehicles().at(v)->start, data.Vehicles().at(v)->stop); } RoutingModel routing(size, size_vehicles, *start_ends); // Dimensions const int64 horizon = data.Horizon(); std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> time_evaluators; std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> distance_evaluators; std::vector<ResultCallback2<long long int, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int>, IntType<operations_research::_RoutingModel_NodeIndex_tag_, int> >*> order_evaluators; for (TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { time_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::TimePlusServiceTime)); distance_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::Distance)); if (FLAGS_nearby) { order_evaluators.push_back(NewPermanentCallback(vehicle, &TSPTWDataDT::Vehicle::TimeOrder)); } } routing.AddDimensionWithVehicleTransits(time_evaluators, horizon, horizon, false, "time"); routing.GetMutableDimension("time")->SetSpanCostCoefficientForAllVehicles(5); routing.AddDimensionWithVehicleTransits(distance_evaluators, 0, LLONG_MAX, true, "distance"); if (FLAGS_nearby) { routing.AddDimensionWithVehicleTransits(order_evaluators, horizon, horizon, true, "order"); routing.GetMutableDimension("order")->SetSpanCostCoefficientForAllVehicles(1); } for (int64 i = 0; i < data.Vehicles().at(0)->capacity.size(); ++i) { routing.AddDimension(NewPermanentCallback(&data, &TSPTWDataDT::Quantity, NewPermanentCallback(&routing, &RoutingModel::NodeToIndex), i), 0, LLONG_MAX, true, "quantity" + std::to_string(i)); } Solver *solver = routing.solver(); // Setting visit time windows TWBuilder(data, routing, solver, 0, size_matrix - 2); // Setting rest time windows TWBuilder(data, routing, solver, size_matrix, size_rest); // Vehicle time windows int64 v = 0; for(TSPTWDataDT::Vehicle* vehicle: data.Vehicles()) { if (vehicle->time_start > -2147483648) { int64 index = routing.Start(v); IntVar *const cumul_var = routing.CumulVar(index, "time"); cumul_var->SetMin(vehicle->time_start); } if (vehicle->time_end < 2147483647) { int64 coef = vehicle->late_multiplier; if(coef > 0) { routing.GetMutableDimension("time")->SetEndCumulVarSoftUpperBound(v, vehicle->time_end, coef); } else { int64 index = routing.End(v); IntVar *const cumul_var = routing.CumulVar(index, "time"); cumul_var->SetMax(vehicle->time_end); } } for (int64 i = 0; i < vehicle->capacity.size(); ++i) { int64 coef = vehicle->overload_multiplier[i]; if(vehicle->capacity[i] >= 0) { if(coef > 0) { routing.GetMutableDimension("quantity" + std::to_string(i))->SetEndCumulVarSoftUpperBound(v, vehicle->capacity[i], coef); } else { int64 index = routing.End(v); IntVar *const cumul_var = routing.CumulVar(index, "quantity" + std::to_string(i)); cumul_var->SetMax(vehicle->capacity[i]); } } } ++v; } RoutingSearchParameters parameters = BuildSearchParametersFromFlags(); // Search strategy // parameters.set_first_solution_strategy(FirstSolutionStrategy::FIRST_UNBOUND_MIN_VALUE); // Default // parameters.set_first_solution_strategy(FirstSolutionStrategy::PATH_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::PATH_MOST_CONSTRAINED_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::CHRISTOFIDES); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ALL_UNPERFORMED); // parameters.set_first_solution_strategy(FirstSolutionStrategy::BEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ROUTING_BEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::PARALLEL_CHEAPEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::LOCAL_CHEAPEST_INSERTION); // parameters.set_first_solution_strategy(FirstSolutionStrategy::GLOBAL_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::LOCAL_CHEAPEST_ARC); // parameters.set_first_solution_strategy(FirstSolutionStrategy::ROUTING_BEST_INSERTION); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_GREEDY_DESCENT); parameters.set_local_search_metaheuristic(LocalSearchMetaheuristic::GUIDED_LOCAL_SEARCH); // parameters.set_guided_local_search_lambda_coefficient(0.5); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_SIMULATED_ANNEALING); // parameters.set_metaheuristic(LocalSearchMetaheuristic::ROUTING_TABU_SEARCH); // routing.SetCommandLineOption("routing_no_lns", "true"); if (FLAGS_time_limit_in_ms > 0) { parameters.set_time_limit_ms(FLAGS_time_limit_in_ms); } routing.CloseModelWithParameters(parameters); LoggerMonitor * const logger = MakeLoggerMonitor(routing.solver(), routing.CostVar(), true); routing.AddSearchMonitor(logger); if (data.Size() > 3) { if (FLAGS_no_solution_improvement_limit > 0) { NoImprovementLimit * const no_improvement_limit = MakeNoImprovementLimit(routing.solver(), routing.CostVar(), FLAGS_no_solution_improvement_limit, FLAGS_initial_time_out_no_solution_improvement, FLAGS_time_out_multiplier, true); routing.AddSearchMonitor(no_improvement_limit); } } else { SearchLimit * const limit = solver->MakeLimit(kint64max,kint64max,kint64max,1); routing.AddSearchMonitor(limit); } const Assignment *solution = routing.SolveWithParameters(parameters); if (solution != NULL) { float cost = solution->ObjectiveValue() / 500.0; // Back to original cost value after GetMutableDimension("time")->SetSpanCostCoefficientForAllVehicles(5) logger->GetFinalLog(); for (int route_nbr = 0; route_nbr < routing.vehicles(); route_nbr++) { for (int64 index = routing.Start(route_nbr); !routing.IsEnd(index); index = solution->Value(routing.NextVar(index))) { RoutingModel::NodeIndex nodeIndex = routing.IndexToNode(index); std::cout << nodeIndex << ","; } std::cout << routing.IndexToNode(routing.End(route_nbr)) << ";"; } std::cout << std::endl; } else { std::cout << "No solution found..." << std::endl; } } } // namespace operations_research int main(int argc, char **argv) { gflags::ParseCommandLineFlags(&argc, &argv, true); if(FLAGS_time_limit_in_ms > 0 || FLAGS_no_solution_improvement_limit > 0) { operations_research::TSPTWDataDT tsptw_data(FLAGS_instance_file); operations_research::TSPTWSolver(tsptw_data); } else { std::cout << "No Stop condition" << std::endl; } return 0; }
Fix disjunction cost
Fix disjunction cost
C++
agpl-3.0
Mapotempo/optimizer-ortools,Mapotempo/mapotempo-optimizer,Mapotempo/mapotempo-optimizer,braktar/mapotempo-optimizer,Mapotempo/optimizer-ortools,braktar/mapotempo-optimizer,Mapotempo/optimizer-ortools
a83b64357446f601833fda6d2b59315f3fd3602a
include/bitcoin/bitcoin/impl/math/checksum.ipp
include/bitcoin/bitcoin/impl/math/checksum.ipp
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_CHECKSUM_IPP #define LIBBITCOIN_CHECKSUM_IPP #include <algorithm> #include <cstddef> #include <initializer_list> #include <bitcoin/bitcoin/utility/assert.hpp> #include <bitcoin/bitcoin/utility/data.hpp> namespace libbitcoin { template <size_t Size> bool build_checked_array(byte_array<Size>& out, std::initializer_list<data_slice> slices) { return build_array(out, slices) && insert_checksum(out); } template<size_t Size> bool insert_checksum(byte_array<Size>& out) { BITCOIN_ASSERT(out.size() < checksum_size); data_chunk body(out.begin(), out.end() - checksum_size); const auto checksum = to_little_endian(bitcoin_checksum(body)); std::copy(checksum.begin(), checksum.end(), out.end() - checksum_size); return true; } } // namespace libbitcoin #endif
/** * Copyright (c) 2011-2015 libbitcoin developers (see AUTHORS) * * This file is part of libbitcoin. * * libbitcoin is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License with * additional permissions to the one published by the Free Software * Foundation, either version 3 of the License, or (at your option) * any later version. For more information see LICENSE. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #ifndef LIBBITCOIN_CHECKSUM_IPP #define LIBBITCOIN_CHECKSUM_IPP #include <algorithm> #include <cstddef> #include <initializer_list> #include <bitcoin/bitcoin/utility/assert.hpp> #include <bitcoin/bitcoin/utility/data.hpp> #include <bitcoin/bitcoin/utility/endian.hpp> namespace libbitcoin { template <size_t Size> bool build_checked_array(byte_array<Size>& out, std::initializer_list<data_slice> slices) { return build_array(out, slices) && insert_checksum(out); } template<size_t Size> bool insert_checksum(byte_array<Size>& out) { BITCOIN_ASSERT(out.size() < checksum_size); data_chunk body(out.begin(), out.end() - checksum_size); const auto checksum = to_little_endian(bitcoin_checksum(body)); std::copy(checksum.begin(), checksum.end(), out.end() - checksum_size); return true; } } // namespace libbitcoin #endif
Add missing include.
Add missing include.
C++
agpl-3.0
swansontec/libbitcoin,swansontec/libbitcoin,swansontec/libbitcoin,swansontec/libbitcoin
8a86b8788dad6f538a6f3299ca09457482b87dfa
Code/Wrappers/QtWidget/otbWrapperQtWidgetStringListParameter.cxx
Code/Wrappers/QtWidget/otbWrapperQtWidgetStringListParameter.cxx
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetStringListParameter.h" namespace otb { namespace Wrapper { QtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m) : QtWidgetParameterBase(param, m), m_StringListParam(param) { connect( this, SIGNAL(Change()), GetModel(), SLOT(NotifyUpdate()) ); } QtWidgetStringListParameter::~QtWidgetStringListParameter() { } void QtWidgetStringListParameter::DoUpdateGUI() { } void QtWidgetStringListParameter::DoCreateWidget() { m_LineEditList.clear(); const unsigned int sp(2); const unsigned int buttonSize(30); // Global layout QHBoxLayout * hLayout = new QHBoxLayout; hLayout->setSpacing(sp); hLayout->setContentsMargins(sp, sp, sp, sp); // Button layout QVBoxLayout * buttonLayout = new QVBoxLayout; buttonLayout->setSpacing(sp); buttonLayout->setContentsMargins(sp, sp, sp, sp); QHBoxLayout * addSupLayout = new QHBoxLayout; addSupLayout->setSpacing(sp); addSupLayout->setContentsMargins(sp, sp, sp, sp); QHBoxLayout * upDownLayout = new QHBoxLayout; upDownLayout->setSpacing(sp); upDownLayout->setContentsMargins(sp, sp, sp, sp); // Add file button QPushButton * addButton = new QPushButton; addButton->setText("+"); addButton->setFixedWidth(buttonSize); addButton->setToolTip("Add a string selector..."); connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) ); addSupLayout->addWidget(addButton); // Supress file button QPushButton * supButton = new QPushButton; supButton->setText("-"); supButton->setFixedWidth(buttonSize); supButton->setToolTip("Supress the selected string..."); connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) ); addSupLayout->addWidget(supButton); buttonLayout->addLayout(addSupLayout); // Up file edit QPushButton * upButton = new QPushButton; upButton->setText("Up"); upButton->setFixedWidth(buttonSize); upButton->setToolTip("Up the selected string in the list..."); connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) ); upDownLayout->addWidget(upButton); // Down file edit QPushButton * downButton = new QPushButton; downButton->setText("Down"); downButton->setFixedWidth(buttonSize); downButton->setToolTip("Down the selected string in the list..."); connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) ); upDownLayout->addWidget(downButton); buttonLayout->addLayout(upDownLayout); // Erase file edit QPushButton * eraseButton = new QPushButton; eraseButton->setText("Erase"); eraseButton->setFixedWidth(2*(buttonSize+sp)); eraseButton->setToolTip("Erase the selected string of the list..."); connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) ); buttonLayout->addWidget(eraseButton); QVBoxLayout * fileLayout = new QVBoxLayout(); fileLayout->setSpacing(0); //QtFileSelectionWidget * fileSelection = new QtFileSelectionWidget(); /*fileSelection->setFixedHeight(30); fileLayout->addWidget( fileSelection ); m_StringListParam->AddNullElement(); connect( fileSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) ); m_LineEditList.push_back(fileSelection); */ QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(fileLayout); QScrollArea * scroll = new QScrollArea(); scroll->setWidget(mainGroup); scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); scroll->setWidgetResizable(true); hLayout->addWidget(scroll); hLayout->addLayout(buttonLayout); this->setLayout(hLayout); //m_StringLayout = fileLayout; m_HLayout = hLayout; m_Scroll = scroll; } void QtWidgetStringListParameter::UpdateStringList() { // save value for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ ) { m_StringListParam->SetNthElement(j, m_LineEditList[j]->GetStringName()); } emit Change(); } void QtWidgetStringListParameter::UpString() { if(m_LineEditList.size() < 2 ) return; m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(2); // Map link between old and new index in the list std::map<unsigned int, unsigned int> idMap; // Init map for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { idMap[i] = i; } // If the first item is checked, uncheck it... // It won't be moved if( m_LineEditList[0]->IsChecked() ) { m_LineEditList[0]->SetChecked(false); } // If other item are checked, up the index // Starts at 1 because the first item mustn't move for(unsigned int i=1; i<m_LineEditList.size(); i++ ) { if( m_LineEditList[i]->IsChecked() ) { unsigned int tmp = idMap[i]; idMap[i] = i-1; idMap[idMap[i-1]] = tmp; } } this->UpdateStringList( idMap ); this->RecreateStringList(); } void QtWidgetStringListParameter::DownString() { if(m_LineEditList.size() < 2 ) return; m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); // Map link between old and new index in the list std::map<unsigned int, unsigned int> idMap; // Init map for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { idMap[i] = i; } // If the last item is checked, uncheck it... // It won't be moved if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() ) { m_LineEditList[m_LineEditList.size()-1]->SetChecked(false); } // If other item are checked, up the index // Stops at size-1 because the last item mustn't move for(int i=m_LineEditList.size()-2; i>=0; i-- ) { if( m_LineEditList[i]->IsChecked() ) { unsigned int tmp = idMap[i]; idMap[i] = i+1; idMap[idMap[i+1]] = tmp; } } this->UpdateStringList( idMap ); this->RecreateStringList(); } void QtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap ) { std::vector<QtStringSelectionWidget *> tmpList; // Keys become values and inverse std::map<unsigned int, unsigned int> idMapBis; for(unsigned int i=0; i<idMap.size(); i++ ) { idMapBis[ idMap[i] ] = i; } // Create the new item list for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] ); tmpList.push_back(m_LineEditList[ idMapBis[i] ]); } m_LineEditList = tmpList; QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); // notify of value change QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } void QtWidgetStringListParameter::SetString(const QString& value) { m_StringListParam->AddString(value.toStdString()); m_StringListParam->SetUserValue(true); QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } void QtWidgetStringListParameter::AddString() { m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { m_StringLayout->addWidget( m_LineEditList[i] ); } QtStringSelectionWidget * stringInput = new QtStringSelectionWidget(); stringInput->setFixedHeight( 30 ); m_StringLayout->addWidget( stringInput ); m_LineEditList.push_back(stringInput); m_StringListParam->AddNullElement(); connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList())); connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) ); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); } void QtWidgetStringListParameter::SupressString() { m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); std::vector<QtStringSelectionWidget *> tmpList; for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { if( !m_LineEditList[i]->IsChecked() ) { m_StringLayout->addWidget( m_LineEditList[i] ); tmpList.push_back(m_LineEditList[i]); } } m_LineEditList = tmpList; QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); this->RecreateStringList(); } void QtWidgetStringListParameter::EraseString() { m_LineEditList.clear(); m_StringLayout = new QVBoxLayout(); QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget(); stringSelection->setFixedHeight( 30 ); m_StringLayout->addWidget( stringSelection ); m_LineEditList.push_back(stringSelection); m_StringListParam->AddNullElement(); connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) ); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); this->RecreateStringList(); } void QtWidgetStringListParameter::RecreateStringList() { // save value m_StringListParam->ClearValue(); if( m_LineEditList.size() == 0) { // this->AddString(); } else { for(unsigned int j=0; j<m_LineEditList.size(); j++ ) { m_StringListParam->AddString(m_LineEditList[j]->GetStringName()); //connect( m_LineEditList[j]->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) ); } emit Change(); // notify of value change QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } } } }
/*========================================================================= Program: ORFEO Toolbox Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Centre National d'Etudes Spatiales. All rights reserved. See OTBCopyright.txt for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "otbWrapperQtWidgetStringListParameter.h" namespace otb { namespace Wrapper { QtWidgetStringListParameter::QtWidgetStringListParameter(StringListParameter* param, QtWidgetModel* m) : QtWidgetParameterBase(param, m), m_StringListParam(param) { connect( this, SIGNAL(Change()), GetModel(), SLOT(NotifyUpdate()) ); } QtWidgetStringListParameter::~QtWidgetStringListParameter() { } void QtWidgetStringListParameter::DoUpdateGUI() { m_LineEditList.clear(); m_StringLayout = new QVBoxLayout(); for(unsigned int i=0; i<m_StringListParam->GetValue().size(); i++) { QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget(); stringSelection->setFixedHeight( 30 ); QString val(m_StringListParam->GetNthElement(i).c_str()); stringSelection->GetInput()->setText( m_StringListParam->GetNthElement(i).c_str() );//val ); m_StringLayout->addWidget( stringSelection ); m_LineEditList.push_back(stringSelection); connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) ); connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) ); } QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); } void QtWidgetStringListParameter::DoCreateWidget() { m_LineEditList.clear(); const unsigned int sp(2); const unsigned int buttonSize(30); // Global layout QHBoxLayout * hLayout = new QHBoxLayout; hLayout->setSpacing(sp); hLayout->setContentsMargins(sp, sp, sp, sp); if( m_StringListParam->GetRole() != Role_Output ) { // Button layout QVBoxLayout * buttonLayout = new QVBoxLayout; buttonLayout->setSpacing(sp); buttonLayout->setContentsMargins(sp, sp, sp, sp); QHBoxLayout * addSupLayout = new QHBoxLayout; addSupLayout->setSpacing(sp); addSupLayout->setContentsMargins(sp, sp, sp, sp); QHBoxLayout * upDownLayout = new QHBoxLayout; upDownLayout->setSpacing(sp); upDownLayout->setContentsMargins(sp, sp, sp, sp); // Add file button QPushButton * addButton = new QPushButton; addButton->setText("+"); addButton->setFixedWidth(buttonSize); addButton->setToolTip("Add a string selector..."); connect( addButton, SIGNAL(clicked()), this, SLOT(AddString()) ); addSupLayout->addWidget(addButton); // Supress file button QPushButton * supButton = new QPushButton; supButton->setText("-"); supButton->setFixedWidth(buttonSize); supButton->setToolTip("Supress the selected string..."); connect( supButton, SIGNAL(clicked()), this, SLOT(SupressString()) ); addSupLayout->addWidget(supButton); buttonLayout->addLayout(addSupLayout); // Up file edit QPushButton * upButton = new QPushButton; upButton->setText("Up"); upButton->setFixedWidth(buttonSize); upButton->setToolTip("Up the selected string in the list..."); connect( upButton, SIGNAL(clicked()), this, SLOT(UpString()) ); upDownLayout->addWidget(upButton); // Down file edit QPushButton * downButton = new QPushButton; downButton->setText("Down"); downButton->setFixedWidth(buttonSize); downButton->setToolTip("Down the selected string in the list..."); connect( downButton, SIGNAL(clicked()), this, SLOT(DownString()) ); upDownLayout->addWidget(downButton); buttonLayout->addLayout(upDownLayout); // Erase file edit QPushButton * eraseButton = new QPushButton; eraseButton->setText("Erase"); eraseButton->setFixedWidth(2*(buttonSize+sp)); eraseButton->setToolTip("Erase the selected string of the list..."); connect( eraseButton, SIGNAL(clicked()), this, SLOT(EraseString()) ); buttonLayout->addWidget(eraseButton); hLayout->addLayout(buttonLayout); } QVBoxLayout * fileLayout = new QVBoxLayout(); fileLayout->setSpacing(0); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(fileLayout); QScrollArea * scroll = new QScrollArea(); scroll->setWidget(mainGroup); scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn); scroll->setWidgetResizable(true); hLayout->addWidget(scroll); connect( GetModel(), SIGNAL(UpdateGui()), this, SLOT(UpdateGUI() ) ); this->setLayout(hLayout); //m_StringLayout = fileLayout; m_HLayout = hLayout; m_Scroll = scroll; } void QtWidgetStringListParameter::UpdateStringList() { // save value for(unsigned int j=0; j<m_StringListParam->GetValue().size(); j++ ) { m_StringListParam->SetNthElement(j, m_LineEditList[j]->GetStringName()); } emit Change(); } void QtWidgetStringListParameter::UpString() { if(m_LineEditList.size() < 2 ) return; m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(2); // Map link between old and new index in the list std::map<unsigned int, unsigned int> idMap; // Init map for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { idMap[i] = i; } // If the first item is checked, uncheck it... // It won't be moved if( m_LineEditList[0]->IsChecked() ) { m_LineEditList[0]->SetChecked(false); } // If other item are checked, up the index // Starts at 1 because the first item mustn't move for(unsigned int i=1; i<m_LineEditList.size(); i++ ) { if( m_LineEditList[i]->IsChecked() ) { unsigned int tmp = idMap[i]; idMap[i] = i-1; idMap[idMap[i-1]] = tmp; } } this->UpdateStringList( idMap ); this->RecreateStringList(); } void QtWidgetStringListParameter::DownString() { if(m_LineEditList.size() < 2 ) return; m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); // Map link between old and new index in the list std::map<unsigned int, unsigned int> idMap; // Init map for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { idMap[i] = i; } // If the last item is checked, uncheck it... // It won't be moved if( m_LineEditList[m_LineEditList.size()-1]->IsChecked() ) { m_LineEditList[m_LineEditList.size()-1]->SetChecked(false); } // If other item are checked, up the index // Stops at size-1 because the last item mustn't move for(int i=m_LineEditList.size()-2; i>=0; i-- ) { if( m_LineEditList[i]->IsChecked() ) { unsigned int tmp = idMap[i]; idMap[i] = i+1; idMap[idMap[i+1]] = tmp; } } this->UpdateStringList( idMap ); this->RecreateStringList(); } void QtWidgetStringListParameter::UpdateStringList( std::map<unsigned int, unsigned int> idMap ) { std::vector<QtStringSelectionWidget *> tmpList; // Keys become values and inverse std::map<unsigned int, unsigned int> idMapBis; for(unsigned int i=0; i<idMap.size(); i++ ) { idMapBis[ idMap[i] ] = i; } // Create the new item list for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { m_StringLayout->addWidget( m_LineEditList[ idMapBis[i] ] ); tmpList.push_back(m_LineEditList[ idMapBis[i] ]); } m_LineEditList = tmpList; QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); // notify of value change QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } void QtWidgetStringListParameter::SetString(const QString& value) { m_StringListParam->AddString(value.toStdString()); m_StringListParam->SetUserValue(true); QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } void QtWidgetStringListParameter::AddString() { m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { m_StringLayout->addWidget( m_LineEditList[i] ); } QtStringSelectionWidget * stringInput = new QtStringSelectionWidget(); stringInput->setFixedHeight( 30 ); m_StringLayout->addWidget( stringInput ); m_LineEditList.push_back(stringInput); m_StringListParam->AddNullElement(); connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList())); connect( stringInput->GetInput(), SIGNAL(textChanged(const QString&)), GetModel(), SLOT(NotifyUpdate()) ); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); } void QtWidgetStringListParameter::SupressString() { m_StringLayout = new QVBoxLayout(); m_StringLayout->setSpacing(0); std::vector<QtStringSelectionWidget *> tmpList; for(unsigned int i=0; i<m_LineEditList.size(); i++ ) { if( !m_LineEditList[i]->IsChecked() ) { m_StringLayout->addWidget( m_LineEditList[i] ); tmpList.push_back(m_LineEditList[i]); } } m_LineEditList = tmpList; QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); this->RecreateStringList(); } void QtWidgetStringListParameter::EraseString() { m_LineEditList.clear(); m_StringLayout = new QVBoxLayout(); QtStringSelectionWidget * stringSelection = new QtStringSelectionWidget(); stringSelection->setFixedHeight( 30 ); m_StringLayout->addWidget( stringSelection ); m_LineEditList.push_back(stringSelection); m_StringListParam->AddNullElement(); connect( stringSelection->GetInput(), SIGNAL(textChanged(const QString&)), this, SLOT(UpdateStringList()) ); QGroupBox *mainGroup = new QGroupBox(); mainGroup->setLayout(m_StringLayout); m_Scroll->setWidget(mainGroup); this->update(); this->RecreateStringList(); } void QtWidgetStringListParameter::RecreateStringList() { // save value m_StringListParam->ClearValue(); if( m_LineEditList.size() != 0) { for(unsigned int j=0; j<m_LineEditList.size(); j++ ) { m_StringListParam->AddString(m_LineEditList[j]->GetStringName()); } emit Change(); // notify of value change QString key( QString::fromStdString(m_StringListParam->GetKey()) ); emit ParameterChanged(key); } } } }
implement DoUpdateGui for Role_Output case in StringListWidget
ENH: implement DoUpdateGui for Role_Output case in StringListWidget
C++
apache-2.0
orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB,orfeotoolbox/OTB
a0b56ec12c2ea6264d7474130b768ad099a7a4b5
calculate.cpp
calculate.cpp
#include <iostream> #include <string> #include <sstream> #include <vector> #include <stack> #include <map> #include <utility> #include <algorithm> #include <numeric> #include <cmath> #include <functional> #include <stdexcept> using namespace std; struct oper_t { bool right; int prec; bool unary; }; typedef pair<bool, double> return_t; typedef vector<double> args_t; typedef function<return_t(args_t)> func_t; typedef pair<string, int> token_t; typedef vector<token_t> postfix_t; class parse_error : public runtime_error { public: parse_error(const string &what_arg, unsigned int i_arg) : runtime_error(what_arg), i(i_arg) { } unsigned int index() const { return i; } protected: unsigned int i; }; multimap<string, oper_t> opers; multimap<string, func_t> funcs; func_t func_args(unsigned int n, function<double(args_t)> func) { return [func, n](args_t v) { if (v.size() == n) return return_t(true, func(v)); else return return_t(false, 0.0); }; } func_t func_constant(double c) { return func_args(0, [c](args_t v) { return c; }); } postfix_t infix2postfix(string in) { postfix_t out; stack<token_t> s; token_t lasttok; for (auto it = in.cbegin(); it != in.cend();) { const unsigned int i = it - in.cbegin(); static const string spaces = " \t\r\n"; if (spaces.find(*it) != string::npos) { ++it; continue; } /*cout << string(it, in.cend()) << endl; cout << lasttok.first << "/" << lasttok.second << endl; if (!s.empty()) cout << s.top().first << "/" << s.top().second << endl;*/ static const string numbers = "0123456789."; auto it2 = it; for (; it2 != in.cend() && numbers.find(*it2) != string::npos; ++it2); if (it2 != it) { if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end()) || lasttok.second == -1) throw parse_error("Missing operator", i); out.push_back(lasttok = token_t(string(it, it2), -1)); it = it2; continue; } bool unary = lasttok.first == "" || lasttok.first == "(" || lasttok.first == "," || opers.find(lasttok.first) != opers.end(); /*cout << unary << endl; cout << endl;*/ auto oit = opers.begin(); for (; oit != opers.end(); ++oit) { if (equal(oit->first.begin(), oit->first.end(), it) && oit->second.unary == unary) { break; } } if (oit != opers.end()) { if (unary) { s.push(lasttok = token_t(oit->first, 1)); } else { while (!s.empty()) { bool found = false; int tprec; auto range = opers.equal_range(s.top().first); for (auto oit2 = range.first; oit2 != range.second; ++oit2) { if (s.top().second == (oit2->second.unary ? 1 : 2)) { tprec = oit2->second.prec; found = true; break; } } if ((found && ((!oit->second.right && oit->second.prec == tprec) || (oit->second.prec < tprec))) || (range.first == range.second && funcs.find(s.top().first) != funcs.end())) { out.push_back(s.top()); s.pop(); } else break; } s.push(lasttok = token_t(oit->first, 2)); } it += oit->first.size(); continue; } auto fit = funcs.begin(); for (; fit != funcs.end(); ++fit) { if (opers.find(fit->first) == opers.end() && equal(fit->first.begin(), fit->first.end(), it)) { break; } } if (fit != funcs.end()) { if (lasttok.second == -1 || lasttok.first == ")") throw parse_error("Missing operator", i); s.push(lasttok = token_t(fit->first, 0)); it += fit->first.size(); continue; } if (*it == ',') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found ',' not inside function arguments", i); s.top().second++; lasttok = token_t(",", 0); ++it; continue; } if (*it == '(') { if (lasttok.second == -1) throw parse_error("Missing operator", i); s.push(lasttok = token_t("(", 1)); ++it; continue; } if (*it == ')') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found excess '('", i); token_t tok = s.top(); s.pop(); if (!s.empty() && opers.find(s.top().first) == opers.end() && funcs.find(s.top().first) != funcs.end()) { out.push_back(token_t(s.top().first, tok.second)); s.pop(); } lasttok = token_t(")", 0); ++it; continue; } throw parse_error("Unknown token found", i); } while (!s.empty()) { token_t tok = s.top(); s.pop(); if (tok.first == "(") throw parse_error("Found unclosed '('", in.size()); out.push_back(tok); } return out; } double evalpostfix(postfix_t in) { stack<double> s; for (token_t &tok : in) { if (tok.second == -1) s.push(stod(tok.first)); else { if (s.size() < tok.second) throw runtime_error("Not enough arguments (have " + to_string(s.size()) + ") for function '" + tok.first + "' (want " + to_string(tok.second) + ")"); else { args_t v; for (int i = 0; i < tok.second; i++) { v.insert(v.begin(), s.top()); s.pop(); } auto range = funcs.equal_range(tok.first); auto it = range.first; return_t ret(false, 0); for (; it != range.second; ++it) { ret = it->second(v); if (ret.first) break; } if (ret.first) s.push(ret.second); else { ostringstream args; // stringstream because to_string adds trailing zeroes for (auto vit = v.begin(); vit != v.end(); ++vit) { args << *vit; if ((vit + 1) != v.end()) args << ", "; } throw runtime_error("Unacceptable arguments (" + args.str() + ") for function '" + tok.first + "'"); } } } } if (s.size() == 1) return s.top(); else throw runtime_error("No single result found"); } int main() { opers.insert(make_pair("+", oper_t{false, 1, false})); opers.insert(make_pair("-", oper_t{false, 1, false})); opers.insert(make_pair("*", oper_t{false, 2, false})); opers.insert(make_pair("/", oper_t{false, 2, false})); opers.insert(make_pair("%", oper_t{false, 2, false})); opers.insert(make_pair("^", oper_t{true, 3, false})); opers.insert(make_pair("+", oper_t{false, 10, true})); opers.insert(make_pair("-", oper_t{false, 10, true})); funcs.insert(make_pair("+", func_args(1, [](vector<double> v) { return v[0]; }))); funcs.insert(make_pair("+", func_args(2, [](vector<double> v) { return v[0] + v[1]; }))); funcs.insert(make_pair("-", func_args(1, [](vector<double> v) { return -v[0]; }))); funcs.insert(make_pair("-", func_args(2, [](vector<double> v) { return v[0] - v[1]; }))); funcs.insert(make_pair("*", func_args(2, [](vector<double> v) { return v[0] * v[1]; }))); funcs.insert(make_pair("/", func_args(2, [](vector<double> v) { return v[0] / v[1]; }))); funcs.insert(make_pair("%", func_args(2, [](vector<double> v) { return fmod(v[0], v[1]); }))); funcs.insert(make_pair("^", func_args(2, [](vector<double> v) { return pow(v[0], v[1]); }))); funcs.insert(make_pair("abs", func_args(1, [](vector<double> v) { return abs(v[0]); }))); funcs.insert(make_pair("log", [](vector<double> v) { if (v.size() == 1) return make_pair(true, log10(v[0])); else if (v.size() == 2) return make_pair(true, log(v[1]) / log(v[0])); else return make_pair(false, 0.0); })); funcs.insert(make_pair("sqrt", func_args(1, [](vector<double> v) { return sqrt(v[0]); }))); funcs.insert(make_pair("min", [](vector<double> v) { if (v.size() > 0) return make_pair(true, *min_element(v.begin(), v.end())); else return make_pair(false, 0.0); })); funcs.insert(make_pair("max", [](vector<double> v) { if (v.size() > 0) return make_pair(true, *max_element(v.begin(), v.end())); else return make_pair(false, 0.0); })); funcs.insert(make_pair("pi", func_constant(M_PI))); funcs.insert(make_pair("e", func_constant(M_E))); funcs.insert(make_pair("_", func_constant(NAN))); string exp; while (cout << "> ", getline(cin, exp)) { try { auto postfix = infix2postfix(exp); for (auto &tok : postfix) cout << tok.first << "/" << tok.second << " "; cout << endl; double value = evalpostfix(postfix); cout << value << endl; funcs.find("_")->second = func_constant(value); } catch (parse_error &e) { cout << string(e.index() + 2, ' ') << "^" << endl; cout << e.what() << " at " << e.index() << endl; } catch (exception &e) { cout << e.what() << endl; } cout << endl; } return 0; }
#include <iostream> #include <iomanip> #include <string> #include <sstream> #include <vector> #include <stack> #include <map> #include <utility> #include <algorithm> #include <numeric> #include <cmath> #include <limits> #include <functional> #include <stdexcept> using namespace std; struct oper_t { bool right; int prec; bool unary; }; typedef pair<bool, double> return_t; typedef vector<double> args_t; typedef function<return_t(args_t)> func_t; typedef pair<string, int> token_t; typedef vector<token_t> postfix_t; class parse_error : public runtime_error { public: parse_error(const string &what_arg, unsigned int i_arg) : runtime_error(what_arg), i(i_arg) { } unsigned int index() const { return i; } protected: unsigned int i; }; multimap<string, oper_t> opers; multimap<string, func_t> funcs; func_t func_args(unsigned int n, function<double(args_t)> func) { return [func, n](args_t v) { if (v.size() == n) return return_t(true, func(v)); else return return_t(false, 0.0); }; } func_t func_constant(double c) { return func_args(0, [c](args_t v) { return c; }); } postfix_t infix2postfix(string in) { postfix_t out; stack<token_t> s; token_t lasttok; for (auto it = in.cbegin(); it != in.cend();) { const unsigned int i = it - in.cbegin(); static const string spaces = " \t\r\n"; if (spaces.find(*it) != string::npos) { ++it; continue; } /*cout << string(it, in.cend()) << endl; cout << lasttok.first << "/" << lasttok.second << endl; if (!s.empty()) cout << s.top().first << "/" << s.top().second << endl;*/ static const string numbers = "0123456789."; auto it2 = it; for (; it2 != in.cend() && numbers.find(*it2) != string::npos; ++it2); if (it2 != it) { if (lasttok.first == ")" || (opers.find(lasttok.first) == opers.end() && funcs.find(lasttok.first) != funcs.end()) || lasttok.second == -1) throw parse_error("Missing operator", i); out.push_back(lasttok = token_t(string(it, it2), -1)); it = it2; continue; } bool unary = lasttok.first == "" || lasttok.first == "(" || lasttok.first == "," || opers.find(lasttok.first) != opers.end(); /*cout << unary << endl; cout << endl;*/ auto oit = opers.begin(); for (; oit != opers.end(); ++oit) { if (equal(oit->first.begin(), oit->first.end(), it) && oit->second.unary == unary) { break; } } if (oit != opers.end()) { if (unary) { s.push(lasttok = token_t(oit->first, 1)); } else { while (!s.empty()) { bool found = false; int tprec; auto range = opers.equal_range(s.top().first); for (auto oit2 = range.first; oit2 != range.second; ++oit2) { if (s.top().second == (oit2->second.unary ? 1 : 2)) { tprec = oit2->second.prec; found = true; break; } } if ((found && ((!oit->second.right && oit->second.prec == tprec) || (oit->second.prec < tprec))) || (range.first == range.second && funcs.find(s.top().first) != funcs.end())) { out.push_back(s.top()); s.pop(); } else break; } s.push(lasttok = token_t(oit->first, 2)); } it += oit->first.size(); continue; } auto fit = funcs.begin(); for (; fit != funcs.end(); ++fit) { if (opers.find(fit->first) == opers.end() && equal(fit->first.begin(), fit->first.end(), it)) { break; } } if (fit != funcs.end()) { if (lasttok.second == -1 || lasttok.first == ")") throw parse_error("Missing operator", i); s.push(lasttok = token_t(fit->first, 0)); it += fit->first.size(); continue; } if (*it == ',') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found ',' not inside function arguments", i); s.top().second++; lasttok = token_t(",", 0); ++it; continue; } if (*it == '(') { if (lasttok.second == -1) throw parse_error("Missing operator", i); s.push(lasttok = token_t("(", 1)); ++it; continue; } if (*it == ')') { if (lasttok.first == "(" || lasttok.first == ",") throw parse_error("Missing argument", i); bool found = false; while (!s.empty()) { token_t tok = s.top(); if (tok.first == "(") { found = true; break; } else { out.push_back(tok); s.pop(); } } if (!found) throw parse_error("Found excess '('", i); token_t tok = s.top(); s.pop(); if (!s.empty() && opers.find(s.top().first) == opers.end() && funcs.find(s.top().first) != funcs.end()) { out.push_back(token_t(s.top().first, tok.second)); s.pop(); } lasttok = token_t(")", 0); ++it; continue; } throw parse_error("Unknown token found", i); } while (!s.empty()) { token_t tok = s.top(); s.pop(); if (tok.first == "(") throw parse_error("Found unclosed '('", in.size()); out.push_back(tok); } return out; } double evalpostfix(postfix_t in) { stack<double> s; for (token_t &tok : in) { if (tok.second == -1) s.push(stod(tok.first)); else { if (s.size() < tok.second) throw runtime_error("Not enough arguments (have " + to_string(s.size()) + ") for function '" + tok.first + "' (want " + to_string(tok.second) + ")"); else { args_t v; for (int i = 0; i < tok.second; i++) { v.insert(v.begin(), s.top()); s.pop(); } auto range = funcs.equal_range(tok.first); auto it = range.first; return_t ret(false, 0); for (; it != range.second; ++it) { ret = it->second(v); if (ret.first) break; } if (ret.first) s.push(ret.second); else { ostringstream args; // stringstream because to_string adds trailing zeroes for (auto vit = v.begin(); vit != v.end(); ++vit) { args << *vit; if ((vit + 1) != v.end()) args << ", "; } throw runtime_error("Unacceptable arguments (" + args.str() + ") for function '" + tok.first + "'"); } } } } if (s.size() == 1) return s.top(); else throw runtime_error("No single result found"); } int main() { opers.insert(make_pair("+", oper_t{false, 1, false})); opers.insert(make_pair("-", oper_t{false, 1, false})); opers.insert(make_pair("*", oper_t{false, 2, false})); opers.insert(make_pair("/", oper_t{false, 2, false})); opers.insert(make_pair("%", oper_t{false, 2, false})); opers.insert(make_pair("^", oper_t{true, 3, false})); opers.insert(make_pair("+", oper_t{false, 10, true})); opers.insert(make_pair("-", oper_t{false, 10, true})); funcs.insert(make_pair("+", func_args(1, [](args_t v) { return v[0]; }))); funcs.insert(make_pair("+", func_args(2, [](args_t v) { return v[0] + v[1]; }))); funcs.insert(make_pair("-", func_args(1, [](args_t v) { return -v[0]; }))); funcs.insert(make_pair("-", func_args(2, [](args_t v) { return v[0] - v[1]; }))); funcs.insert(make_pair("*", func_args(2, [](args_t v) { return v[0] * v[1]; }))); funcs.insert(make_pair("/", func_args(2, [](args_t v) { return v[0] / v[1]; }))); funcs.insert(make_pair("%", func_args(2, [](args_t v) { return fmod(v[0], v[1]); }))); funcs.insert(make_pair("^", func_args(2, [](args_t v) { return pow(v[0], v[1]); }))); funcs.insert(make_pair("abs", func_args(1, [](args_t v) { return abs(v[0]); }))); funcs.insert(make_pair("log", [](args_t v) { if (v.size() == 1) return make_pair(true, log10(v[0])); else if (v.size() == 2) return make_pair(true, log(v[1]) / log(v[0])); else return make_pair(false, 0.0); })); funcs.insert(make_pair("sqrt", func_args(1, [](args_t v) { return sqrt(v[0]); }))); funcs.insert(make_pair("min", [](args_t v) { if (v.size() > 0) return make_pair(true, *min_element(v.begin(), v.end())); else return make_pair(false, 0.0); })); funcs.insert(make_pair("max", [](args_t v) { if (v.size() > 0) return make_pair(true, *max_element(v.begin(), v.end())); else return make_pair(false, 0.0); })); funcs.insert(make_pair("pi", func_constant(M_PI))); funcs.insert(make_pair("e", func_constant(M_E))); funcs.insert(make_pair("_", func_constant(NAN))); string exp; while (cout << "> ", getline(cin, exp)) { try { auto postfix = infix2postfix(exp); for (auto &tok : postfix) cout << tok.first << "/" << tok.second << " "; cout << endl; double value = evalpostfix(postfix); cout << setprecision(numeric_limits<decltype(value)>::digits10) << value << endl; funcs.find("_")->second = func_constant(value); } catch (parse_error &e) { cout << string(e.index() + 2, ' ') << "^" << endl; cout << e.what() << " at " << e.index() << endl; } catch (exception &e) { cout << e.what() << endl; } cout << endl; } return 0; }
Use defined types, most accurate possible output
Use defined types, most accurate possible output
C++
mit
sim642/calculate,r-lyeh/eval
70901df2392512f97c3f523102a4dea0f7e469e0
chrome/browser/ui/views/uninstall_view.cc
chrome/browser/ui/views/uninstall_view.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/uninstall_view.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/run_loop.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/uninstall_browser_prompt.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" UninstallView::UninstallView(int* user_selection, const base::Closure& quit_closure, bool show_delete_profile) : confirm_label_(NULL), show_delete_profile_(show_delete_profile), delete_profile_(NULL), change_default_browser_(NULL), browsers_combo_(NULL), user_selection_(*user_selection), quit_closure_(quit_closure) { SetupControls(); } UninstallView::~UninstallView() { // Exit the message loop we were started with so that uninstall can continue. quit_closure_.Run(); } void UninstallView::SetupControls() { using views::ColumnSet; using views::GridLayout; GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); // Message to confirm uninstallation. int column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); confirm_label_ = new views::Label( l10n_util::GetStringUTF16(IDS_UNINSTALL_VERIFY)); confirm_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(confirm_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); // The "delete profile" check box. if (show_delete_profile_) { ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); delete_profile_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_DELETE_PROFILE)); layout->AddView(delete_profile_); } // Set default browser combo box. If the default should not or cannot be // changed, widgets are not shown. We assume here that if Chrome cannot // be set programatically as default, neither can any other browser (for // instance because the OS doesn't permit that). BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (dist->CanSetAsDefault() && ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT && (ShellIntegration::CanSetAsDefaultBrowser() != ShellIntegration::SET_DEFAULT_INTERACTIVE)) { browsers_.reset(new BrowsersMap()); ShellUtil::GetRegisteredBrowsers(dist, browsers_.get()); if (!browsers_->empty()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); change_default_browser_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_SET_DEFAULT_BROWSER)); change_default_browser_->set_listener(this); layout->AddView(change_default_browser_); browsers_combo_ = new views::Combobox(this); layout->AddView(browsers_combo_); browsers_combo_->SetEnabled(false); } } layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing); } bool UninstallView::Accept() { user_selection_ = content::RESULT_CODE_NORMAL_EXIT; if (show_delete_profile_ && delete_profile_->checked()) user_selection_ = chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE; if (change_default_browser_ && change_default_browser_->checked()) { BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, browsers_combo_->selected_index()); base::LaunchOptions options; options.start_hidden = true; base::LaunchProcess(i->second, options, NULL); } return true; } bool UninstallView::Cancel() { user_selection_ = chrome::RESULT_CODE_UNINSTALL_USER_CANCEL; return true; } string16 UninstallView::GetDialogButtonLabel(ui::DialogButton button) const { // We only want to give custom name to OK button - 'Uninstall'. Cancel // button remains same. if (button == ui::DIALOG_BUTTON_OK) return l10n_util::GetStringUTF16(IDS_UNINSTALL_BUTTON_TEXT); return string16(); } void UninstallView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (change_default_browser_ == sender) { // Disable the browsers combobox if the user unchecks the checkbox. DCHECK(browsers_combo_); browsers_combo_->SetEnabled(change_default_browser_->checked()); } } string16 UninstallView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME); } int UninstallView::GetItemCount() const { DCHECK(!browsers_->empty()); return browsers_->size(); } string16 UninstallView::GetItemAt(int index) { DCHECK_LT(index, static_cast<int>(browsers_->size())); BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, index); return i->first; } namespace chrome { int ShowUninstallBrowserPrompt(bool show_delete_profile) { DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type()); int result = content::RESULT_CODE_NORMAL_EXIT; views::AcceleratorHandler accelerator_handler; base::RunLoop run_loop(&accelerator_handler); UninstallView* view = new UninstallView(&result, run_loop.QuitClosure(), show_delete_profile); views::Widget::CreateWindow(view)->Show(); run_loop.Run(); return result; } } // namespace chrome
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/uninstall_view.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/run_loop.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/uninstall_browser_prompt.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" UninstallView::UninstallView(int* user_selection, const base::Closure& quit_closure, bool show_delete_profile) : confirm_label_(NULL), show_delete_profile_(show_delete_profile), delete_profile_(NULL), change_default_browser_(NULL), browsers_combo_(NULL), user_selection_(*user_selection), quit_closure_(quit_closure) { SetupControls(); } UninstallView::~UninstallView() { // Exit the message loop we were started with so that uninstall can continue. quit_closure_.Run(); } void UninstallView::SetupControls() { using views::ColumnSet; using views::GridLayout; GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); // Message to confirm uninstallation. int column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); confirm_label_ = new views::Label( l10n_util::GetStringUTF16(IDS_UNINSTALL_VERIFY)); confirm_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(confirm_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); // The "delete profile" check box. if (show_delete_profile_) { ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); delete_profile_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_DELETE_PROFILE)); layout->AddView(delete_profile_); } // Set default browser combo box. If the default should not or cannot be // changed, widgets are not shown. We assume here that if Chrome cannot // be set programatically as default, neither can any other browser (for // instance because the OS doesn't permit that). BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (dist->CanSetAsDefault() && ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT && (ShellIntegration::CanSetAsDefaultBrowser() != ShellIntegration::SET_DEFAULT_INTERACTIVE)) { browsers_.reset(new BrowsersMap()); ShellUtil::GetRegisteredBrowsers(dist, browsers_.get()); if (!browsers_->empty()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); change_default_browser_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_SET_DEFAULT_BROWSER)); change_default_browser_->set_listener(this); layout->AddView(change_default_browser_); browsers_combo_ = new views::Combobox(this); layout->AddView(browsers_combo_); browsers_combo_->SetEnabled(false); } } layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing); } bool UninstallView::Accept() { user_selection_ = content::RESULT_CODE_NORMAL_EXIT; if (show_delete_profile_ && delete_profile_->checked()) user_selection_ = chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE; if (change_default_browser_ && change_default_browser_->checked()) { BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, browsers_combo_->selected_index()); base::LaunchOptions options; options.start_hidden = true; base::LaunchProcess(i->second, options, NULL); } return true; } bool UninstallView::Cancel() { user_selection_ = chrome::RESULT_CODE_UNINSTALL_USER_CANCEL; return true; } string16 UninstallView::GetDialogButtonLabel(ui::DialogButton button) const { // Label the OK button 'Uninstall'; Cancel remains the same. if (button == ui::DIALOG_BUTTON_OK) return l10n_util::GetStringUTF16(IDS_UNINSTALL_BUTTON_TEXT); return views::DialogDelegateView::GetDialogButtonLabel(button); } void UninstallView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (change_default_browser_ == sender) { // Disable the browsers combobox if the user unchecks the checkbox. DCHECK(browsers_combo_); browsers_combo_->SetEnabled(change_default_browser_->checked()); } } string16 UninstallView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME); } int UninstallView::GetItemCount() const { DCHECK(!browsers_->empty()); return browsers_->size(); } string16 UninstallView::GetItemAt(int index) { DCHECK_LT(index, static_cast<int>(browsers_->size())); BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, index); return i->first; } namespace chrome { int ShowUninstallBrowserPrompt(bool show_delete_profile) { DCHECK_EQ(MessageLoop::TYPE_UI, MessageLoop::current()->type()); int result = content::RESULT_CODE_NORMAL_EXIT; views::AcceleratorHandler accelerator_handler; base::RunLoop run_loop(&accelerator_handler); UninstallView* view = new UninstallView(&result, run_loop.QuitClosure(), show_delete_profile); views::Widget::CreateWindow(view)->Show(); run_loop.Run(); return result; } } // namespace chrome
Fix GetDialogButtonLabel for UninstallView.
Fix GetDialogButtonLabel for UninstallView. Return the base class text for the cancel button. This was a regression from http://crrev.com/183286. That changed the behavior of GetDialogButtonLabel. I simply missed this dialog in the update; sorry! BUG=166075,178464 TEST=Uninstall dialog has expected Cancel button text. [email protected] Review URL: https://chromiumcodereview.appspot.com/12342026 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@184851 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
krieger-od/nwjs_chromium.src,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,Jonekee/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,ChromiumWebApps/chromium,timopulkkinen/BubbleFish,chuan9/chromium-crosswalk,littlstar/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,chuan9/chromium-crosswalk,Just-D/chromium-1,bright-sparks/chromium-spacewalk,ltilve/chromium,markYoungH/chromium.src,patrickm/chromium.src,krieger-od/nwjs_chromium.src,M4sse/chromium.src,patrickm/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Just-D/chromium-1,ltilve/chromium,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,dushu1203/chromium.src,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,anirudhSK/chromium,anirudhSK/chromium,dushu1203/chromium.src,dednal/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,axinging/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,dushu1203/chromium.src,hujiajie/pa-chromium,chuan9/chromium-crosswalk,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,bright-sparks/chromium-spacewalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,Jonekee/chromium.src,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,timopulkkinen/BubbleFish,jaruba/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,markYoungH/chromium.src,anirudhSK/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,ondra-novak/chromium.src,timopulkkinen/BubbleFish,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,jaruba/chromium.src,ondra-novak/chromium.src,hujiajie/pa-chromium,markYoungH/chromium.src,Chilledheart/chromium,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,axinging/chromium-crosswalk,littlstar/chromium.src,axinging/chromium-crosswalk,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,markYoungH/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,Fireblend/chromium-crosswalk,Fireblend/chromium-crosswalk,ltilve/chromium,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,anirudhSK/chromium,jaruba/chromium.src,anirudhSK/chromium,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,Just-D/chromium-1,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,M4sse/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,ltilve/chromium,hujiajie/pa-chromium,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl,Chilledheart/chromium,anirudhSK/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,hujiajie/pa-chromium,Chilledheart/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,patrickm/chromium.src,chuan9/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,Jonekee/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,fujunwei/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,Fireblend/chromium-crosswalk,patrickm/chromium.src,axinging/chromium-crosswalk,dednal/chromium.src,anirudhSK/chromium,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,bright-sparks/chromium-spacewalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,markYoungH/chromium.src,dushu1203/chromium.src,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,M4sse/chromium.src,krieger-od/nwjs_chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,M4sse/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,mogoweb/chromium-crosswalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,hujiajie/pa-chromium,anirudhSK/chromium,mogoweb/chromium-crosswalk,Chilledheart/chromium,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,krieger-od/nwjs_chromium.src,dushu1203/chromium.src,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,markYoungH/chromium.src,dushu1203/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,M4sse/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,jaruba/chromium.src,ChromiumWebApps/chromium,hujiajie/pa-chromium,patrickm/chromium.src,ltilve/chromium,TheTypoMaster/chromium-crosswalk,Jonekee/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,crosswalk-project/chromium-crosswalk-efl
a60b5865e906adeae2449c5f63fdd30655b68971
chrome/browser/ui/views/uninstall_view.cc
chrome/browser/ui/views/uninstall_view.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/uninstall_view.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/run_loop.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/uninstall_browser_prompt.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" UninstallView::UninstallView(int* user_selection, const base::Closure& quit_closure, bool show_delete_profile) : confirm_label_(NULL), show_delete_profile_(show_delete_profile), delete_profile_(NULL), change_default_browser_(NULL), browsers_combo_(NULL), user_selection_(*user_selection), quit_closure_(quit_closure) { SetupControls(); } UninstallView::~UninstallView() { // Exit the message loop we were started with so that uninstall can continue. quit_closure_.Run(); } void UninstallView::SetupControls() { using views::ColumnSet; using views::GridLayout; GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); // Message to confirm uninstallation. int column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); confirm_label_ = new views::Label( l10n_util::GetStringUTF16(IDS_UNINSTALL_VERIFY)); confirm_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(confirm_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); // The "delete profile" check box. if (show_delete_profile_) { ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); delete_profile_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_DELETE_PROFILE)); layout->AddView(delete_profile_); } // Set default browser combo box. If the default should not or cannot be // changed, widgets are not shown. We assume here that if Chrome cannot // be set programatically as default, neither can any other browser (for // instance because the OS doesn't permit that). BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (dist->CanSetAsDefault() && ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT && (ShellIntegration::CanSetAsDefaultBrowser() != ShellIntegration::SET_DEFAULT_INTERACTIVE)) { browsers_.reset(new BrowsersMap()); ShellUtil::GetRegisteredBrowsers(dist, browsers_.get()); if (!browsers_->empty()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); change_default_browser_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_SET_DEFAULT_BROWSER)); change_default_browser_->set_listener(this); layout->AddView(change_default_browser_); browsers_combo_ = new views::Combobox(this); layout->AddView(browsers_combo_); browsers_combo_->SetEnabled(false); } } layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing); } bool UninstallView::Accept() { user_selection_ = content::RESULT_CODE_NORMAL_EXIT; if (show_delete_profile_ && delete_profile_->checked()) user_selection_ = chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE; if (change_default_browser_ && change_default_browser_->checked()) { BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, browsers_combo_->selected_index()); base::LaunchOptions options; options.start_hidden = true; base::LaunchProcess(i->second, options, NULL); } return true; } bool UninstallView::Cancel() { user_selection_ = chrome::RESULT_CODE_UNINSTALL_USER_CANCEL; return true; } string16 UninstallView::GetDialogButtonLabel(ui::DialogButton button) const { // Label the OK button 'Uninstall'; Cancel remains the same. if (button == ui::DIALOG_BUTTON_OK) return l10n_util::GetStringUTF16(IDS_UNINSTALL_BUTTON_TEXT); return views::DialogDelegateView::GetDialogButtonLabel(button); } void UninstallView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (change_default_browser_ == sender) { // Disable the browsers combobox if the user unchecks the checkbox. DCHECK(browsers_combo_); browsers_combo_->SetEnabled(change_default_browser_->checked()); } } string16 UninstallView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME); } int UninstallView::GetItemCount() const { DCHECK(!browsers_->empty()); return browsers_->size(); } string16 UninstallView::GetItemAt(int index) { DCHECK_LT(index, static_cast<int>(browsers_->size())); BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, index); return i->first; } namespace chrome { int ShowUninstallBrowserPrompt(bool show_delete_profile) { DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type()); int result = content::RESULT_CODE_NORMAL_EXIT; views::AcceleratorHandler accelerator_handler; base::RunLoop run_loop(&accelerator_handler); UninstallView* view = new UninstallView(&result, run_loop.QuitClosure(), show_delete_profile); views::Widget::CreateWindow(view)->Show(); run_loop.Run(); return result; } } // namespace chrome
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ui/views/uninstall_view.h" #include "base/message_loop.h" #include "base/process_util.h" #include "base/run_loop.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/shell_integration.h" #include "chrome/browser/ui/uninstall_browser_prompt.h" #include "chrome/common/chrome_result_codes.h" #include "chrome/installer/util/browser_distribution.h" #include "chrome/installer/util/shell_util.h" #include "grit/chromium_strings.h" #include "ui/base/l10n/l10n_util.h" #include "ui/views/controls/button/checkbox.h" #include "ui/views/controls/combobox/combobox.h" #include "ui/views/controls/label.h" #include "ui/views/focus/accelerator_handler.h" #include "ui/views/layout/grid_layout.h" #include "ui/views/layout/layout_constants.h" #include "ui/views/widget/widget.h" UninstallView::UninstallView(int* user_selection, const base::Closure& quit_closure, bool show_delete_profile) : confirm_label_(NULL), show_delete_profile_(show_delete_profile), delete_profile_(NULL), change_default_browser_(NULL), browsers_combo_(NULL), user_selection_(*user_selection), quit_closure_(quit_closure) { SetupControls(); } UninstallView::~UninstallView() { // Exit the message loop we were started with so that uninstall can continue. quit_closure_.Run(); } void UninstallView::SetupControls() { using views::ColumnSet; using views::GridLayout; GridLayout* layout = GridLayout::CreatePanel(this); SetLayoutManager(layout); // Message to confirm uninstallation. int column_set_id = 0; ColumnSet* column_set = layout->AddColumnSet(column_set_id); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); confirm_label_ = new views::Label( l10n_util::GetStringUTF16(IDS_UNINSTALL_VERIFY)); confirm_label_->SetHorizontalAlignment(gfx::ALIGN_LEFT); layout->AddView(confirm_label_); layout->AddPaddingRow(0, views::kUnrelatedControlVerticalSpacing); // The "delete profile" check box. if (show_delete_profile_) { ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); delete_profile_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_DELETE_PROFILE)); layout->AddView(delete_profile_); } // Set default browser combo box. If the default should not or cannot be // changed, widgets are not shown. We assume here that if Chrome cannot // be set programatically as default, neither can any other browser (for // instance because the OS doesn't permit that). BrowserDistribution* dist = BrowserDistribution::GetDistribution(); if (dist->CanSetAsDefault() && ShellIntegration::GetDefaultBrowser() == ShellIntegration::IS_DEFAULT && (ShellIntegration::CanSetAsDefaultBrowser() != ShellIntegration::SET_DEFAULT_INTERACTIVE)) { browsers_.reset(new BrowsersMap()); ShellUtil::GetRegisteredBrowsers(dist, browsers_.get()); if (!browsers_->empty()) { layout->AddPaddingRow(0, views::kRelatedControlVerticalSpacing); ++column_set_id; column_set = layout->AddColumnSet(column_set_id); column_set->AddPaddingColumn(0, views::kPanelHorizIndentation); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); column_set->AddPaddingColumn(0, views::kRelatedControlHorizontalSpacing); column_set->AddColumn(GridLayout::LEADING, GridLayout::CENTER, 0, GridLayout::USE_PREF, 0, 0); layout->StartRow(0, column_set_id); change_default_browser_ = new views::Checkbox( l10n_util::GetStringUTF16(IDS_UNINSTALL_SET_DEFAULT_BROWSER)); change_default_browser_->set_listener(this); layout->AddView(change_default_browser_); browsers_combo_ = new views::Combobox(this); layout->AddView(browsers_combo_); browsers_combo_->SetEnabled(false); } } layout->AddPaddingRow(0, views::kRelatedControlSmallVerticalSpacing); } bool UninstallView::Accept() { user_selection_ = content::RESULT_CODE_NORMAL_EXIT; if (show_delete_profile_ && delete_profile_->checked()) user_selection_ = chrome::RESULT_CODE_UNINSTALL_DELETE_PROFILE; if (change_default_browser_ && change_default_browser_->checked()) { BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, browsers_combo_->selected_index()); base::LaunchOptions options; options.start_hidden = true; base::LaunchProcess(i->second, options, NULL); } return true; } bool UninstallView::Cancel() { user_selection_ = chrome::RESULT_CODE_UNINSTALL_USER_CANCEL; return true; } string16 UninstallView::GetDialogButtonLabel(ui::DialogButton button) const { // Label the OK button 'Uninstall'; Cancel remains the same. if (button == ui::DIALOG_BUTTON_OK) return l10n_util::GetStringUTF16(IDS_UNINSTALL_BUTTON_TEXT); return views::DialogDelegateView::GetDialogButtonLabel(button); } void UninstallView::ButtonPressed(views::Button* sender, const ui::Event& event) { if (change_default_browser_ == sender) { // Disable the browsers combobox if the user unchecks the checkbox. DCHECK(browsers_combo_); browsers_combo_->SetEnabled(change_default_browser_->checked()); } } string16 UninstallView::GetWindowTitle() const { return l10n_util::GetStringUTF16(IDS_UNINSTALL_CHROME); } int UninstallView::GetItemCount() const { DCHECK(!browsers_->empty()); return browsers_->size(); } string16 UninstallView::GetItemAt(int index) { DCHECK_LT(index, static_cast<int>(browsers_->size())); BrowsersMap::const_iterator i = browsers_->begin(); std::advance(i, index); return i->first; } namespace chrome { int ShowUninstallBrowserPrompt(bool show_delete_profile) { DCHECK_EQ(base::MessageLoop::TYPE_UI, base::MessageLoop::current()->type()); int result = content::RESULT_CODE_NORMAL_EXIT; views::AcceleratorHandler accelerator_handler; // Take a reference on g_browser_process while showing the dialog. This is // done because the dialog uses the views framework which may increment // and decrement the module ref count during the course of displaying UI and // this code can be called while the module refcount is still at 0. // Note that this reference is never released, as this code is shown on a path // that immediately exits Chrome anyway. // See http://crbug.com/241366 for details. g_browser_process->AddRefModule(); base::RunLoop run_loop(&accelerator_handler); UninstallView* view = new UninstallView(&result, run_loop.QuitClosure(), show_delete_profile); views::Widget::CreateWindow(view)->Show(); run_loop.Run(); return result; } } // namespace chrome
Add a leaked reference to g_browser_process before showing the uninstall dialog to avoid the views framework from erroneously exiting the browser process.
Add a leaked reference to g_browser_process before showing the uninstall dialog to avoid the views framework from erroneously exiting the browser process. BUG=241366 TEST=Uninstall Chrome while it is set as the default browser. Select an item from the "make other browser default" combobox. Observe that the dialog does not immediately close. Review URL: https://chromiumcodereview.appspot.com/15134004 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@200732 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dushu1203/chromium.src,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,Jonekee/chromium.src,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,ondra-novak/chromium.src,chuan9/chromium-crosswalk,dushu1203/chromium.src,Chilledheart/chromium,chuan9/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,Jonekee/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,markYoungH/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,dushu1203/chromium.src,M4sse/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,markYoungH/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,Chilledheart/chromium,ondra-novak/chromium.src,hujiajie/pa-chromium,hgl888/chromium-crosswalk,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,mogoweb/chromium-crosswalk,anirudhSK/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,M4sse/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Fireblend/chromium-crosswalk,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,Just-D/chromium-1,patrickm/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,dushu1203/chromium.src,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,jaruba/chromium.src,fujunwei/chromium-crosswalk,bright-sparks/chromium-spacewalk,jaruba/chromium.src,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,littlstar/chromium.src,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,dushu1203/chromium.src,Chilledheart/chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,axinging/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,PeterWangIntel/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,patrickm/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,patrickm/chromium.src,Just-D/chromium-1,littlstar/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,krieger-od/nwjs_chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,mogoweb/chromium-crosswalk,Just-D/chromium-1,Jonekee/chromium.src,fujunwei/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,Jonekee/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,dednal/chromium.src,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,ltilve/chromium,hujiajie/pa-chromium,ChromiumWebApps/chromium,chuan9/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,markYoungH/chromium.src,axinging/chromium-crosswalk,Just-D/chromium-1,hgl888/chromium-crosswalk-efl,anirudhSK/chromium,Fireblend/chromium-crosswalk,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,Jonekee/chromium.src,Just-D/chromium-1,dednal/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,M4sse/chromium.src,ChromiumWebApps/chromium,littlstar/chromium.src,ltilve/chromium,hgl888/chromium-crosswalk-efl,chuan9/chromium-crosswalk,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,anirudhSK/chromium,ltilve/chromium,axinging/chromium-crosswalk,hujiajie/pa-chromium,Jonekee/chromium.src,Just-D/chromium-1,anirudhSK/chromium,mogoweb/chromium-crosswalk,littlstar/chromium.src,hujiajie/pa-chromium,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,Just-D/chromium-1,anirudhSK/chromium,Chilledheart/chromium,krieger-od/nwjs_chromium.src,littlstar/chromium.src,hujiajie/pa-chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,Pluto-tv/chromium-crosswalk,mogoweb/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,M4sse/chromium.src,ChromiumWebApps/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,ondra-novak/chromium.src,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,hgl888/chromium-crosswalk,ltilve/chromium,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,PeterWangIntel/chromium-crosswalk,markYoungH/chromium.src,Chilledheart/chromium,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,Jonekee/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,dushu1203/chromium.src,anirudhSK/chromium,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,Jonekee/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,markYoungH/chromium.src,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,jaruba/chromium.src,anirudhSK/chromium,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,jaruba/chromium.src,dednal/chromium.src,dednal/chromium.src,fujunwei/chromium-crosswalk,ondra-novak/chromium.src,jaruba/chromium.src,M4sse/chromium.src,anirudhSK/chromium,M4sse/chromium.src,krieger-od/nwjs_chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,M4sse/chromium.src,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,bright-sparks/chromium-spacewalk,pozdnyakov/chromium-crosswalk,dednal/chromium.src,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,Just-D/chromium-1,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,fujunwei/chromium-crosswalk,jaruba/chromium.src,jaruba/chromium.src,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Chilledheart/chromium,markYoungH/chromium.src,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,jaruba/chromium.src
51890613b7cdeddff9ad3360a91908ded28bc5f0
vcl/source/glyphs/graphite_features.cxx
vcl/source/glyphs/graphite_features.cxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ // Description: // Parse a string of features specified as & separated pairs. // e.g. // 1001=1&2002=2&fav1=0 #include <sal/types.h> #ifdef WNT #include <windows.h> #endif #include <graphite_features.hxx> using namespace grutils; // These mustn't conflict with font name lists which use ; and , const char GrFeatureParser::FEAT_PREFIX = ':'; const char GrFeatureParser::FEAT_SEPARATOR = '&'; const char GrFeatureParser::FEAT_ID_VALUE_SEPARATOR = '='; GrFeatureParser::GrFeatureParser(const gr_face * pFace, const ::rtl::OString lang) : mnNumSettings(0), mbErrors(false), mpSettings(NULL) { maLang.label[0] = maLang.label[1] = maLang.label[2] = maLang.label[3] = '\0'; setLang(pFace, lang); } GrFeatureParser::GrFeatureParser(const gr_face * pFace, const ::rtl::OString features, const ::rtl::OString lang) : mnNumSettings(0), mbErrors(false), mpSettings(NULL) { sal_Int32 nEquals = 0; sal_Int32 nFeatEnd = 0; sal_Int32 pos = 0; maLang.num = 0u; setLang(pFace, lang); while ((pos < features.getLength()) && (mnNumSettings < MAX_FEATURES)) { nEquals = features.indexOf(FEAT_ID_VALUE_SEPARATOR, pos); if (nEquals == -1) { mbErrors = true; break; } // check for a lang=xxx specification const ::rtl::OString aLangPrefix("lang"); if (features.match(aLangPrefix, pos )) { pos = nEquals + 1; nFeatEnd = features.indexOf(FEAT_SEPARATOR, pos); if (nFeatEnd == -1) { nFeatEnd = features.getLength(); } if (nFeatEnd - pos > 3) mbErrors = true; else { FeatId aLang = maLang; aLang.num = 0; for (sal_Int32 i = pos; i < nFeatEnd; i++) aLang.label[i-pos] = features[i]; //ext_std::pair<gr::LanguageIterator,gr::LanguageIterator> aSupported // = font.getSupportedLanguages(); //gr::LanguageIterator iL = aSupported.first; unsigned short i = 0; for (; i < gr_face_n_languages(pFace); i++) { gr_uint32 nFaceLang = gr_face_lang_by_index(pFace, i); FeatId aSupportedLang; aSupportedLang.num = nFaceLang; #ifdef __BIG_ENDIAN__ // here we only expect full 3 letter codes if (aLang.label[0] == aSupportedLang.label[0] && aLang.label[1] == aSupportedLang.label[1] && aLang.label[2] == aSupportedLang.label[2] && aLang.label[3] == aSupportedLang.label[3]) #else if (aLang.label[0] == aSupportedLang.label[3] && aLang.label[1] == aSupportedLang.label[2] && aLang.label[2] == aSupportedLang.label[1] && aLang.label[3] == aSupportedLang.label[0]) #endif { maLang = aSupportedLang; break; } } if (i == gr_face_n_languages(pFace)) mbErrors = true; else { mnHash = maLang.num; mpSettings = gr_face_featureval_for_lang(pFace, maLang.num); } } } else { sal_uInt32 featId = 0; if (isCharId(features, pos, nEquals - pos)) { featId = getCharId(features, pos, nEquals - pos); } else { featId = getIntValue(features, pos, nEquals - pos); } const gr_feature_ref * pFref = gr_face_find_fref(pFace, featId); pos = nEquals + 1; nFeatEnd = features.indexOf(FEAT_SEPARATOR, pos); if (nFeatEnd == -1) { nFeatEnd = features.getLength(); } sal_Int16 featValue = 0; featValue = getIntValue(features, pos, nFeatEnd - pos); if (pFref && gr_fref_set_feature_value(pFref, featValue, mpSettings)) { mnHash = (mnHash << 16) ^ ((featId << 8) | featValue); mnNumSettings++; } else mbErrors = true; } pos = nFeatEnd + 1; } } void GrFeatureParser::setLang(const gr_face * pFace, const rtl::OString & lang) { FeatId aLang; aLang.num = 0; if (lang.getLength() >= 2) { for (sal_Int32 i = 0; i < lang.getLength() && i < 3; i++) { if (lang[i] == '-') break; aLang.label[i] = lang[i]; } unsigned short i = 0; for (; i < gr_face_n_languages(pFace); i++) { gr_uint32 nFaceLang = gr_face_lang_by_index(pFace, i); FeatId aSupportedLang; aSupportedLang.num = nFaceLang; // here we only expect full 2 & 3 letter codes #ifdef __BIG_ENDIAN__ if (aLang.label[0] == aSupportedLang.label[0] && aLang.label[1] == aSupportedLang.label[1] && aLang.label[2] == aSupportedLang.label[2] && aLang.label[3] == aSupportedLang.label[3]) #else if (aLang.label[0] == aSupportedLang.label[3] && aLang.label[1] == aSupportedLang.label[2] && aLang.label[2] == aSupportedLang.label[1] && aLang.label[3] == aSupportedLang.label[0]) #endif { maLang = aSupportedLang; break; } } if (i != gr_face_n_languages(pFace)) { if (mpSettings) gr_featureval_destroy(mpSettings); mpSettings = gr_face_featureval_for_lang(pFace, maLang.num); mnHash = maLang.num; } } if (!mpSettings) mpSettings = gr_face_featureval_for_lang(pFace, 0); } GrFeatureParser::~GrFeatureParser() { if (mpSettings) { gr_featureval_destroy(mpSettings); mpSettings = NULL; } } bool GrFeatureParser::isCharId(const rtl::OString & id, size_t offset, size_t length) { if (length > 4) return false; for (size_t i = 0; i < length; i++) { if (i > 0 && id[offset+i] == '\0') continue; if ((id[offset+i] < 0x20) || (id[offset+i] < 0)) return false; if (i==0 && (id[offset+i] < 0x41)) return false; } return true; } gr_uint32 GrFeatureParser::getCharId(const rtl::OString & id, size_t offset, size_t length) { FeatId charId; charId.num = 0; #ifdef WORDS_BIGENDIAN for (size_t i = 0; i < length; i++) { charId.label[i] = id[offset+i]; } #else for (size_t i = 0; i < length; i++) { charId.label[3-i] = id[offset+i]; } #endif return charId.num; } short GrFeatureParser::getIntValue(const rtl::OString & id, size_t offset, size_t length) { short value = 0; int sign = 1; for (size_t i = 0; i < length; i++) { switch (id[offset + i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value *= 10; if (sign < 0) { value = -(id[offset + i] - '0'); sign = 1; } value += (id[offset + i] - '0'); break; case '-': if (i == 0) sign = -1; else { mbErrors = true; break; } default: mbErrors = true; break; } } return value; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed * with this work for additional information regarding copyright * ownership. The ASF licenses this file to you under the Apache * License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of * the License at http://www.apache.org/licenses/LICENSE-2.0 . */ // Description: // Parse a string of features specified as & separated pairs. // e.g. // 1001=1&2002=2&fav1=0 #include <sal/types.h> #include <osl/endian.h> #ifdef WNT #include <windows.h> #endif #include <graphite_features.hxx> using namespace grutils; // These mustn't conflict with font name lists which use ; and , const char GrFeatureParser::FEAT_PREFIX = ':'; const char GrFeatureParser::FEAT_SEPARATOR = '&'; const char GrFeatureParser::FEAT_ID_VALUE_SEPARATOR = '='; GrFeatureParser::GrFeatureParser(const gr_face * pFace, const ::rtl::OString lang) : mnNumSettings(0), mbErrors(false), mpSettings(NULL) { maLang.label[0] = maLang.label[1] = maLang.label[2] = maLang.label[3] = '\0'; setLang(pFace, lang); } GrFeatureParser::GrFeatureParser(const gr_face * pFace, const ::rtl::OString features, const ::rtl::OString lang) : mnNumSettings(0), mbErrors(false), mpSettings(NULL) { sal_Int32 nEquals = 0; sal_Int32 nFeatEnd = 0; sal_Int32 pos = 0; maLang.num = 0u; setLang(pFace, lang); while ((pos < features.getLength()) && (mnNumSettings < MAX_FEATURES)) { nEquals = features.indexOf(FEAT_ID_VALUE_SEPARATOR, pos); if (nEquals == -1) { mbErrors = true; break; } // check for a lang=xxx specification const ::rtl::OString aLangPrefix("lang"); if (features.match(aLangPrefix, pos )) { pos = nEquals + 1; nFeatEnd = features.indexOf(FEAT_SEPARATOR, pos); if (nFeatEnd == -1) { nFeatEnd = features.getLength(); } if (nFeatEnd - pos > 3) mbErrors = true; else { FeatId aLang = maLang; aLang.num = 0; for (sal_Int32 i = pos; i < nFeatEnd; i++) aLang.label[i-pos] = features[i]; //ext_std::pair<gr::LanguageIterator,gr::LanguageIterator> aSupported // = font.getSupportedLanguages(); //gr::LanguageIterator iL = aSupported.first; unsigned short i = 0; for (; i < gr_face_n_languages(pFace); i++) { gr_uint32 nFaceLang = gr_face_lang_by_index(pFace, i); FeatId aSupportedLang; aSupportedLang.num = nFaceLang; #ifdef OSL_BIGENDIAN // here we only expect full 3 letter codes if (aLang.label[0] == aSupportedLang.label[0] && aLang.label[1] == aSupportedLang.label[1] && aLang.label[2] == aSupportedLang.label[2] && aLang.label[3] == aSupportedLang.label[3]) #else if (aLang.label[0] == aSupportedLang.label[3] && aLang.label[1] == aSupportedLang.label[2] && aLang.label[2] == aSupportedLang.label[1] && aLang.label[3] == aSupportedLang.label[0]) #endif { maLang = aSupportedLang; break; } } if (i == gr_face_n_languages(pFace)) mbErrors = true; else { mnHash = maLang.num; mpSettings = gr_face_featureval_for_lang(pFace, maLang.num); } } } else { sal_uInt32 featId = 0; if (isCharId(features, pos, nEquals - pos)) { featId = getCharId(features, pos, nEquals - pos); } else { featId = getIntValue(features, pos, nEquals - pos); } const gr_feature_ref * pFref = gr_face_find_fref(pFace, featId); pos = nEquals + 1; nFeatEnd = features.indexOf(FEAT_SEPARATOR, pos); if (nFeatEnd == -1) { nFeatEnd = features.getLength(); } sal_Int16 featValue = 0; featValue = getIntValue(features, pos, nFeatEnd - pos); if (pFref && gr_fref_set_feature_value(pFref, featValue, mpSettings)) { mnHash = (mnHash << 16) ^ ((featId << 8) | featValue); mnNumSettings++; } else mbErrors = true; } pos = nFeatEnd + 1; } } void GrFeatureParser::setLang(const gr_face * pFace, const rtl::OString & lang) { FeatId aLang; aLang.num = 0; if (lang.getLength() >= 2) { for (sal_Int32 i = 0; i < lang.getLength() && i < 3; i++) { if (lang[i] == '-') break; aLang.label[i] = lang[i]; } unsigned short i = 0; for (; i < gr_face_n_languages(pFace); i++) { gr_uint32 nFaceLang = gr_face_lang_by_index(pFace, i); FeatId aSupportedLang; aSupportedLang.num = nFaceLang; // here we only expect full 2 & 3 letter codes #ifdef OSL_BIGENDIAN if (aLang.label[0] == aSupportedLang.label[0] && aLang.label[1] == aSupportedLang.label[1] && aLang.label[2] == aSupportedLang.label[2] && aLang.label[3] == aSupportedLang.label[3]) #else if (aLang.label[0] == aSupportedLang.label[3] && aLang.label[1] == aSupportedLang.label[2] && aLang.label[2] == aSupportedLang.label[1] && aLang.label[3] == aSupportedLang.label[0]) #endif { maLang = aSupportedLang; break; } } if (i != gr_face_n_languages(pFace)) { if (mpSettings) gr_featureval_destroy(mpSettings); mpSettings = gr_face_featureval_for_lang(pFace, maLang.num); mnHash = maLang.num; } } if (!mpSettings) mpSettings = gr_face_featureval_for_lang(pFace, 0); } GrFeatureParser::~GrFeatureParser() { if (mpSettings) { gr_featureval_destroy(mpSettings); mpSettings = NULL; } } bool GrFeatureParser::isCharId(const rtl::OString & id, size_t offset, size_t length) { if (length > 4) return false; for (size_t i = 0; i < length; i++) { if (i > 0 && id[offset+i] == '\0') continue; if ((id[offset+i] < 0x20) || (id[offset+i] < 0)) return false; if (i==0 && (id[offset+i] < 0x41)) return false; } return true; } gr_uint32 GrFeatureParser::getCharId(const rtl::OString & id, size_t offset, size_t length) { FeatId charId; charId.num = 0; #ifdef WORDS_BIGENDIAN for (size_t i = 0; i < length; i++) { charId.label[i] = id[offset+i]; } #else for (size_t i = 0; i < length; i++) { charId.label[3-i] = id[offset+i]; } #endif return charId.num; } short GrFeatureParser::getIntValue(const rtl::OString & id, size_t offset, size_t length) { short value = 0; int sign = 1; for (size_t i = 0; i < length; i++) { switch (id[offset + i]) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value *= 10; if (sign < 0) { value = -(id[offset + i] - '0'); sign = 1; } value += (id[offset + i] - '0'); break; case '-': if (i == 0) sign = -1; else { mbErrors = true; break; } default: mbErrors = true; break; } } return value; } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
use OSL_BIGENDIAN
vcl: use OSL_BIGENDIAN Change-Id: Ifdf54d30cca94d0d65d78f94d5fac31edf8c6df2
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
921911de962ce3f594a0812f43e25e81821ddecf
TerrainSDK/vtui/AutoDialog.cpp
TerrainSDK/vtui/AutoDialog.cpp
// // Implements the following classes: // // AutoDialog - An improvement to wxDialog which makes validation easier. // // AutoPanel - An improvement to wxPanel which makes validation easier. // // wxNumericValidator - A validator capable of transfering numeric values. // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "AutoDialog.h" #include "wxString2.h" ///////////////////////////////////////////////// // wxNumericValidator::wxNumericValidator(int *val) : wxValidator() { Initialize(); m_pValInt = val; } wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator() { Initialize(); m_pValFloat = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator() { Initialize(); m_pValDouble = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(const wxNumericValidator& val) { Copy(val); } bool wxNumericValidator::Copy(const wxNumericValidator& val) { wxValidator::Copy(val); m_pValInt = val.m_pValInt; m_pValFloat = val.m_pValFloat; m_pValDouble = val.m_pValDouble; m_iDigits = val.m_iDigits; return TRUE; } // Called to transfer data to the window bool wxNumericValidator::TransferToWindow() { if ( !m_validatorWindow ) return FALSE; wxString str, format; if (m_pValInt) str.Printf(_T("%d"), *m_pValInt); if (m_pValFloat) { if (m_iDigits != -1) { format.Printf(_T("%%.%df"), m_iDigits); str.Printf(format, *m_pValFloat); } else str.Printf(_T("%.8g"), *m_pValFloat); } if (m_pValDouble) { if (m_iDigits != -1) { format.Printf(_T("%%.%dlf"), m_iDigits); str.Printf(format, *m_pValDouble); } else str.Printf(_T("%.16lg"), *m_pValDouble); } if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) { pControl->SetLabel(str) ; return TRUE; } } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) { pControl->SetValue(str) ; return TRUE; } } else return FALSE; // unrecognized control, or bad pointer return FALSE; } // Called to transfer data from the window bool wxNumericValidator::TransferFromWindow() { if ( !m_validatorWindow ) return FALSE; wxString2 str = _T(""); // string controls if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) str = pControl->GetLabel() ; } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) str = pControl->GetValue() ; } else // unrecognized control, or bad pointer return FALSE; if (str != _T("")) { const char *ccs = str.mb_str(); if (m_pValInt) sscanf(ccs, "%d", m_pValInt); if (m_pValFloat) sscanf(ccs, "%f", m_pValFloat); if (m_pValDouble) sscanf(ccs, "%lf", m_pValDouble); return TRUE; } return FALSE; } /* Called by constructors to initialize ALL data members */ void wxNumericValidator::Initialize() { m_pValInt = NULL; m_pValFloat = NULL; m_pValDouble = NULL; } ///////////////////////////////////////////////// // BEGIN_EVENT_TABLE(AutoDialog, wxDialog) EVT_INIT_DIALOG (AutoDialog::OnInitDialog) END_EVENT_TABLE() void AutoDialog::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(sptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(bptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoDialog::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(fptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoDialog::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(dptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } ///////////////////////////////////////////////// // BEGIN_EVENT_TABLE(AutoPanel, wxPanel) EVT_INIT_DIALOG (AutoPanel::OnInitDialog) END_EVENT_TABLE() void AutoPanel::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(sptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(bptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoPanel::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(fptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoPanel::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(dptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } }
// // Implements the following classes: // // AutoDialog - An improvement to wxDialog which makes validation easier. // // AutoPanel - An improvement to wxPanel which makes validation easier. // // wxNumericValidator - A validator capable of transfering numeric values. // // Copyright (c) 2001-2003 Virtual Terrain Project // Free for all uses, see license.txt for details. // #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/wx.h" #endif #include "AutoDialog.h" #include "wxString2.h" ///////////////////////////////////////////////// // wxNumericValidator::wxNumericValidator(int *val) : wxValidator() { Initialize(); m_pValInt = val; } wxNumericValidator::wxNumericValidator(float *val, int digits) : wxValidator() { Initialize(); m_pValFloat = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(double *val, int digits) : wxValidator() { Initialize(); m_pValDouble = val; m_iDigits = digits; } wxNumericValidator::wxNumericValidator(const wxNumericValidator& val) { Copy(val); } bool wxNumericValidator::Copy(const wxNumericValidator& val) { wxValidator::Copy(val); m_pValInt = val.m_pValInt; m_pValFloat = val.m_pValFloat; m_pValDouble = val.m_pValDouble; m_iDigits = val.m_iDigits; return TRUE; } // Called to transfer data to the window bool wxNumericValidator::TransferToWindow() { if ( !m_validatorWindow ) return FALSE; wxString str, format; if (m_pValInt) str.Printf(_T("%d"), *m_pValInt); if (m_pValFloat) { if (m_iDigits != -1) { format.Printf(_T("%%.%df"), m_iDigits); str.Printf(format, *m_pValFloat); } else str.Printf(_T("%.8g"), *m_pValFloat); // 8 significant digits } if (m_pValDouble) { if (m_iDigits != -1) { format.Printf(_T("%%.%dlf"), m_iDigits); str.Printf(format, *m_pValDouble); } else str.Printf(_T("%.16lg"), *m_pValDouble); // 16 significant digits } if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) { pControl->SetLabel(str) ; return TRUE; } } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) { pControl->SetValue(str) ; return TRUE; } } else return FALSE; // unrecognized control, or bad pointer return FALSE; } // Called to transfer data from the window bool wxNumericValidator::TransferFromWindow() { if ( !m_validatorWindow ) return FALSE; wxString2 str = _T(""); // string controls if (m_validatorWindow->IsKindOf(CLASSINFO(wxStaticText)) ) { wxStaticText* pControl = (wxStaticText*) m_validatorWindow; if (pControl) str = pControl->GetLabel() ; } else if (m_validatorWindow->IsKindOf(CLASSINFO(wxTextCtrl)) ) { wxTextCtrl* pControl = (wxTextCtrl*) m_validatorWindow; if (pControl) str = pControl->GetValue() ; } else // unrecognized control, or bad pointer return FALSE; if (str != _T("")) { const char *ccs = str.mb_str(); if (m_pValInt) sscanf(ccs, "%d", m_pValInt); if (m_pValFloat) sscanf(ccs, "%f", m_pValFloat); if (m_pValDouble) sscanf(ccs, "%lf", m_pValDouble); return TRUE; } return FALSE; } /* Called by constructors to initialize ALL data members */ void wxNumericValidator::Initialize() { m_pValInt = NULL; m_pValFloat = NULL; m_pValDouble = NULL; } ///////////////////////////////////////////////// // BEGIN_EVENT_TABLE(AutoDialog, wxDialog) EVT_INIT_DIALOG (AutoDialog::OnInitDialog) END_EVENT_TABLE() void AutoDialog::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(sptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(bptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoDialog::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoDialog::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(fptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoDialog::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(dptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } ///////////////////////////////////////////////// // BEGIN_EVENT_TABLE(AutoPanel, wxPanel) EVT_INIT_DIALOG (AutoPanel::OnInitDialog) END_EVENT_TABLE() void AutoPanel::AddValidator(long id, wxString *sptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(sptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddValidator(long id, bool *bptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(bptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (!pWin) return; wxGenericValidator *gv = new wxGenericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } void AutoPanel::AddNumValidator(long id, int *iptr) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(iptr); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoPanel::AddNumValidator(long id, float *fptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(fptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } } void AutoPanel::AddNumValidator(long id, double *dptr, int digits) { wxWindow *pWin = FindWindow(id); if (pWin) { wxNumericValidator *gv = new wxNumericValidator(dptr, digits); pWin->SetValidator(*gv); // actually clones the one we pass in delete gv; } }
comment tweak
comment tweak
C++
mit
nakijun/vtp,markraz/vtp,nakijun/vtp,seanisom/vtp,seanisom/vtp,seanisom/vtp,seanisom/vtp,markraz/vtp,markraz/vtp,markraz/vtp,nakijun/vtp,nakijun/vtp,seanisom/vtp,nakijun/vtp,markraz/vtp
e8bf798b52cee12da68d1168e176e845161c8418
atom/browser/api/atom_api_window.cc
atom/browser/api/atom_api_window.cc
// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_window.h" #include "atom/browser/native_window.h" #include "atom/common/native_mate_converters/function_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/bind.h" #include "base/callback.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/render_process_host.h" #include "native_mate/constructor.h" #include "native_mate/dictionary.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" #include "atom/common/node_includes.h" using content::NavigationController; namespace mate { template<> struct Converter<gfx::Rect> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, gfx::Rect* out) { if (!val->IsObject()) return false; mate::Dictionary dict(isolate, val->ToObject()); int x, y, width, height; if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) || !dict.Get("height", &height)) return false; *out = gfx::Rect(x, y, width, height); return true; } }; } // namespace mate namespace atom { namespace api { namespace { void OnCapturePageDone( const base::Callback<void(v8::Handle<v8::Value>)>& callback, const std::vector<unsigned char>& data) { v8::Locker locker(node_isolate); v8::HandleScope handle_scope(node_isolate); v8::Local<v8::Value> buffer = node::Buffer::New( reinterpret_cast<const char*>(data.data()), data.size()); callback.Run(buffer); } } // namespace Window::Window(base::DictionaryValue* options) : window_(NativeWindow::Create(options)) { window_->InitFromOptions(options); window_->AddObserver(this); } Window::~Window() { if (window_) Destroy(); Emit("destroyed"); } void Window::OnPageTitleUpdated(bool* prevent_default, const std::string& title) { base::ListValue args; args.AppendString(title); *prevent_default = Emit("page-title-updated", args); } void Window::OnLoadingStateChanged(bool is_loading) { base::ListValue args; args.AppendBoolean(is_loading); Emit("loading-state-changed", args); } void Window::WillCloseWindow(bool* prevent_default) { *prevent_default = Emit("close"); } void Window::OnWindowClosed() { Emit("closed"); window_->RemoveObserver(this); } void Window::OnWindowBlur() { Emit("blur"); } void Window::OnRendererUnresponsive() { Emit("unresponsive"); } void Window::OnRendererResponsive() { Emit("responsive"); } void Window::OnRenderViewDeleted(int process_id, int routing_id) { base::ListValue args; args.AppendInteger(process_id); args.AppendInteger(routing_id); Emit("render-view-deleted", args); } void Window::OnRendererCrashed() { Emit("crashed"); } // static mate::Wrappable* Window::New(mate::Arguments* args, const base::DictionaryValue& options) { scoped_ptr<base::DictionaryValue> copied_options(options.DeepCopy()); Window* window = new Window(copied_options.get()); window->Wrap(args->isolate(), args->GetThis()); // Give js code a chance to do initialization. node::MakeCallback(args->GetThis(), "_init", 0, NULL); return window; } void Window::Destroy() { window_->DestroyWebContents(); window_->CloseImmediately(); } void Window::Close() { window_->Close(); } void Window::Focus() { window_->Focus(true); } bool Window::IsFocused() { return window_->IsFocused(); } void Window::Show() { window_->Show(); } void Window::Hide() { window_->Hide(); } bool Window::IsVisible() { return window_->IsVisible(); } void Window::Maximize() { window_->Maximize(); } void Window::Unmaximize() { window_->Unmaximize(); } void Window::Minimize() { window_->Minimize(); } void Window::Restore() { window_->Restore(); } void Window::SetFullscreen(bool fullscreen) { window_->SetFullscreen(fullscreen); } bool Window::IsFullscreen() { return window_->IsFullscreen(); } void Window::SetSize(int width, int height) { window_->SetSize(gfx::Size(width, height)); } std::vector<int> Window::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> Window::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> Window::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool Window::IsResizable() { return window_->IsResizable(); } void Window::SetAlwaysOnTop(bool top) { window_->SetAlwaysOnTop(top); } bool Window::IsAlwaysOnTop() { return window_->IsAlwaysOnTop(); } void Window::Center() { window_->Center(); } void Window::SetPosition(int x, int y) { window_->SetPosition(gfx::Point(x, y)); } std::vector<int> Window::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void Window::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string Window::GetTitle() { return window_->GetTitle(); } void Window::FlashFrame(bool flash) { window_->FlashFrame(flash); } void Window::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool Window::IsKiosk() { return window_->IsKiosk(); } void Window::OpenDevTools() { window_->OpenDevTools(); } void Window::CloseDevTools() { window_->CloseDevTools(); } bool Window::IsDevToolsOpened() { return window_->IsDevToolsOpened(); } void Window::InspectElement(int x, int y) { window_->InspectElement(x, y); } void Window::DebugDevTools() { if (window_->IsDevToolsOpened()) NativeWindow::Debug(window_->GetDevToolsWebContents()); } void Window::FocusOnWebView() { window_->FocusOnWebView(); } void Window::BlurWebView() { window_->BlurWebView(); } bool Window::IsWebViewFocused() { return window_->IsWebViewFocused(); } void Window::CapturePage(mate::Arguments* args) { gfx::Rect rect; base::Callback<void(v8::Handle<v8::Value>)> callback; if (!(args->Length() == 1 && args->GetNext(&callback)) && !(args->Length() == 2 && args->GetNext(&rect) && args->GetNext(&callback))) { args->ThrowError(); return; } window_->CapturePage(rect, base::Bind(&OnCapturePageDone, callback)); } string16 Window::GetPageTitle() { return window_->GetWebContents()->GetTitle(); } bool Window::IsLoading() { return window_->GetWebContents()->IsLoading(); } bool Window::IsWaitingForResponse() { return window_->GetWebContents()->IsWaitingForResponse(); } void Window::Stop() { window_->GetWebContents()->Stop(); } int Window::GetRoutingID() { return window_->GetWebContents()->GetRoutingID(); } int Window::GetProcessID() { return window_->GetWebContents()->GetRenderProcessHost()->GetID(); } bool Window::IsCrashed() { return window_->GetWebContents()->IsCrashed(); } mate::Dictionary Window::GetDevTools(v8::Isolate* isolate) { content::WebContents* web_contents = window_->GetDevToolsWebContents(); mate::Dictionary dict(isolate); dict.Set("processId", web_contents->GetRenderProcessHost()->GetID()); dict.Set("routingId", web_contents->GetRoutingID()); return dict; } void Window::ExecuteJavaScriptInDevTools(const std::string& code) { window_->ExecuteJavaScriptInDevTools(code); } void Window::LoadURL(const GURL& url) { NavigationController& controller = window_->GetWebContents()->GetController(); content::NavigationController::LoadURLParams params(url); params.transition_type = content::PAGE_TRANSITION_TYPED; params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; controller.LoadURLWithParams(params); } GURL Window::GetURL() { NavigationController& controller = window_->GetWebContents()->GetController(); if (!controller.GetActiveEntry()) return GURL(); return controller.GetActiveEntry()->GetVirtualURL(); } bool Window::CanGoBack() { return window_->GetWebContents()->GetController().CanGoBack(); } bool Window::CanGoForward() { return window_->GetWebContents()->GetController().CanGoForward(); } bool Window::CanGoToOffset(int offset) { return window_->GetWebContents()->GetController().CanGoToOffset(offset); } void Window::GoBack() { window_->GetWebContents()->GetController().GoBack(); } void Window::GoForward() { window_->GetWebContents()->GetController().GoForward(); } void Window::GoToIndex(int index) { window_->GetWebContents()->GetController().GoToIndex(index); } void Window::GoToOffset(int offset) { window_->GetWebContents()->GetController().GoToOffset(offset); } void Window::Reload() { window_->GetWebContents()->GetController().Reload(false); } void Window::ReloadIgnoringCache() { window_->GetWebContents()->GetController().ReloadIgnoringCache(false); } // static void Window::BuildPrototype(v8::Isolate* isolate, v8::Handle<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("destroy", &Window::Destroy) .SetMethod("close", &Window::Close) .SetMethod("focus", &Window::Focus) .SetMethod("isFocused", &Window::IsFocused) .SetMethod("show", &Window::Show) .SetMethod("hide", &Window::Hide) .SetMethod("isVisible", &Window::IsVisible) .SetMethod("maximize", &Window::Maximize) .SetMethod("unmaximize", &Window::Unmaximize) .SetMethod("minimize", &Window::Minimize) .SetMethod("restore", &Window::Restore) .SetMethod("setFullScreen", &Window::SetFullscreen) .SetMethod("isFullScreen", &Window::IsFullscreen) .SetMethod("getSize", &Window::GetSize) .SetMethod("setSize", &Window::SetSize) .SetMethod("setMinimumSize", &Window::SetMinimumSize) .SetMethod("getMinimumSize", &Window::GetMinimumSize) .SetMethod("setMaximumSize", &Window::SetMaximumSize) .SetMethod("getMaximumSize", &Window::GetMaximumSize) .SetMethod("setResizable", &Window::SetResizable) .SetMethod("isResizable", &Window::IsResizable) .SetMethod("setAlwaysOnTop", &Window::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &Window::IsAlwaysOnTop) .SetMethod("center", &Window::Center) .SetMethod("setPosition", &Window::SetPosition) .SetMethod("getPosition", &Window::GetPosition) .SetMethod("setTitle", &Window::SetTitle) .SetMethod("getTitle", &Window::GetTitle) .SetMethod("flashFrame", &Window::FlashFrame) .SetMethod("setKiosk", &Window::SetKiosk) .SetMethod("isKiosk", &Window::IsKiosk) .SetMethod("openDevTools", &Window::OpenDevTools) .SetMethod("closeDevTools", &Window::CloseDevTools) .SetMethod("isDevToolsOpened", &Window::IsDevToolsOpened) .SetMethod("inspectElement", &Window::InspectElement) .SetMethod("debugDevTools", &Window::DebugDevTools) .SetMethod("focusOnWebView", &Window::FocusOnWebView) .SetMethod("blurWebView", &Window::BlurWebView) .SetMethod("isWebViewFocused", &Window::IsWebViewFocused) .SetMethod("capturePage", &Window::CapturePage) .SetMethod("getPageTitle", &Window::GetPageTitle) .SetMethod("isLoading", &Window::IsLoading) .SetMethod("isWaitingForResponse", &Window::IsWaitingForResponse) .SetMethod("stop", &Window::Stop) .SetMethod("getRoutingId", &Window::GetRoutingID) .SetMethod("getProcessId", &Window::GetProcessID) .SetMethod("isCrashed", &Window::IsCrashed) .SetMethod("getDevTools", &Window::GetDevTools) .SetMethod("executeJavaScriptInDevTools", &Window::ExecuteJavaScriptInDevTools) .SetMethod("loadUrl", &Window::LoadURL) .SetMethod("getUrl", &Window::GetURL) .SetMethod("canGoBack", &Window::CanGoBack) .SetMethod("canGoForward", &Window::CanGoForward) .SetMethod("canGoToOffset", &Window::CanGoToOffset) .SetMethod("goBack", &Window::GoBack) .SetMethod("goForward", &Window::GoForward) .SetMethod("goToIndex", &Window::GoToIndex) .SetMethod("goToOffset", &Window::GoToOffset) .SetMethod("reload", &Window::Reload) .SetMethod("reloadIgnoringCache", &Window::ReloadIgnoringCache); } } // namespace api } // namespace atom namespace { void Initialize(v8::Handle<v8::Object> exports) { using atom::api::Window; v8::Local<v8::Function> constructor = mate::CreateConstructor<Window>( node_isolate, "BrowserWindow", base::Bind(&Window::New)); mate::Dictionary dict(v8::Isolate::GetCurrent(), exports); dict.Set("BrowserWindow", static_cast<v8::Handle<v8::Value>>(constructor)); } } // namespace NODE_MODULE(atom_browser_window, Initialize)
// Copyright (c) 2013 GitHub, Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "atom/browser/api/atom_api_window.h" #include "atom/browser/native_window.h" #include "atom/common/native_mate_converters/function_converter.h" #include "atom/common/native_mate_converters/gurl_converter.h" #include "atom/common/native_mate_converters/string16_converter.h" #include "atom/common/native_mate_converters/value_converter.h" #include "base/bind.h" #include "base/callback.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/web_contents.h" #include "content/public/browser/render_process_host.h" #include "native_mate/constructor.h" #include "native_mate/dictionary.h" #include "ui/gfx/point.h" #include "ui/gfx/rect.h" #include "ui/gfx/size.h" #include "atom/common/node_includes.h" using content::NavigationController; namespace mate { template<> struct Converter<gfx::Rect> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, gfx::Rect* out) { if (!val->IsObject()) return false; mate::Dictionary dict(isolate, val->ToObject()); int x, y, width, height; if (!dict.Get("x", &x) || !dict.Get("y", &y) || !dict.Get("width", &width) || !dict.Get("height", &height)) return false; *out = gfx::Rect(x, y, width, height); return true; } }; } // namespace mate namespace atom { namespace api { namespace { void OnCapturePageDone( const base::Callback<void(v8::Handle<v8::Value>)>& callback, const std::vector<unsigned char>& data) { v8::Locker locker(node_isolate); v8::HandleScope handle_scope(node_isolate); v8::Local<v8::Value> buffer = node::Buffer::New( reinterpret_cast<const char*>(data.data()), data.size()); callback.Run(buffer); } } // namespace Window::Window(base::DictionaryValue* options) : window_(NativeWindow::Create(options)) { window_->InitFromOptions(options); window_->AddObserver(this); } Window::~Window() { if (window_) Destroy(); Emit("destroyed"); } void Window::OnPageTitleUpdated(bool* prevent_default, const std::string& title) { base::ListValue args; args.AppendString(title); *prevent_default = Emit("page-title-updated", args); } void Window::OnLoadingStateChanged(bool is_loading) { base::ListValue args; args.AppendBoolean(is_loading); Emit("loading-state-changed", args); } void Window::WillCloseWindow(bool* prevent_default) { *prevent_default = Emit("close"); } void Window::OnWindowClosed() { Emit("closed"); window_->RemoveObserver(this); } void Window::OnWindowBlur() { Emit("blur"); } void Window::OnRendererUnresponsive() { Emit("unresponsive"); } void Window::OnRendererResponsive() { Emit("responsive"); } void Window::OnRenderViewDeleted(int process_id, int routing_id) { base::ListValue args; args.AppendInteger(process_id); args.AppendInteger(routing_id); Emit("render-view-deleted", args); } void Window::OnRendererCrashed() { Emit("crashed"); } // static mate::Wrappable* Window::New(mate::Arguments* args, const base::DictionaryValue& options) { scoped_ptr<base::DictionaryValue> copied_options(options.DeepCopy()); Window* window = new Window(copied_options.get()); window->Wrap(args->isolate(), args->GetThis()); // Give js code a chance to do initialization. node::MakeCallback(args->GetThis(), "_init", 0, NULL); return window; } void Window::Destroy() { window_->DestroyWebContents(); window_->CloseImmediately(); } void Window::Close() { window_->Close(); } void Window::Focus() { window_->Focus(true); } bool Window::IsFocused() { return window_->IsFocused(); } void Window::Show() { window_->Show(); } void Window::Hide() { window_->Hide(); } bool Window::IsVisible() { return window_->IsVisible(); } void Window::Maximize() { window_->Maximize(); } void Window::Unmaximize() { window_->Unmaximize(); } void Window::Minimize() { window_->Minimize(); } void Window::Restore() { window_->Restore(); } void Window::SetFullscreen(bool fullscreen) { window_->SetFullscreen(fullscreen); } bool Window::IsFullscreen() { return window_->IsFullscreen(); } void Window::SetSize(int width, int height) { window_->SetSize(gfx::Size(width, height)); } std::vector<int> Window::GetSize() { std::vector<int> result(2); gfx::Size size = window_->GetSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetMinimumSize(int width, int height) { window_->SetMinimumSize(gfx::Size(width, height)); } std::vector<int> Window::GetMinimumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMinimumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetMaximumSize(int width, int height) { window_->SetMaximumSize(gfx::Size(width, height)); } std::vector<int> Window::GetMaximumSize() { std::vector<int> result(2); gfx::Size size = window_->GetMaximumSize(); result[0] = size.width(); result[1] = size.height(); return result; } void Window::SetResizable(bool resizable) { window_->SetResizable(resizable); } bool Window::IsResizable() { return window_->IsResizable(); } void Window::SetAlwaysOnTop(bool top) { window_->SetAlwaysOnTop(top); } bool Window::IsAlwaysOnTop() { return window_->IsAlwaysOnTop(); } void Window::Center() { window_->Center(); } void Window::SetPosition(int x, int y) { window_->SetPosition(gfx::Point(x, y)); } std::vector<int> Window::GetPosition() { std::vector<int> result(2); gfx::Point pos = window_->GetPosition(); result[0] = pos.x(); result[1] = pos.y(); return result; } void Window::SetTitle(const std::string& title) { window_->SetTitle(title); } std::string Window::GetTitle() { return window_->GetTitle(); } void Window::FlashFrame(bool flash) { window_->FlashFrame(flash); } void Window::SetKiosk(bool kiosk) { window_->SetKiosk(kiosk); } bool Window::IsKiosk() { return window_->IsKiosk(); } void Window::OpenDevTools() { window_->OpenDevTools(); } void Window::CloseDevTools() { window_->CloseDevTools(); } bool Window::IsDevToolsOpened() { return window_->IsDevToolsOpened(); } void Window::InspectElement(int x, int y) { window_->InspectElement(x, y); } void Window::DebugDevTools() { if (window_->IsDevToolsOpened()) NativeWindow::Debug(window_->GetDevToolsWebContents()); } void Window::FocusOnWebView() { window_->FocusOnWebView(); } void Window::BlurWebView() { window_->BlurWebView(); } bool Window::IsWebViewFocused() { return window_->IsWebViewFocused(); } void Window::CapturePage(mate::Arguments* args) { gfx::Rect rect; base::Callback<void(v8::Handle<v8::Value>)> callback; if (!(args->Length() == 1 && args->GetNext(&callback)) && !(args->Length() == 2 && args->GetNext(&rect) && args->GetNext(&callback))) { args->ThrowError(); return; } window_->CapturePage(rect, base::Bind(&OnCapturePageDone, callback)); } string16 Window::GetPageTitle() { return window_->GetWebContents()->GetTitle(); } bool Window::IsLoading() { return window_->GetWebContents()->IsLoading(); } bool Window::IsWaitingForResponse() { return window_->GetWebContents()->IsWaitingForResponse(); } void Window::Stop() { window_->GetWebContents()->Stop(); } int Window::GetRoutingID() { return window_->GetWebContents()->GetRoutingID(); } int Window::GetProcessID() { return window_->GetWebContents()->GetRenderProcessHost()->GetID(); } bool Window::IsCrashed() { return window_->GetWebContents()->IsCrashed(); } mate::Dictionary Window::GetDevTools(v8::Isolate* isolate) { mate::Dictionary dict(mate::Dictionary::CreateEmpty(isolate)); content::WebContents* web_contents = window_->GetDevToolsWebContents(); dict.Set("processId", web_contents->GetRenderProcessHost()->GetID()); dict.Set("routingId", web_contents->GetRoutingID()); return dict; } void Window::ExecuteJavaScriptInDevTools(const std::string& code) { window_->ExecuteJavaScriptInDevTools(code); } void Window::LoadURL(const GURL& url) { NavigationController& controller = window_->GetWebContents()->GetController(); content::NavigationController::LoadURLParams params(url); params.transition_type = content::PAGE_TRANSITION_TYPED; params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; controller.LoadURLWithParams(params); } GURL Window::GetURL() { NavigationController& controller = window_->GetWebContents()->GetController(); if (!controller.GetActiveEntry()) return GURL(); return controller.GetActiveEntry()->GetVirtualURL(); } bool Window::CanGoBack() { return window_->GetWebContents()->GetController().CanGoBack(); } bool Window::CanGoForward() { return window_->GetWebContents()->GetController().CanGoForward(); } bool Window::CanGoToOffset(int offset) { return window_->GetWebContents()->GetController().CanGoToOffset(offset); } void Window::GoBack() { window_->GetWebContents()->GetController().GoBack(); } void Window::GoForward() { window_->GetWebContents()->GetController().GoForward(); } void Window::GoToIndex(int index) { window_->GetWebContents()->GetController().GoToIndex(index); } void Window::GoToOffset(int offset) { window_->GetWebContents()->GetController().GoToOffset(offset); } void Window::Reload() { window_->GetWebContents()->GetController().Reload(false); } void Window::ReloadIgnoringCache() { window_->GetWebContents()->GetController().ReloadIgnoringCache(false); } // static void Window::BuildPrototype(v8::Isolate* isolate, v8::Handle<v8::ObjectTemplate> prototype) { mate::ObjectTemplateBuilder(isolate, prototype) .SetMethod("destroy", &Window::Destroy) .SetMethod("close", &Window::Close) .SetMethod("focus", &Window::Focus) .SetMethod("isFocused", &Window::IsFocused) .SetMethod("show", &Window::Show) .SetMethod("hide", &Window::Hide) .SetMethod("isVisible", &Window::IsVisible) .SetMethod("maximize", &Window::Maximize) .SetMethod("unmaximize", &Window::Unmaximize) .SetMethod("minimize", &Window::Minimize) .SetMethod("restore", &Window::Restore) .SetMethod("setFullScreen", &Window::SetFullscreen) .SetMethod("isFullScreen", &Window::IsFullscreen) .SetMethod("getSize", &Window::GetSize) .SetMethod("setSize", &Window::SetSize) .SetMethod("setMinimumSize", &Window::SetMinimumSize) .SetMethod("getMinimumSize", &Window::GetMinimumSize) .SetMethod("setMaximumSize", &Window::SetMaximumSize) .SetMethod("getMaximumSize", &Window::GetMaximumSize) .SetMethod("setResizable", &Window::SetResizable) .SetMethod("isResizable", &Window::IsResizable) .SetMethod("setAlwaysOnTop", &Window::SetAlwaysOnTop) .SetMethod("isAlwaysOnTop", &Window::IsAlwaysOnTop) .SetMethod("center", &Window::Center) .SetMethod("setPosition", &Window::SetPosition) .SetMethod("getPosition", &Window::GetPosition) .SetMethod("setTitle", &Window::SetTitle) .SetMethod("getTitle", &Window::GetTitle) .SetMethod("flashFrame", &Window::FlashFrame) .SetMethod("setKiosk", &Window::SetKiosk) .SetMethod("isKiosk", &Window::IsKiosk) .SetMethod("openDevTools", &Window::OpenDevTools) .SetMethod("closeDevTools", &Window::CloseDevTools) .SetMethod("isDevToolsOpened", &Window::IsDevToolsOpened) .SetMethod("inspectElement", &Window::InspectElement) .SetMethod("debugDevTools", &Window::DebugDevTools) .SetMethod("focusOnWebView", &Window::FocusOnWebView) .SetMethod("blurWebView", &Window::BlurWebView) .SetMethod("isWebViewFocused", &Window::IsWebViewFocused) .SetMethod("capturePage", &Window::CapturePage) .SetMethod("getPageTitle", &Window::GetPageTitle) .SetMethod("isLoading", &Window::IsLoading) .SetMethod("isWaitingForResponse", &Window::IsWaitingForResponse) .SetMethod("stop", &Window::Stop) .SetMethod("getRoutingId", &Window::GetRoutingID) .SetMethod("getProcessId", &Window::GetProcessID) .SetMethod("isCrashed", &Window::IsCrashed) .SetMethod("getDevTools", &Window::GetDevTools) .SetMethod("executeJavaScriptInDevTools", &Window::ExecuteJavaScriptInDevTools) .SetMethod("loadUrl", &Window::LoadURL) .SetMethod("getUrl", &Window::GetURL) .SetMethod("canGoBack", &Window::CanGoBack) .SetMethod("canGoForward", &Window::CanGoForward) .SetMethod("canGoToOffset", &Window::CanGoToOffset) .SetMethod("goBack", &Window::GoBack) .SetMethod("goForward", &Window::GoForward) .SetMethod("goToIndex", &Window::GoToIndex) .SetMethod("goToOffset", &Window::GoToOffset) .SetMethod("reload", &Window::Reload) .SetMethod("reloadIgnoringCache", &Window::ReloadIgnoringCache); } } // namespace api } // namespace atom namespace { void Initialize(v8::Handle<v8::Object> exports) { using atom::api::Window; v8::Local<v8::Function> constructor = mate::CreateConstructor<Window>( node_isolate, "BrowserWindow", base::Bind(&Window::New)); mate::Dictionary dict(v8::Isolate::GetCurrent(), exports); dict.Set("BrowserWindow", static_cast<v8::Handle<v8::Value>>(constructor)); } } // namespace NODE_MODULE(atom_browser_window, Initialize)
Fix using an null dictionary.
Fix using an null dictionary.
C++
mit
cqqccqc/electron,preco21/electron,kokdemo/electron,trankmichael/electron,nicobot/electron,RobertJGabriel/electron,aichingm/electron,bruce/electron,aaron-goshine/electron,JussMee15/electron,arusakov/electron,joneit/electron,gstack/infinium-shell,stevekinney/electron,smczk/electron,ianscrivener/electron,kokdemo/electron,mrwizard82d1/electron,Neron-X5/electron,JesselJohn/electron,dongjoon-hyun/electron,xfstudio/electron,sircharleswatson/electron,edulan/electron,seanchas116/electron,shennushi/electron,nekuz0r/electron,mhkeller/electron,nicobot/electron,RobertJGabriel/electron,timruffles/electron,joaomoreno/atom-shell,anko/electron,zhakui/electron,LadyNaggaga/electron,joneit/electron,brave/muon,jsutcodes/electron,cos2004/electron,arturts/electron,synaptek/electron,egoist/electron,jaanus/electron,rprichard/electron,pandoraui/electron,arusakov/electron,shennushi/electron,bwiggs/electron,jlhbaseball15/electron,nicholasess/electron,yalexx/electron,gabriel/electron,smczk/electron,d-salas/electron,tinydew4/electron,posix4e/electron,d-salas/electron,jonatasfreitasv/electron,michaelchiche/electron,Rokt33r/electron,electron/electron,Andrey-Pavlov/electron,darwin/electron,arturts/electron,JussMee15/electron,mjaniszew/electron,MaxGraey/electron,christian-bromann/electron,egoist/electron,kokdemo/electron,yalexx/electron,abhishekgahlot/electron,JesselJohn/electron,sshiting/electron,bbondy/electron,preco21/electron,setzer777/electron,gerhardberger/electron,wan-qy/electron,renaesop/electron,leethomas/electron,RobertJGabriel/electron,mrwizard82d1/electron,darwin/electron,bright-sparks/electron,webmechanicx/electron,cqqccqc/electron,egoist/electron,systembugtj/electron,hokein/atom-shell,sshiting/electron,jonatasfreitasv/electron,mirrh/electron,mubassirhayat/electron,bbondy/electron,vipulroxx/electron,mattdesl/electron,wolfflow/electron,christian-bromann/electron,edulan/electron,xfstudio/electron,roadev/electron,medixdev/electron,yalexx/electron,Jacobichou/electron,brave/electron,soulteary/electron,stevekinney/electron,tonyganch/electron,leftstick/electron,fffej/electron,carsonmcdonald/electron,jtburke/electron,d-salas/electron,mattdesl/electron,jtburke/electron,gbn972/electron,michaelchiche/electron,arturts/electron,simonfork/electron,faizalpribadi/electron,SufianHassan/electron,cqqccqc/electron,tomashanacek/electron,digideskio/electron,gstack/infinium-shell,benweissmann/electron,JussMee15/electron,tincan24/electron,thompsonemerson/electron,robinvandernoord/electron,stevekinney/electron,tincan24/electron,mirrh/electron,Evercoder/electron,coderhaoxin/electron,edulan/electron,mjaniszew/electron,subblue/electron,kazupon/electron,the-ress/electron,jannishuebl/electron,rhencke/electron,sky7sea/electron,farmisen/electron,biblerule/UMCTelnetHub,shaundunne/electron,joneit/electron,micalan/electron,shockone/electron,darwin/electron,voidbridge/electron,joneit/electron,rprichard/electron,miniak/electron,howmuchcomputer/electron,jannishuebl/electron,chrisswk/electron,michaelchiche/electron,cos2004/electron,GoooIce/electron,vHanda/electron,trankmichael/electron,adamjgray/electron,jlord/electron,kikong/electron,mubassirhayat/electron,lrlna/electron,bwiggs/electron,thingsinjars/electron,natgolov/electron,biblerule/UMCTelnetHub,mrwizard82d1/electron,Neron-X5/electron,ervinb/electron,michaelchiche/electron,gabriel/electron,xfstudio/electron,howmuchcomputer/electron,greyhwndz/electron,aecca/electron,fomojola/electron,chriskdon/electron,pandoraui/electron,nagyistoce/electron-atom-shell,d-salas/electron,aliib/electron,rreimann/electron,biblerule/UMCTelnetHub,baiwyc119/electron,kostia/electron,posix4e/electron,jonatasfreitasv/electron,jaanus/electron,Ivshti/electron,RIAEvangelist/electron,shiftkey/electron,DivyaKMenon/electron,tincan24/electron,oiledCode/electron,joneit/electron,tylergibson/electron,Zagorakiss/electron,yalexx/electron,lrlna/electron,DivyaKMenon/electron,neutrous/electron,trigrass2/electron,simonfork/electron,fireball-x/atom-shell,gamedevsam/electron,brenca/electron,jhen0409/electron,the-ress/electron,sshiting/electron,Ivshti/electron,subblue/electron,miniak/electron,the-ress/electron,neutrous/electron,bright-sparks/electron,Rokt33r/electron,tylergibson/electron,posix4e/electron,deed02392/electron,brave/muon,kcrt/electron,evgenyzinoviev/electron,Zagorakiss/electron,Gerhut/electron,kazupon/electron,Jacobichou/electron,arusakov/electron,simongregory/electron,evgenyzinoviev/electron,smczk/electron,dongjoon-hyun/electron,Floato/electron,SufianHassan/electron,mjaniszew/electron,mrwizard82d1/electron,Ivshti/electron,Faiz7412/electron,jcblw/electron,webmechanicx/electron,evgenyzinoviev/electron,trigrass2/electron,vHanda/electron,RIAEvangelist/electron,destan/electron,lzpfmh/electron,John-Lin/electron,synaptek/electron,icattlecoder/electron,robinvandernoord/electron,setzer777/electron,thomsonreuters/electron,bruce/electron,baiwyc119/electron,subblue/electron,aecca/electron,bobwol/electron,mattotodd/electron,jsutcodes/electron,xfstudio/electron,Jacobichou/electron,gbn972/electron,astoilkov/electron,Jonekee/electron,benweissmann/electron,Jacobichou/electron,hokein/atom-shell,shockone/electron,jlord/electron,twolfson/electron,astoilkov/electron,icattlecoder/electron,dongjoon-hyun/electron,bbondy/electron,rajatsingla28/electron,Faiz7412/electron,mirrh/electron,vHanda/electron,mattdesl/electron,jlhbaseball15/electron,wolfflow/electron,soulteary/electron,sshiting/electron,noikiy/electron,icattlecoder/electron,lzpfmh/electron,medixdev/electron,webmechanicx/electron,LadyNaggaga/electron,tomashanacek/electron,howmuchcomputer/electron,bright-sparks/electron,abhishekgahlot/electron,nekuz0r/electron,arusakov/electron,bright-sparks/electron,subblue/electron,thomsonreuters/electron,tylergibson/electron,JussMee15/electron,nicholasess/electron,kokdemo/electron,jjz/electron,takashi/electron,kenmozi/electron,rhencke/electron,anko/electron,miniak/electron,aliib/electron,electron/electron,vipulroxx/electron,arturts/electron,gabrielPeart/electron,BionicClick/electron,deed02392/electron,neutrous/electron,twolfson/electron,fffej/electron,beni55/electron,Gerhut/electron,gstack/infinium-shell,JesselJohn/electron,gabriel/electron,MaxGraey/electron,shaundunne/electron,thompsonemerson/electron,synaptek/electron,timruffles/electron,destan/electron,gamedevsam/electron,anko/electron,dahal/electron,zhakui/electron,rsvip/electron,aecca/electron,bbondy/electron,bpasero/electron,anko/electron,christian-bromann/electron,yan-foto/electron,xfstudio/electron,the-ress/electron,nicobot/electron,ankitaggarwal011/electron,shiftkey/electron,xiruibing/electron,John-Lin/electron,fritx/electron,aichingm/electron,abhishekgahlot/electron,xiruibing/electron,eriser/electron,gabrielPeart/electron,John-Lin/electron,maxogden/atom-shell,pirafrank/electron,xfstudio/electron,destan/electron,etiktin/electron,BionicClick/electron,mattotodd/electron,gerhardberger/electron,noikiy/electron,leethomas/electron,lzpfmh/electron,darwin/electron,John-Lin/electron,jannishuebl/electron,jjz/electron,jannishuebl/electron,kokdemo/electron,Neron-X5/electron,fomojola/electron,joaomoreno/atom-shell,jhen0409/electron,aliib/electron,fireball-x/atom-shell,timruffles/electron,pandoraui/electron,the-ress/electron,aichingm/electron,preco21/electron,felixrieseberg/electron,posix4e/electron,yan-foto/electron,aecca/electron,Evercoder/electron,shaundunne/electron,ianscrivener/electron,jtburke/electron,minggo/electron,GoooIce/electron,roadev/electron,bwiggs/electron,mjaniszew/electron,mubassirhayat/electron,mirrh/electron,abhishekgahlot/electron,rreimann/electron,darwin/electron,electron/electron,deepak1556/atom-shell,leolujuyi/electron,jlhbaseball15/electron,iftekeriba/electron,bruce/electron,stevemao/electron,Zagorakiss/electron,pombredanne/electron,rsvip/electron,kcrt/electron,medixdev/electron,voidbridge/electron,farmisen/electron,medixdev/electron,jiaz/electron,sircharleswatson/electron,icattlecoder/electron,seanchas116/electron,adamjgray/electron,RobertJGabriel/electron,leftstick/electron,fffej/electron,renaesop/electron,edulan/electron,shaundunne/electron,vipulroxx/electron,digideskio/electron,rreimann/electron,brenca/electron,sircharleswatson/electron,electron/electron,vaginessa/electron,DivyaKMenon/electron,the-ress/electron,simongregory/electron,BionicClick/electron,tomashanacek/electron,beni55/electron,IonicaBizauKitchen/electron,brave/electron,mjaniszew/electron,bobwol/electron,gbn972/electron,mattdesl/electron,thingsinjars/electron,ervinb/electron,shennushi/electron,rhencke/electron,adamjgray/electron,mhkeller/electron,jcblw/electron,GoooIce/electron,digideskio/electron,rreimann/electron,natgolov/electron,roadev/electron,aliib/electron,natgolov/electron,seanchas116/electron,systembugtj/electron,chriskdon/electron,Jonekee/electron,vHanda/electron,maxogden/atom-shell,Gerhut/electron,robinvandernoord/electron,Jonekee/electron,Floato/electron,gbn972/electron,mattotodd/electron,setzer777/electron,trigrass2/electron,iftekeriba/electron,SufianHassan/electron,matiasinsaurralde/electron,rhencke/electron,pirafrank/electron,wan-qy/electron,kostia/electron,etiktin/electron,egoist/electron,Floato/electron,fabien-d/electron,wolfflow/electron,mhkeller/electron,tylergibson/electron,jannishuebl/electron,kikong/electron,rajatsingla28/electron,jjz/electron,tinydew4/electron,stevemao/electron,biblerule/UMCTelnetHub,setzer777/electron,mirrh/electron,bobwol/electron,aliib/electron,christian-bromann/electron,aaron-goshine/electron,gerhardberger/electron,Evercoder/electron,aecca/electron,kostia/electron,greyhwndz/electron,roadev/electron,soulteary/electron,sircharleswatson/electron,MaxWhere/electron,sky7sea/electron,thompsonemerson/electron,JussMee15/electron,Rokt33r/electron,etiktin/electron,minggo/electron,jcblw/electron,micalan/electron,pandoraui/electron,Gerhut/electron,seanchas116/electron,felixrieseberg/electron,faizalpribadi/electron,RIAEvangelist/electron,rhencke/electron,Evercoder/electron,ankitaggarwal011/electron,rajatsingla28/electron,eriser/electron,maxogden/atom-shell,renaesop/electron,astoilkov/electron,pombredanne/electron,carsonmcdonald/electron,destan/electron,kikong/electron,kenmozi/electron,vipulroxx/electron,Jonekee/electron,matiasinsaurralde/electron,fireball-x/atom-shell,jaanus/electron,iftekeriba/electron,davazp/electron,gerhardberger/electron,aichingm/electron,brave/muon,bpasero/electron,wan-qy/electron,kenmozi/electron,mhkeller/electron,rprichard/electron,kazupon/electron,michaelchiche/electron,voidbridge/electron,farmisen/electron,jcblw/electron,jtburke/electron,the-ress/electron,ankitaggarwal011/electron,bbondy/electron,noikiy/electron,felixrieseberg/electron,etiktin/electron,gamedevsam/electron,jtburke/electron,michaelchiche/electron,bitemyapp/electron,tomashanacek/electron,shiftkey/electron,leftstick/electron,sky7sea/electron,oiledCode/electron,rreimann/electron,sky7sea/electron,jhen0409/electron,gstack/infinium-shell,GoooIce/electron,timruffles/electron,Neron-X5/electron,anko/electron,fomojola/electron,deed02392/electron,carsonmcdonald/electron,JesselJohn/electron,shennushi/electron,SufianHassan/electron,beni55/electron,synaptek/electron,deed02392/electron,bwiggs/electron,nagyistoce/electron-atom-shell,cqqccqc/electron,saronwei/electron,LadyNaggaga/electron,pirafrank/electron,fireball-x/atom-shell,ervinb/electron,fritx/electron,minggo/electron,Andrey-Pavlov/electron,setzer777/electron,micalan/electron,brenca/electron,jlhbaseball15/electron,wolfflow/electron,tincan24/electron,felixrieseberg/electron,Floato/electron,pombredanne/electron,egoist/electron,nicholasess/electron,takashi/electron,kenmozi/electron,MaxWhere/electron,d-salas/electron,nagyistoce/electron-atom-shell,jiaz/electron,simonfork/electron,bpasero/electron,joneit/electron,oiledCode/electron,timruffles/electron,aichingm/electron,setzer777/electron,joaomoreno/atom-shell,renaesop/electron,Rokt33r/electron,bpasero/electron,miniak/electron,micalan/electron,bright-sparks/electron,jlhbaseball15/electron,JesselJohn/electron,cos2004/electron,electron/electron,kikong/electron,faizalpribadi/electron,bruce/electron,jhen0409/electron,carsonmcdonald/electron,rreimann/electron,sircharleswatson/electron,meowlab/electron,gamedevsam/electron,carsonmcdonald/electron,baiwyc119/electron,gamedevsam/electron,Jacobichou/electron,robinvandernoord/electron,Andrey-Pavlov/electron,fffej/electron,nicholasess/electron,BionicClick/electron,thomsonreuters/electron,vHanda/electron,adcentury/electron,edulan/electron,bitemyapp/electron,fabien-d/electron,jonatasfreitasv/electron,chrisswk/electron,d-salas/electron,gabrielPeart/electron,astoilkov/electron,bpasero/electron,cos2004/electron,gbn972/electron,thomsonreuters/electron,soulteary/electron,gerhardberger/electron,LadyNaggaga/electron,simonfork/electron,bitemyapp/electron,bitemyapp/electron,Ivshti/electron,seanchas116/electron,digideskio/electron,carsonmcdonald/electron,micalan/electron,natgolov/electron,SufianHassan/electron,ervinb/electron,RobertJGabriel/electron,pirafrank/electron,robinvandernoord/electron,jlord/electron,yan-foto/electron,robinvandernoord/electron,anko/electron,lrlna/electron,tinydew4/electron,webmechanicx/electron,fabien-d/electron,smczk/electron,deed02392/electron,twolfson/electron,bitemyapp/electron,jcblw/electron,Andrey-Pavlov/electron,nekuz0r/electron,deepak1556/atom-shell,eric-seekas/electron,jiaz/electron,webmechanicx/electron,leolujuyi/electron,tinydew4/electron,beni55/electron,faizalpribadi/electron,brenca/electron,thompsonemerson/electron,cqqccqc/electron,GoooIce/electron,roadev/electron,leethomas/electron,matiasinsaurralde/electron,subblue/electron,bpasero/electron,seanchas116/electron,nicobot/electron,astoilkov/electron,Faiz7412/electron,destan/electron,oiledCode/electron,lrlna/electron,RIAEvangelist/electron,brenca/electron,greyhwndz/electron,christian-bromann/electron,tonyganch/electron,bpasero/electron,nekuz0r/electron,shockone/electron,fomojola/electron,nekuz0r/electron,xiruibing/electron,dongjoon-hyun/electron,zhakui/electron,dahal/electron,tincan24/electron,SufianHassan/electron,meowlab/electron,mhkeller/electron,faizalpribadi/electron,jhen0409/electron,eric-seekas/electron,mattotodd/electron,vaginessa/electron,pirafrank/electron,jaanus/electron,baiwyc119/electron,arusakov/electron,joaomoreno/atom-shell,minggo/electron,shennushi/electron,rajatsingla28/electron,webmechanicx/electron,systembugtj/electron,gabriel/electron,ervinb/electron,LadyNaggaga/electron,vipulroxx/electron,iftekeriba/electron,DivyaKMenon/electron,chrisswk/electron,jacksondc/electron,sircharleswatson/electron,voidbridge/electron,aaron-goshine/electron,dkfiresky/electron,synaptek/electron,fffej/electron,micalan/electron,aliib/electron,gerhardberger/electron,gabrielPeart/electron,egoist/electron,pandoraui/electron,yan-foto/electron,jiaz/electron,coderhaoxin/electron,cos2004/electron,bwiggs/electron,Zagorakiss/electron,hokein/atom-shell,beni55/electron,JussMee15/electron,fffej/electron,kcrt/electron,dahal/electron,davazp/electron,meowlab/electron,IonicaBizauKitchen/electron,jonatasfreitasv/electron,jacksondc/electron,shockone/electron,trigrass2/electron,mhkeller/electron,chriskdon/electron,MaxWhere/electron,mrwizard82d1/electron,mirrh/electron,nicobot/electron,saronwei/electron,wan-qy/electron,benweissmann/electron,adamjgray/electron,meowlab/electron,jhen0409/electron,oiledCode/electron,mattdesl/electron,tinydew4/electron,brave/electron,felixrieseberg/electron,edulan/electron,pombredanne/electron,soulteary/electron,howmuchcomputer/electron,Floato/electron,pombredanne/electron,dongjoon-hyun/electron,simongregory/electron,farmisen/electron,LadyNaggaga/electron,farmisen/electron,leethomas/electron,neutrous/electron,ianscrivener/electron,dkfiresky/electron,nicholasess/electron,gstack/infinium-shell,voidbridge/electron,dongjoon-hyun/electron,kenmozi/electron,eriser/electron,DivyaKMenon/electron,stevemao/electron,trankmichael/electron,natgolov/electron,leolujuyi/electron,evgenyzinoviev/electron,zhakui/electron,oiledCode/electron,jsutcodes/electron,leolujuyi/electron,IonicaBizauKitchen/electron,voidbridge/electron,iftekeriba/electron,sshiting/electron,pombredanne/electron,posix4e/electron,leolujuyi/electron,simonfork/electron,jjz/electron,brave/muon,leftstick/electron,thingsinjars/electron,MaxWhere/electron,brave/electron,smczk/electron,tinydew4/electron,medixdev/electron,JesselJohn/electron,saronwei/electron,shiftkey/electron,IonicaBizauKitchen/electron,shennushi/electron,MaxWhere/electron,Jacobichou/electron,tonyganch/electron,mubassirhayat/electron,Zagorakiss/electron,jsutcodes/electron,kostia/electron,stevemao/electron,arusakov/electron,shaundunne/electron,howmuchcomputer/electron,chriskdon/electron,gabrielPeart/electron,Andrey-Pavlov/electron,stevekinney/electron,kikong/electron,fritx/electron,digideskio/electron,rprichard/electron,miniak/electron,twolfson/electron,aaron-goshine/electron,rsvip/electron,tonyganch/electron,Floato/electron,medixdev/electron,vaginessa/electron,jacksondc/electron,tomashanacek/electron,jjz/electron,jiaz/electron,smczk/electron,RobertJGabriel/electron,meowlab/electron,thompsonemerson/electron,stevemao/electron,systembugtj/electron,hokein/atom-shell,ianscrivener/electron,dahal/electron,Neron-X5/electron,simongregory/electron,eric-seekas/electron,chriskdon/electron,brave/electron,John-Lin/electron,aaron-goshine/electron,astoilkov/electron,vaginessa/electron,mjaniszew/electron,shaundunne/electron,meowlab/electron,shiftkey/electron,eric-seekas/electron,leethomas/electron,davazp/electron,greyhwndz/electron,jlord/electron,trankmichael/electron,BionicClick/electron,fabien-d/electron,tonyganch/electron,fritx/electron,simongregory/electron,bruce/electron,gerhardberger/electron,simongregory/electron,nagyistoce/electron-atom-shell,mattotodd/electron,tincan24/electron,GoooIce/electron,Jonekee/electron,matiasinsaurralde/electron,baiwyc119/electron,synaptek/electron,ianscrivener/electron,noikiy/electron,leethomas/electron,biblerule/UMCTelnetHub,bwiggs/electron,arturts/electron,trigrass2/electron,tonyganch/electron,bobwol/electron,brenca/electron,vHanda/electron,cqqccqc/electron,jannishuebl/electron,dahal/electron,eric-seekas/electron,gamedevsam/electron,sky7sea/electron,howmuchcomputer/electron,icattlecoder/electron,xiruibing/electron,saronwei/electron,brave/muon,tylergibson/electron,jacksondc/electron,yalexx/electron,leftstick/electron,adcentury/electron,rsvip/electron,gbn972/electron,arturts/electron,jacksondc/electron,evgenyzinoviev/electron,yan-foto/electron,cos2004/electron,bright-sparks/electron,Faiz7412/electron,thingsinjars/electron,lzpfmh/electron,rajatsingla28/electron,adcentury/electron,chriskdon/electron,fritx/electron,thomsonreuters/electron,digideskio/electron,kenmozi/electron,thompsonemerson/electron,MaxGraey/electron,jlhbaseball15/electron,thomsonreuters/electron,Jonekee/electron,christian-bromann/electron,adamjgray/electron,stevekinney/electron,natgolov/electron,tomashanacek/electron,electron/electron,kcrt/electron,neutrous/electron,Evercoder/electron,Gerhut/electron,DivyaKMenon/electron,takashi/electron,kazupon/electron,bobwol/electron,saronwei/electron,rhencke/electron,abhishekgahlot/electron,leftstick/electron,takashi/electron,preco21/electron,jtburke/electron,wan-qy/electron,Rokt33r/electron,systembugtj/electron,yan-foto/electron,deepak1556/atom-shell,jcblw/electron,twolfson/electron,felixrieseberg/electron,bbondy/electron,shiftkey/electron,benweissmann/electron,roadev/electron,zhakui/electron,shockone/electron,BionicClick/electron,dahal/electron,John-Lin/electron,eric-seekas/electron,adcentury/electron,fritx/electron,lrlna/electron,ervinb/electron,jacksondc/electron,evgenyzinoviev/electron,stevekinney/electron,chrisswk/electron,minggo/electron,neutrous/electron,mattdesl/electron,lzpfmh/electron,aaron-goshine/electron,ankitaggarwal011/electron,gabrielPeart/electron,zhakui/electron,wolfflow/electron,nicholasess/electron,etiktin/electron,farmisen/electron,sky7sea/electron,faizalpribadi/electron,davazp/electron,takashi/electron,kostia/electron,electron/electron,kostia/electron,kokdemo/electron,Andrey-Pavlov/electron,vaginessa/electron,abhishekgahlot/electron,RIAEvangelist/electron,fomojola/electron,nicobot/electron,thingsinjars/electron,fireball-x/atom-shell,vipulroxx/electron,matiasinsaurralde/electron,MaxGraey/electron,aecca/electron,pirafrank/electron,fabien-d/electron,kcrt/electron,noikiy/electron,greyhwndz/electron,Faiz7412/electron,stevemao/electron,lrlna/electron,xiruibing/electron,kazupon/electron,jiaz/electron,iftekeriba/electron,soulteary/electron,thingsinjars/electron,Rokt33r/electron,maxogden/atom-shell,adcentury/electron,eriser/electron,ankitaggarwal011/electron,kcrt/electron,gabriel/electron,deepak1556/atom-shell,ianscrivener/electron,Ivshti/electron,eriser/electron,benweissmann/electron,hokein/atom-shell,fomojola/electron,simonfork/electron,coderhaoxin/electron,noikiy/electron,dkfiresky/electron,mattotodd/electron,davazp/electron,davazp/electron,greyhwndz/electron,icattlecoder/electron,preco21/electron,pandoraui/electron,joaomoreno/atom-shell,jjz/electron,sshiting/electron,vaginessa/electron,lzpfmh/electron,yalexx/electron,posix4e/electron,bruce/electron,etiktin/electron,dkfiresky/electron,brave/muon,coderhaoxin/electron,rajatsingla28/electron,twolfson/electron,leolujuyi/electron,trigrass2/electron,shockone/electron,MaxGraey/electron,rsvip/electron,mrwizard82d1/electron,gabriel/electron,systembugtj/electron,wolfflow/electron,coderhaoxin/electron,xiruibing/electron,maxogden/atom-shell,jsutcodes/electron,miniak/electron,Gerhut/electron,beni55/electron,jsutcodes/electron,takashi/electron,destan/electron,jonatasfreitasv/electron,subblue/electron,MaxWhere/electron,tylergibson/electron,nekuz0r/electron,joaomoreno/atom-shell,coderhaoxin/electron,biblerule/UMCTelnetHub,chrisswk/electron,aichingm/electron,eriser/electron,preco21/electron,dkfiresky/electron,adcentury/electron,jlord/electron,dkfiresky/electron,trankmichael/electron,mubassirhayat/electron,RIAEvangelist/electron,bobwol/electron,baiwyc119/electron,ankitaggarwal011/electron,jaanus/electron,renaesop/electron,Evercoder/electron,Zagorakiss/electron,minggo/electron,kazupon/electron,deed02392/electron,deepak1556/atom-shell,IonicaBizauKitchen/electron,nagyistoce/electron-atom-shell,adamjgray/electron,saronwei/electron,trankmichael/electron,IonicaBizauKitchen/electron,matiasinsaurralde/electron,renaesop/electron,Neron-X5/electron,wan-qy/electron,jaanus/electron,bitemyapp/electron,benweissmann/electron,brave/electron
442f8716115ad20f75aa3d456727fb51f790d31c
basctl/source/basicide/basides2.cxx
basctl/source/basicide/basides2.cxx
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basctl.hxx" #include "docsignature.hxx" #define SI_NOCONTROL #define SI_NOSBXCONTROLS #include <ide_pch.hxx> #include <basic/sbx.hxx> #include "basicrenderable.hxx" #include <com/sun/star/frame/XTitle.hpp> #include <vcl/sound.hxx> #include <basidesh.hxx> #include <basidesh.hrc> #include <baside2.hxx> #include <basdoc.hxx> #include <basobj.hxx> #include <svtools/texteng.hxx> #include <svtools/textview.hxx> #include <svtools/xtextedt.hxx> #include <tools/diagnose_ex.h> #include <sfx2/sfxdefs.hxx> #include <sfx2/signaturestate.hxx> #include <com/sun/star/script/XVBAModuleInfo.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace css = ::com::sun::star; IMPL_LINK_INLINE_START( BasicIDEShell, ObjectDialogCancelHdl, ObjectCatalog *, EMPTYARG ) { ShowObjectDialog( FALSE, TRUE ); return 0; } IMPL_LINK_INLINE_END( BasicIDEShell, ObjectDialogCancelHdl, ObjectCatalog *, EMPTYARG ) /* IMPL_LINK( BasicIDEShell, ObjectDialogInsertHdl, ObjectCatalog *, pObjCat ) { if ( !pCurWin ) return 0; if ( pCurWin->IsA( TYPE( ModulWindow ) ) ) { ModulWindow* pEditWin = (ModulWindow*)pCurWin; pEditWin->InsertFromObjectCatalog( pObjCat ); } else Sound::Beep(); return 0; } */ Reference< view::XRenderable > BasicIDEShell::GetRenderable() { return Reference< view::XRenderable >( new basicide::BasicRenderable( pCurWin ) ); } #if 0 USHORT __EXPORT BasicIDEShell::Print( SfxProgress &rProgress, BOOL bIsAPI, PrintDialog *pPrintDialog ) { if ( pCurWin ) { SfxPrinter* pPrinter = GetPrinter( TRUE ); if ( pPrinter ) { SfxViewShell::Print( rProgress, bIsAPI, pPrintDialog ); pCurWin->PrintData( pPrinter ); } } return 0; } #endif BOOL BasicIDEShell::HasSelection( BOOL /* bText */ ) const { BOOL bSel = FALSE; if ( pCurWin && pCurWin->ISA( ModulWindow ) ) { TextView* pEditView = ((ModulWindow*)pCurWin)->GetEditView(); if ( pEditView && pEditView->HasSelection() ) bSel = TRUE; } return bSel; } String BasicIDEShell::GetSelectionText( BOOL bWholeWord ) { String aText; if ( pCurWin && pCurWin->ISA( ModulWindow ) ) { TextView* pEditView = ((ModulWindow*)pCurWin)->GetEditView(); if ( pEditView ) { if ( bWholeWord && !pEditView->HasSelection() ) { // String aStrCurrentDelimiters = pEngine->GetWordDelimiters(); // pEngine->SetWordDelimiters( " .,;\"'" ); aText = pEditView->GetTextEngine()->GetWord( pEditView->GetSelection().GetEnd() ); // pEngine->SetWordDelimiters( aStrCurrentDelimiters ); } else { TextSelection aSel = pEditView->GetSelection(); if ( !bWholeWord || ( aSel.GetStart().GetPara() == aSel.GetEnd().GetPara() ) ) aText = pEditView->GetSelected(); } } } return aText; } SfxPrinter* __EXPORT BasicIDEShell::GetPrinter( BOOL bCreate ) { if ( pCurWin ) // && pCurWin->ISA( ModulWindow ) ) { BasicDocShell* pDocShell = (BasicDocShell*)GetViewFrame()->GetObjectShell(); DBG_ASSERT( pDocShell, "DocShell ?!" ); return pDocShell->GetPrinter( bCreate ); } return 0; } USHORT __EXPORT BasicIDEShell::SetPrinter( SfxPrinter *pNewPrinter, USHORT nDiffFlags, bool ) { (void)nDiffFlags; BasicDocShell* pDocShell = (BasicDocShell*)GetViewFrame()->GetObjectShell(); DBG_ASSERT( pDocShell, "DocShell ?!" ); pDocShell->SetPrinter( pNewPrinter ); return 0; } void BasicIDEShell::SetMDITitle() { String aTitle; if ( m_aCurLibName.Len() ) { LibraryLocation eLocation = m_aCurDocument.getLibraryLocation( m_aCurLibName ); aTitle = m_aCurDocument.getTitle( eLocation ); aTitle += '.'; aTitle += m_aCurLibName; } else { aTitle = String( IDEResId( RID_STR_ALL ) ); } ::basctl::DocumentSignature aCurSignature( m_aCurDocument ); if ( aCurSignature.getScriptingSignatureState() == SIGNATURESTATE_SIGNATURES_OK ) { aTitle += String::CreateFromAscii( " " ); aTitle += String( IDEResId( RID_STR_SIGNED ) ); aTitle += String::CreateFromAscii( " " ); } SfxViewFrame* pViewFrame = GetViewFrame(); if ( pViewFrame ) { SfxObjectShell* pShell = pViewFrame->GetObjectShell(); if ( pShell && aTitle != pShell->GetTitle( SFX_TITLE_CAPTION ) ) { pShell->SetTitle( aTitle ); pShell->SetModified( FALSE ); } css::uno::Reference< css::frame::XController > xController = GetController (); css::uno::Reference< css::frame::XTitle > xTitle (xController, css::uno::UNO_QUERY); if (xTitle.is ()) xTitle->setTitle (aTitle); } } void BasicIDEShell::DestroyModulWindowLayout() { delete pModulLayout; pModulLayout = 0; } void BasicIDEShell::UpdateModulWindowLayout( bool bBasicStopped ) { if ( pModulLayout ) { pModulLayout->GetStackWindow().UpdateCalls(); pModulLayout->GetWatchWindow().UpdateWatches( bBasicStopped ); } } void BasicIDEShell::CreateModulWindowLayout() { pModulLayout = new ModulWindowLayout( &GetViewFrame()->GetWindow() ); } ModulWindow* BasicIDEShell::CreateBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName ) { bCreatingWindow = TRUE; ULONG nKey = 0; ModulWindow* pWin = 0; String aLibName( rLibName ); String aModName( rModName ); if ( !aLibName.Len() ) aLibName = String::CreateFromAscii( "Standard" ); uno::Reference< container::XNameContainer > xLib = rDocument.getOrCreateLibrary( E_SCRIPTS, aLibName ); if ( !aModName.Len() ) aModName = rDocument.createObjectName( E_SCRIPTS, aLibName ); // Vielleicht gibt es ein suspendiertes? pWin = FindBasWin( rDocument, aLibName, aModName, FALSE, TRUE ); if ( !pWin ) { ::rtl::OUString aModule; bool bSuccess = false; if ( rDocument.hasModule( aLibName, aModName ) ) bSuccess = rDocument.getModule( aLibName, aModName, aModule ); else bSuccess = rDocument.createModule( aLibName, aModName, TRUE, aModule ); if ( bSuccess ) { pWin = FindBasWin( rDocument, aLibName, aModName, FALSE, TRUE ); if( !pWin ) { // new module window pWin = new ModulWindow( pModulLayout, rDocument, aLibName, aModName, aModule ); nKey = InsertWindowInTable( pWin ); } } } else { pWin->SetStatus( pWin->GetStatus() & ~BASWIN_SUSPENDED ); IDEBaseWindow* pTmp = aIDEWindowTable.First(); while ( pTmp && !nKey ) { if ( pTmp == pWin ) nKey = aIDEWindowTable.GetCurKey(); pTmp = aIDEWindowTable.Next(); } DBG_ASSERT( nKey, "CreateBasWin: Kein Key- Fenster nicht gefunden!" ); } if( nKey && xLib.is() && rDocument.isInVBAMode() ) { // display a nice friendly name in the ObjectModule tab, // combining the objectname and module name, e.g. Sheet1 ( Financials ) String sObjName; ModuleInfoHelper::getObjectName( xLib, rModName, sObjName ); if( sObjName.Len() ) { aModName.AppendAscii(" (").Append(sObjName).AppendAscii(")"); } } pTabBar->InsertPage( (USHORT)nKey, aModName ); pTabBar->Sort(); pWin->GrabScrollBars( &aHScrollBar, &aVScrollBar ); if ( !pCurWin ) SetCurWindow( pWin, FALSE, FALSE ); bCreatingWindow = FALSE; return pWin; } ModulWindow* BasicIDEShell::FindBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName, BOOL bCreateIfNotExist, BOOL bFindSuspended ) { ModulWindow* pModWin = 0; IDEBaseWindow* pWin = aIDEWindowTable.First(); while ( pWin && !pModWin ) { if ( ( !pWin->IsSuspended() || bFindSuspended ) && pWin->IsA( TYPE( ModulWindow ) ) ) { if ( !rLibName.Len() ) // nur irgendeins finden... pModWin = (ModulWindow*)pWin; else if ( pWin->IsDocument( rDocument ) && pWin->GetLibName() == rLibName && pWin->GetName() == rModName ) pModWin = (ModulWindow*)pWin; } pWin = aIDEWindowTable.Next(); } if ( !pModWin && bCreateIfNotExist ) pModWin = CreateBasWin( rDocument, rLibName, rModName ); return pModWin; } void __EXPORT BasicIDEShell::Move() { if ( pCurWin && pCurWin->ISA( ModulWindow ) ) ((ModulWindow*)pCurWin)->FrameWindowMoved(); } void __EXPORT BasicIDEShell::ShowCursor( FASTBOOL bOn ) { if ( pCurWin && pCurWin->ISA( ModulWindow ) ) ((ModulWindow*)pCurWin)->ShowCursor( (BOOL)bOn ); } // Hack for #101048 sal_Int32 getBasicIDEShellCount( void ); // Nur wenn Basicfenster oben: void __EXPORT BasicIDEShell::ExecuteBasic( SfxRequest& rReq ) { if ( !pCurWin || !pCurWin->IsA( TYPE( ModulWindow ) ) ) return; pCurWin->ExecuteCommand( rReq ); sal_Int32 nCount = getBasicIDEShellCount(); if( nCount ) CheckWindows(); }
/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_basctl.hxx" #include "docsignature.hxx" #define SI_NOCONTROL #define SI_NOSBXCONTROLS #include <ide_pch.hxx> #include <basic/sbx.hxx> #include "basicrenderable.hxx" #include <com/sun/star/frame/XTitle.hpp> #include <vcl/sound.hxx> #include <basidesh.hxx> #include <basidesh.hrc> #include <baside2.hxx> #include <basdoc.hxx> #include <basobj.hxx> #include <svtools/texteng.hxx> #include <svtools/textview.hxx> #include <svtools/xtextedt.hxx> #include <tools/diagnose_ex.h> #include <sfx2/sfxdefs.hxx> #include <sfx2/signaturestate.hxx> #include <com/sun/star/script/XVBAModuleInfo.hpp> #include <com/sun/star/container/XNameContainer.hpp> #include <com/sun/star/container/XNamed.hpp> #include <com/sun/star/lang/XServiceInfo.hpp> using namespace ::com::sun::star; using namespace ::com::sun::star::uno; namespace css = ::com::sun::star; IMPL_LINK_INLINE_START( BasicIDEShell, ObjectDialogCancelHdl, ObjectCatalog *, EMPTYARG ) { ShowObjectDialog( FALSE, TRUE ); return 0; } IMPL_LINK_INLINE_END( BasicIDEShell, ObjectDialogCancelHdl, ObjectCatalog *, EMPTYARG ) /* IMPL_LINK( BasicIDEShell, ObjectDialogInsertHdl, ObjectCatalog *, pObjCat ) { if ( !pCurWin ) return 0; if ( pCurWin->IsA( TYPE( ModulWindow ) ) ) { ModulWindow* pEditWin = (ModulWindow*)pCurWin; pEditWin->InsertFromObjectCatalog( pObjCat ); } else Sound::Beep(); return 0; } */ Reference< view::XRenderable > BasicIDEShell::GetRenderable() { return Reference< view::XRenderable >( new basicide::BasicRenderable( pCurWin ) ); } #if 0 USHORT __EXPORT BasicIDEShell::Print( SfxProgress &rProgress, BOOL bIsAPI, PrintDialog *pPrintDialog ) { if ( pCurWin ) { SfxPrinter* pPrinter = GetPrinter( TRUE ); if ( pPrinter ) { SfxViewShell::Print( rProgress, bIsAPI, pPrintDialog ); pCurWin->PrintData( pPrinter ); } } return 0; } #endif BOOL BasicIDEShell::HasSelection( BOOL /* bText */ ) const { BOOL bSel = FALSE; if ( pCurWin && pCurWin->ISA( ModulWindow ) ) { TextView* pEditView = ((ModulWindow*)pCurWin)->GetEditView(); if ( pEditView && pEditView->HasSelection() ) bSel = TRUE; } return bSel; } String BasicIDEShell::GetSelectionText( BOOL bWholeWord ) { String aText; if ( pCurWin && pCurWin->ISA( ModulWindow ) ) { TextView* pEditView = ((ModulWindow*)pCurWin)->GetEditView(); if ( pEditView ) { if ( bWholeWord && !pEditView->HasSelection() ) { // String aStrCurrentDelimiters = pEngine->GetWordDelimiters(); // pEngine->SetWordDelimiters( " .,;\"'" ); aText = pEditView->GetTextEngine()->GetWord( pEditView->GetSelection().GetEnd() ); // pEngine->SetWordDelimiters( aStrCurrentDelimiters ); } else { TextSelection aSel = pEditView->GetSelection(); if ( !bWholeWord || ( aSel.GetStart().GetPara() == aSel.GetEnd().GetPara() ) ) aText = pEditView->GetSelected(); } } } return aText; } SfxPrinter* __EXPORT BasicIDEShell::GetPrinter( BOOL bCreate ) { if ( pCurWin ) // && pCurWin->ISA( ModulWindow ) ) { BasicDocShell* pDocShell = (BasicDocShell*)GetViewFrame()->GetObjectShell(); DBG_ASSERT( pDocShell, "DocShell ?!" ); return pDocShell->GetPrinter( bCreate ); } return 0; } USHORT __EXPORT BasicIDEShell::SetPrinter( SfxPrinter *pNewPrinter, USHORT nDiffFlags, bool ) { (void)nDiffFlags; BasicDocShell* pDocShell = (BasicDocShell*)GetViewFrame()->GetObjectShell(); DBG_ASSERT( pDocShell, "DocShell ?!" ); pDocShell->SetPrinter( pNewPrinter ); return 0; } void BasicIDEShell::SetMDITitle() { String aTitle; if ( m_aCurLibName.Len() ) { LibraryLocation eLocation = m_aCurDocument.getLibraryLocation( m_aCurLibName ); aTitle = m_aCurDocument.getTitle( eLocation ); aTitle += '.'; aTitle += m_aCurLibName; } else { aTitle = String( IDEResId( RID_STR_ALL ) ); } ::basctl::DocumentSignature aCurSignature( m_aCurDocument ); if ( aCurSignature.getScriptingSignatureState() == SIGNATURESTATE_SIGNATURES_OK ) { aTitle += String::CreateFromAscii( " " ); aTitle += String( IDEResId( RID_STR_SIGNED ) ); aTitle += String::CreateFromAscii( " " ); } SfxViewFrame* pViewFrame = GetViewFrame(); if ( pViewFrame ) { SfxObjectShell* pShell = pViewFrame->GetObjectShell(); if ( pShell && aTitle != pShell->GetTitle( SFX_TITLE_CAPTION ) ) { pShell->SetTitle( aTitle ); pShell->SetModified( FALSE ); } css::uno::Reference< css::frame::XController > xController = GetController (); css::uno::Reference< css::frame::XTitle > xTitle (xController, css::uno::UNO_QUERY); if (xTitle.is ()) xTitle->setTitle (aTitle); } } void BasicIDEShell::DestroyModulWindowLayout() { delete pModulLayout; pModulLayout = 0; } void BasicIDEShell::UpdateModulWindowLayout( bool bBasicStopped ) { if ( pModulLayout ) { pModulLayout->GetStackWindow().UpdateCalls(); pModulLayout->GetWatchWindow().UpdateWatches( bBasicStopped ); } } void BasicIDEShell::CreateModulWindowLayout() { pModulLayout = new ModulWindowLayout( &GetViewFrame()->GetWindow() ); } ModulWindow* BasicIDEShell::CreateBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName ) { bCreatingWindow = TRUE; ULONG nKey = 0; ModulWindow* pWin = 0; String aLibName( rLibName ); String aModName( rModName ); if ( !aLibName.Len() ) aLibName = String::CreateFromAscii( "Standard" ); uno::Reference< container::XNameContainer > xLib = rDocument.getOrCreateLibrary( E_SCRIPTS, aLibName ); if ( !aModName.Len() ) aModName = rDocument.createObjectName( E_SCRIPTS, aLibName ); // Vielleicht gibt es ein suspendiertes? pWin = FindBasWin( rDocument, aLibName, aModName, FALSE, TRUE ); if ( !pWin ) { ::rtl::OUString aModule; bool bSuccess = false; if ( rDocument.hasModule( aLibName, aModName ) ) bSuccess = rDocument.getModule( aLibName, aModName, aModule ); else bSuccess = rDocument.createModule( aLibName, aModName, TRUE, aModule ); if ( bSuccess ) { pWin = FindBasWin( rDocument, aLibName, aModName, FALSE, TRUE ); if( !pWin ) { // new module window pWin = new ModulWindow( pModulLayout, rDocument, aLibName, aModName, aModule ); nKey = InsertWindowInTable( pWin ); } else // we've gotten called recursively ( via listener from createModule above ), get outta here return pWin; } } else { pWin->SetStatus( pWin->GetStatus() & ~BASWIN_SUSPENDED ); IDEBaseWindow* pTmp = aIDEWindowTable.First(); while ( pTmp && !nKey ) { if ( pTmp == pWin ) nKey = aIDEWindowTable.GetCurKey(); pTmp = aIDEWindowTable.Next(); } DBG_ASSERT( nKey, "CreateBasWin: Kein Key- Fenster nicht gefunden!" ); } if( nKey && xLib.is() && rDocument.isInVBAMode() ) { // display a nice friendly name in the ObjectModule tab, // combining the objectname and module name, e.g. Sheet1 ( Financials ) String sObjName; ModuleInfoHelper::getObjectName( xLib, rModName, sObjName ); if( sObjName.Len() ) { aModName.AppendAscii(" (").Append(sObjName).AppendAscii(")"); } } pTabBar->InsertPage( (USHORT)nKey, aModName ); pTabBar->Sort(); pWin->GrabScrollBars( &aHScrollBar, &aVScrollBar ); if ( !pCurWin ) SetCurWindow( pWin, FALSE, FALSE ); bCreatingWindow = FALSE; return pWin; } ModulWindow* BasicIDEShell::FindBasWin( const ScriptDocument& rDocument, const String& rLibName, const String& rModName, BOOL bCreateIfNotExist, BOOL bFindSuspended ) { ModulWindow* pModWin = 0; IDEBaseWindow* pWin = aIDEWindowTable.First(); while ( pWin && !pModWin ) { if ( ( !pWin->IsSuspended() || bFindSuspended ) && pWin->IsA( TYPE( ModulWindow ) ) ) { if ( !rLibName.Len() ) // nur irgendeins finden... pModWin = (ModulWindow*)pWin; else if ( pWin->IsDocument( rDocument ) && pWin->GetLibName() == rLibName && pWin->GetName() == rModName ) pModWin = (ModulWindow*)pWin; } pWin = aIDEWindowTable.Next(); } if ( !pModWin && bCreateIfNotExist ) pModWin = CreateBasWin( rDocument, rLibName, rModName ); return pModWin; } void __EXPORT BasicIDEShell::Move() { if ( pCurWin && pCurWin->ISA( ModulWindow ) ) ((ModulWindow*)pCurWin)->FrameWindowMoved(); } void __EXPORT BasicIDEShell::ShowCursor( FASTBOOL bOn ) { if ( pCurWin && pCurWin->ISA( ModulWindow ) ) ((ModulWindow*)pCurWin)->ShowCursor( (BOOL)bOn ); } // Hack for #101048 sal_Int32 getBasicIDEShellCount( void ); // Nur wenn Basicfenster oben: void __EXPORT BasicIDEShell::ExecuteBasic( SfxRequest& rReq ) { if ( !pCurWin || !pCurWin->IsA( TYPE( ModulWindow ) ) ) return; pCurWin->ExecuteCommand( rReq ); sal_Int32 nCount = getBasicIDEShellCount(); if( nCount ) CheckWindows(); }
fix for insert
fix for insert
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
6683b842e1975197932d651ba8fb725dc5c3a306
jvmfwk/plugins/sunmajor/pluginlib/vendorbase.hxx
jvmfwk/plugins/sunmajor/pluginlib/vendorbase.hxx
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #include "rtl/ustring.hxx" #include "rtl/ref.hxx" #include "osl/endian.h" #include "salhelper/simplereferenceobject.hxx" #include <vector> namespace jfw_plugin { //Used by subclasses of VendorBase to build paths to Java runtime #if defined(__sparcv9) #define JFW_PLUGIN_ARCH "sparcv9" #elif defined SPARC #define JFW_PLUGIN_ARCH "sparc" #elif defined X86_64 #define JFW_PLUGIN_ARCH "amd64" #elif defined INTEL #define JFW_PLUGIN_ARCH "i386" #elif defined POWERPC64 #define JFW_PLUGIN_ARCH "ppc64" #elif defined POWERPC #define JFW_PLUGIN_ARCH "ppc" #elif defined MIPS #ifdef OSL_BIGENDIAN # define JFW_PLUGIN_ARCH "mips" #else # define JFW_PLUGIN_ARCH "mips32" #endif #elif defined S390X #define JFW_PLUGIN_ARCH "s390x" #elif defined S390 #define JFW_PLUGIN_ARCH "s390" #elif defined ARM #define JFW_PLUGIN_ARCH "arm" #elif defined IA64 #define JFW_PLUGIN_ARCH "ia64" #elif defined M68K #define JFW_PLUGIN_ARCH "m68k" #elif defined HPPA #define JFW_PLUGIN_ARCH "parisc" #elif defined AXP #define JFW_PLUGIN_ARCH "alpha" #else // SPARC, INTEL, POWERPC, MIPS, ARM, IA64, M68K, HPPA, ALPHA #error unknown plattform #endif // SPARC, INTEL, POWERPC, MIPS, ARM, IA64, M68K, HPPA, ALPHA class MalformedVersionException { public: MalformedVersionException(); MalformedVersionException(const MalformedVersionException &); virtual ~MalformedVersionException(); MalformedVersionException & operator =(const MalformedVersionException &); }; class VendorBase: public salhelper::SimpleReferenceObject { public: VendorBase(); /* returns relative paths to the java executable as file URLs. For example "bin/java.exe". You need to implement this function in a derived class, if the paths differ. this implmentation provides for Windows "bin/java.exe" and for Unix "bin/java". The paths are relative file URLs. That is, they always contain '/' even on windows. The paths are relative to the installation directory of a JRE. The signature of this function must correspond to getJavaExePaths_func. */ static char const* const * getJavaExePaths(int* size); /* creates an instance of this class. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @param Key - value pairs of the system properties of the JRE. */ static rtl::Reference<VendorBase> createInstance(); /* called automatically on the instance created by createInstance. @return true - the object could completely initialize. false - the object could not completly initialize. In this case it will be discarded by the caller. */ virtual bool initialize( std::vector<std::pair<rtl::OUString, rtl::OUString> > props); /* returns relative file URLs to the runtime library. For example "/bin/client/jvm.dll" */ virtual char const* const* getRuntimePaths(int* size); virtual char const* const* getLibraryPaths(int* size); virtual const rtl::OUString & getVendor() const; virtual const rtl::OUString & getVersion() const; virtual const rtl::OUString & getHome() const; virtual const rtl::OUString & getRuntimeLibrary() const; virtual const rtl::OUString & getLibraryPaths() const; virtual bool supportsAccessibility() const; /* determines if prior to running java something has to be done, like setting the LD_LIBRARY_PATH. This implementation checks if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and if so, needsRestart returns true. */ virtual bool needsRestart() const; /* compares versions of this vendor. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @return 0 this.version == sSecond 1 this.version > sSecond -1 this.version < sSEcond @throw MalformedVersionException if the version string was not recognized. */ virtual int compareVersions(const rtl::OUString& sSecond) const; protected: rtl::OUString m_sVendor; rtl::OUString m_sVersion; rtl::OUString m_sHome; rtl::OUString m_sRuntimeLibrary; rtl::OUString m_sLD_LIBRARY_PATH; bool m_bAccessibility; typedef rtl::Reference<VendorBase> (* createInstance_func) (); friend rtl::Reference<VendorBase> createInstance( createInstance_func pFunc, std::vector<std::pair<rtl::OUString, rtl::OUString> > properties); }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2000, 2010 Oracle and/or its affiliates. * * OpenOffice.org - a multi-platform office productivity suite * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #if !defined INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #define INCLUDED_JFW_PLUGIN_VENDORBASE_HXX #include "rtl/ustring.hxx" #include "rtl/ref.hxx" #include "osl/endian.h" #include "salhelper/simplereferenceobject.hxx" #include <vector> namespace jfw_plugin { //Used by subclasses of VendorBase to build paths to Java runtime #if defined(__sparcv9) #define JFW_PLUGIN_ARCH "sparcv9" #elif defined SPARC #define JFW_PLUGIN_ARCH "sparc" #elif defined X86_64 #define JFW_PLUGIN_ARCH "amd64" #elif defined INTEL #define JFW_PLUGIN_ARCH "i386" #elif defined POWERPC64 #define JFW_PLUGIN_ARCH "ppc64" #elif defined POWERPC #define JFW_PLUGIN_ARCH "ppc" #elif defined MIPS #ifdef OSL_BIGENDIAN # define JFW_PLUGIN_ARCH "mips" #else /* FIXME: do JDKs have some JDK-specific define? This is for OpenJDK at least, but probably not true for Lemotes JDK */ # define JFW_PLUGIN_ARCH "mipsel" #endif #elif defined S390X #define JFW_PLUGIN_ARCH "s390x" #elif defined S390 #define JFW_PLUGIN_ARCH "s390" #elif defined ARM #define JFW_PLUGIN_ARCH "arm" #elif defined IA64 #define JFW_PLUGIN_ARCH "ia64" #elif defined M68K #define JFW_PLUGIN_ARCH "m68k" #elif defined HPPA #define JFW_PLUGIN_ARCH "parisc" #elif defined AXP #define JFW_PLUGIN_ARCH "alpha" #else // SPARC, INTEL, POWERPC, MIPS, ARM, IA64, M68K, HPPA, ALPHA #error unknown plattform #endif // SPARC, INTEL, POWERPC, MIPS, ARM, IA64, M68K, HPPA, ALPHA class MalformedVersionException { public: MalformedVersionException(); MalformedVersionException(const MalformedVersionException &); virtual ~MalformedVersionException(); MalformedVersionException & operator =(const MalformedVersionException &); }; class VendorBase: public salhelper::SimpleReferenceObject { public: VendorBase(); /* returns relative paths to the java executable as file URLs. For example "bin/java.exe". You need to implement this function in a derived class, if the paths differ. this implmentation provides for Windows "bin/java.exe" and for Unix "bin/java". The paths are relative file URLs. That is, they always contain '/' even on windows. The paths are relative to the installation directory of a JRE. The signature of this function must correspond to getJavaExePaths_func. */ static char const* const * getJavaExePaths(int* size); /* creates an instance of this class. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @param Key - value pairs of the system properties of the JRE. */ static rtl::Reference<VendorBase> createInstance(); /* called automatically on the instance created by createInstance. @return true - the object could completely initialize. false - the object could not completly initialize. In this case it will be discarded by the caller. */ virtual bool initialize( std::vector<std::pair<rtl::OUString, rtl::OUString> > props); /* returns relative file URLs to the runtime library. For example "/bin/client/jvm.dll" */ virtual char const* const* getRuntimePaths(int* size); virtual char const* const* getLibraryPaths(int* size); virtual const rtl::OUString & getVendor() const; virtual const rtl::OUString & getVersion() const; virtual const rtl::OUString & getHome() const; virtual const rtl::OUString & getRuntimeLibrary() const; virtual const rtl::OUString & getLibraryPaths() const; virtual bool supportsAccessibility() const; /* determines if prior to running java something has to be done, like setting the LD_LIBRARY_PATH. This implementation checks if an LD_LIBRARY_PATH (getLD_LIBRARY_PATH) needs to be set and if so, needsRestart returns true. */ virtual bool needsRestart() const; /* compares versions of this vendor. MUST be overridden in a derived class. #################################################### OVERRIDE in derived class ################################################### @return 0 this.version == sSecond 1 this.version > sSecond -1 this.version < sSEcond @throw MalformedVersionException if the version string was not recognized. */ virtual int compareVersions(const rtl::OUString& sSecond) const; protected: rtl::OUString m_sVendor; rtl::OUString m_sVersion; rtl::OUString m_sHome; rtl::OUString m_sRuntimeLibrary; rtl::OUString m_sLD_LIBRARY_PATH; bool m_bAccessibility; typedef rtl::Reference<VendorBase> (* createInstance_func) (); friend rtl::Reference<VendorBase> createInstance( createInstance_func pFunc, std::vector<std::pair<rtl::OUString, rtl::OUString> > properties); }; } #endif /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
fix JFW_PLUGIN_ARCH for OpenJDK/mipsel
fix JFW_PLUGIN_ARCH for OpenJDK/mipsel
C++
mpl-2.0
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
1406dfde0e0c76da87db632b28c721cc65e7367b
base/i18n/icu_string_conversions.cc
base/i18n/icu_string_conversions.cc
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_string_conversions.h" #include <vector> #include "base/basictypes.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "unicode/ucnv.h" #include "unicode/ucnv_cb.h" #include "unicode/ucnv_err.h" #include "unicode/unorm.h" #include "unicode/ustring.h" namespace base { namespace { // ToUnicodeCallbackSubstitute() is based on UCNV_TO_U_CALLBACK_SUSBSTITUTE // in source/common/ucnv_err.c. // Copyright (c) 1995-2006 International Business Machines Corporation // and others // // All rights reserved. // // 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, and/or // sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, provided that the above copyright notice(s) and // this permission notice appear in all copies of the Software and that // both the above copyright notice(s) and this permission notice appear in // supporting documentation. // // 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 // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS // INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT // OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE // OR PERFORMANCE OF THIS SOFTWARE. // // Except as contained in this notice, the name of a copyright holder // shall not be used in advertising or otherwise to promote the sale, use // or other dealings in this Software without prior written authorization // of the copyright holder. // ___________________________________________________________________________ // // All trademarks and registered trademarks mentioned herein are the property // of their respective owners. void ToUnicodeCallbackSubstitute(const void* context, UConverterToUnicodeArgs *to_args, const char* code_units, int32_t length, UConverterCallbackReason reason, UErrorCode * err) { static const UChar kReplacementChar = 0xFFFD; if (reason <= UCNV_IRREGULAR) { if (context == NULL || (*(reinterpret_cast<const char*>(context)) == 'i' && reason == UCNV_UNASSIGNED)) { *err = U_ZERO_ERROR; ucnv_cbToUWriteUChars(to_args, &kReplacementChar, 1, 0, err); } // else the caller must have set the error code accordingly. } // else ignore the reset, close and clone calls. } bool ConvertFromUTF16(UConverter* converter, const UChar* uchar_src, int uchar_len, OnStringConversionError::Type on_error, std::string* encoded) { int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(uchar_len, ucnv_getMaxCharSize(converter)); encoded->resize(encoded_max_length); UErrorCode status = U_ZERO_ERROR; // Setup our error handler. switch (on_error) { case OnStringConversionError::FAIL: ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, 0, NULL, NULL, &status); break; case OnStringConversionError::SKIP: case OnStringConversionError::SUBSTITUTE: ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, 0, NULL, NULL, &status); break; default: NOTREACHED(); } // ucnv_fromUChars returns size not including terminating null int actual_size = ucnv_fromUChars(converter, &(*encoded)[0], encoded_max_length, uchar_src, uchar_len, &status); encoded->resize(actual_size); ucnv_close(converter); if (U_SUCCESS(status)) return true; encoded->clear(); // Make sure the output is empty on error. return false; } // Set up our error handler for ToUTF-16 converters void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error, UConverter* converter, UErrorCode* status) { switch (on_error) { case OnStringConversionError::FAIL: ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, 0, NULL, NULL, status); break; case OnStringConversionError::SKIP: ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, 0, NULL, NULL, status); break; case OnStringConversionError::SUBSTITUTE: ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, 0, NULL, NULL, status); break; default: NOTREACHED(); } } inline UConverterType utf32_platform_endian() { #if U_IS_BIG_ENDIAN return UCNV_UTF32_BigEndian; #else return UCNV_UTF32_LittleEndian; #endif } } // namespace const char kCodepageLatin1[] = "ISO-8859-1"; const char kCodepageUTF8[] = "UTF-8"; const char kCodepageUTF16BE[] = "UTF-16BE"; const char kCodepageUTF16LE[] = "UTF-16LE"; // Codepage <-> Wide/UTF-16 --------------------------------------------------- bool UTF16ToCodepage(const string16& utf16, const char* codepage_name, OnStringConversionError::Type on_error, std::string* encoded) { encoded->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; return ConvertFromUTF16(converter, utf16.c_str(), static_cast<int>(utf16.length()), on_error, encoded); } bool CodepageToUTF16(const std::string& encoded, const char* codepage_name, OnStringConversionError::Type on_error, string16* utf16) { utf16->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; // Even in the worst case, the maximum length in 2-byte units of UTF-16 // output would be at most the same as the number of bytes in input. There // is no single-byte encoding in which a character is mapped to a // non-BMP character requiring two 2-byte units. // // Moreover, non-BMP characters in legacy multibyte encodings // (e.g. EUC-JP, GB18030) take at least 2 bytes. The only exceptions are // BOCU and SCSU, but we don't care about them. size_t uchar_max_length = encoded.length() + 1; SetUpErrorHandlerForToUChars(on_error, converter, &status); scoped_array<char16> buffer(new char16[uchar_max_length]); int actual_size = ucnv_toUChars(converter, buffer.get(), static_cast<int>(uchar_max_length), encoded.data(), static_cast<int>(encoded.length()), &status); ucnv_close(converter); if (!U_SUCCESS(status)) { utf16->clear(); // Make sure the output is empty on error. return false; } utf16->assign(buffer.get(), actual_size); return true; } bool WideToCodepage(const std::wstring& wide, const char* codepage_name, OnStringConversionError::Type on_error, std::string* encoded) { #if defined(WCHAR_T_IS_UTF16) return UTF16ToCodepage(wide, codepage_name, on_error, encoded); #elif defined(WCHAR_T_IS_UTF32) encoded->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; int utf16_len; // When wchar_t is wider than UChar (16 bits), transform |wide| into a // UChar* string. Size the UChar* buffer to be large enough to hold twice // as many UTF-16 code units (UChar's) as there are Unicode code points, // in case each code points translates to a UTF-16 surrogate pair, // and leave room for a NUL terminator. std::vector<UChar> utf16(wide.length() * 2 + 1); u_strFromUTF32(&utf16[0], utf16.size(), &utf16_len, reinterpret_cast<const UChar32*>(wide.c_str()), wide.length(), &status); DCHECK(U_SUCCESS(status)) << "failed to convert wstring to UChar*"; return ConvertFromUTF16(converter, &utf16[0], utf16_len, on_error, encoded); #endif // defined(WCHAR_T_IS_UTF32) } bool CodepageToWide(const std::string& encoded, const char* codepage_name, OnStringConversionError::Type on_error, std::wstring* wide) { #if defined(WCHAR_T_IS_UTF16) return CodepageToUTF16(encoded, codepage_name, on_error, wide); #elif defined(WCHAR_T_IS_UTF32) wide->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; // The maximum length in 4 byte unit of UTF-32 output would be // at most the same as the number of bytes in input. In the worst // case of GB18030 (excluding escaped-based encodings like ISO-2022-JP), // this can be 4 times larger than actually needed. size_t wchar_max_length = encoded.length() + 1; SetUpErrorHandlerForToUChars(on_error, converter, &status); scoped_array<wchar_t> buffer(new wchar_t[wchar_max_length]); int actual_size = ucnv_toAlgorithmic(utf32_platform_endian(), converter, reinterpret_cast<char*>(buffer.get()), static_cast<int>(wchar_max_length) * sizeof(wchar_t), encoded.data(), static_cast<int>(encoded.length()), &status); ucnv_close(converter); if (!U_SUCCESS(status)) { wide->clear(); // Make sure the output is empty on error. return false; } // actual_size is # of bytes. wide->assign(buffer.get(), actual_size / sizeof(wchar_t)); return true; #endif // defined(WCHAR_T_IS_UTF32) } bool ConvertToUtf8AndNormalize(const std::string& text, const std::string& charset, std::string* result) { result->clear(); string16 utf16; if (!CodepageToUTF16( text, charset.c_str(), OnStringConversionError::FAIL, &utf16)) return false; UErrorCode status = U_ZERO_ERROR; size_t max_length = utf16.length() + 1; string16 normalized_utf16; scoped_array<char16> buffer(new char16[max_length]); int actual_length = unorm_normalize( utf16.c_str(), utf16.length(), UNORM_NFC, 0, buffer.get(), static_cast<int>(max_length), &status); if (!U_SUCCESS(status)) return false; normalized_utf16.assign(buffer.get(), actual_length); return UTF16ToUTF8(normalized_utf16.data(), normalized_utf16.length(), result); } } // namespace base
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/i18n/icu_string_conversions.h" #include <vector> #include "base/basictypes.h" #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/string_util.h" #include "base/utf_string_conversions.h" #include "unicode/ucnv.h" #include "unicode/ucnv_cb.h" #include "unicode/ucnv_err.h" #include "unicode/unorm.h" #include "unicode/ustring.h" namespace base { namespace { // ToUnicodeCallbackSubstitute() is based on UCNV_TO_U_CALLBACK_SUBSTITUTE // in source/common/ucnv_err.c. // Copyright (c) 1995-2006 International Business Machines Corporation // and others // // All rights reserved. // // 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, and/or // sell copies of the Software, and to permit persons to whom the Software // is furnished to do so, provided that the above copyright notice(s) and // this permission notice appear in all copies of the Software and that // both the above copyright notice(s) and this permission notice appear in // supporting documentation. // // 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 // OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS // INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT // OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE // OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE // OR PERFORMANCE OF THIS SOFTWARE. // // Except as contained in this notice, the name of a copyright holder // shall not be used in advertising or otherwise to promote the sale, use // or other dealings in this Software without prior written authorization // of the copyright holder. // ___________________________________________________________________________ // // All trademarks and registered trademarks mentioned herein are the property // of their respective owners. void ToUnicodeCallbackSubstitute(const void* context, UConverterToUnicodeArgs *to_args, const char* code_units, int32_t length, UConverterCallbackReason reason, UErrorCode * err) { static const UChar kReplacementChar = 0xFFFD; if (reason <= UCNV_IRREGULAR) { if (context == NULL || (*(reinterpret_cast<const char*>(context)) == 'i' && reason == UCNV_UNASSIGNED)) { *err = U_ZERO_ERROR; ucnv_cbToUWriteUChars(to_args, &kReplacementChar, 1, 0, err); } // else the caller must have set the error code accordingly. } // else ignore the reset, close and clone calls. } bool ConvertFromUTF16(UConverter* converter, const UChar* uchar_src, int uchar_len, OnStringConversionError::Type on_error, std::string* encoded) { int encoded_max_length = UCNV_GET_MAX_BYTES_FOR_STRING(uchar_len, ucnv_getMaxCharSize(converter)); encoded->resize(encoded_max_length); UErrorCode status = U_ZERO_ERROR; // Setup our error handler. switch (on_error) { case OnStringConversionError::FAIL: ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_STOP, 0, NULL, NULL, &status); break; case OnStringConversionError::SKIP: case OnStringConversionError::SUBSTITUTE: ucnv_setFromUCallBack(converter, UCNV_FROM_U_CALLBACK_SKIP, 0, NULL, NULL, &status); break; default: NOTREACHED(); } // ucnv_fromUChars returns size not including terminating null int actual_size = ucnv_fromUChars(converter, &(*encoded)[0], encoded_max_length, uchar_src, uchar_len, &status); encoded->resize(actual_size); ucnv_close(converter); if (U_SUCCESS(status)) return true; encoded->clear(); // Make sure the output is empty on error. return false; } // Set up our error handler for ToUTF-16 converters void SetUpErrorHandlerForToUChars(OnStringConversionError::Type on_error, UConverter* converter, UErrorCode* status) { switch (on_error) { case OnStringConversionError::FAIL: ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_STOP, 0, NULL, NULL, status); break; case OnStringConversionError::SKIP: ucnv_setToUCallBack(converter, UCNV_TO_U_CALLBACK_SKIP, 0, NULL, NULL, status); break; case OnStringConversionError::SUBSTITUTE: ucnv_setToUCallBack(converter, ToUnicodeCallbackSubstitute, 0, NULL, NULL, status); break; default: NOTREACHED(); } } inline UConverterType utf32_platform_endian() { #if U_IS_BIG_ENDIAN return UCNV_UTF32_BigEndian; #else return UCNV_UTF32_LittleEndian; #endif } } // namespace const char kCodepageLatin1[] = "ISO-8859-1"; const char kCodepageUTF8[] = "UTF-8"; const char kCodepageUTF16BE[] = "UTF-16BE"; const char kCodepageUTF16LE[] = "UTF-16LE"; // Codepage <-> Wide/UTF-16 --------------------------------------------------- bool UTF16ToCodepage(const string16& utf16, const char* codepage_name, OnStringConversionError::Type on_error, std::string* encoded) { encoded->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; return ConvertFromUTF16(converter, utf16.c_str(), static_cast<int>(utf16.length()), on_error, encoded); } bool CodepageToUTF16(const std::string& encoded, const char* codepage_name, OnStringConversionError::Type on_error, string16* utf16) { utf16->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; // Even in the worst case, the maximum length in 2-byte units of UTF-16 // output would be at most the same as the number of bytes in input. There // is no single-byte encoding in which a character is mapped to a // non-BMP character requiring two 2-byte units. // // Moreover, non-BMP characters in legacy multibyte encodings // (e.g. EUC-JP, GB18030) take at least 2 bytes. The only exceptions are // BOCU and SCSU, but we don't care about them. size_t uchar_max_length = encoded.length() + 1; SetUpErrorHandlerForToUChars(on_error, converter, &status); scoped_array<char16> buffer(new char16[uchar_max_length]); int actual_size = ucnv_toUChars(converter, buffer.get(), static_cast<int>(uchar_max_length), encoded.data(), static_cast<int>(encoded.length()), &status); ucnv_close(converter); if (!U_SUCCESS(status)) { utf16->clear(); // Make sure the output is empty on error. return false; } utf16->assign(buffer.get(), actual_size); return true; } bool WideToCodepage(const std::wstring& wide, const char* codepage_name, OnStringConversionError::Type on_error, std::string* encoded) { #if defined(WCHAR_T_IS_UTF16) return UTF16ToCodepage(wide, codepage_name, on_error, encoded); #elif defined(WCHAR_T_IS_UTF32) encoded->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; int utf16_len; // When wchar_t is wider than UChar (16 bits), transform |wide| into a // UChar* string. Size the UChar* buffer to be large enough to hold twice // as many UTF-16 code units (UChar's) as there are Unicode code points, // in case each code points translates to a UTF-16 surrogate pair, // and leave room for a NUL terminator. std::vector<UChar> utf16(wide.length() * 2 + 1); u_strFromUTF32(&utf16[0], utf16.size(), &utf16_len, reinterpret_cast<const UChar32*>(wide.c_str()), wide.length(), &status); DCHECK(U_SUCCESS(status)) << "failed to convert wstring to UChar*"; return ConvertFromUTF16(converter, &utf16[0], utf16_len, on_error, encoded); #endif // defined(WCHAR_T_IS_UTF32) } bool CodepageToWide(const std::string& encoded, const char* codepage_name, OnStringConversionError::Type on_error, std::wstring* wide) { #if defined(WCHAR_T_IS_UTF16) return CodepageToUTF16(encoded, codepage_name, on_error, wide); #elif defined(WCHAR_T_IS_UTF32) wide->clear(); UErrorCode status = U_ZERO_ERROR; UConverter* converter = ucnv_open(codepage_name, &status); if (!U_SUCCESS(status)) return false; // The maximum length in 4 byte unit of UTF-32 output would be // at most the same as the number of bytes in input. In the worst // case of GB18030 (excluding escaped-based encodings like ISO-2022-JP), // this can be 4 times larger than actually needed. size_t wchar_max_length = encoded.length() + 1; SetUpErrorHandlerForToUChars(on_error, converter, &status); scoped_array<wchar_t> buffer(new wchar_t[wchar_max_length]); int actual_size = ucnv_toAlgorithmic(utf32_platform_endian(), converter, reinterpret_cast<char*>(buffer.get()), static_cast<int>(wchar_max_length) * sizeof(wchar_t), encoded.data(), static_cast<int>(encoded.length()), &status); ucnv_close(converter); if (!U_SUCCESS(status)) { wide->clear(); // Make sure the output is empty on error. return false; } // actual_size is # of bytes. wide->assign(buffer.get(), actual_size / sizeof(wchar_t)); return true; #endif // defined(WCHAR_T_IS_UTF32) } bool ConvertToUtf8AndNormalize(const std::string& text, const std::string& charset, std::string* result) { result->clear(); string16 utf16; if (!CodepageToUTF16( text, charset.c_str(), OnStringConversionError::FAIL, &utf16)) return false; UErrorCode status = U_ZERO_ERROR; size_t max_length = utf16.length() + 1; string16 normalized_utf16; scoped_array<char16> buffer(new char16[max_length]); int actual_length = unorm_normalize( utf16.c_str(), utf16.length(), UNORM_NFC, 0, buffer.get(), static_cast<int>(max_length), &status); if (!U_SUCCESS(status)) return false; normalized_utf16.assign(buffer.get(), actual_length); return UTF16ToUTF8(normalized_utf16.data(), normalized_utf16.length(), result); } } // namespace base
Fix a typo in the comment for ToUnicodeCallbackSubstitute()
Fix a typo in the comment for ToUnicodeCallbackSubstitute() See http://codereview.chromium.org/151065 Review URL: https://chromiumcodereview.appspot.com/9724033 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@128557 0039d316-1c4b-4281-b951-d872f2087c98
C++
bsd-3-clause
Jonekee/chromium.src,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,chuan9/chromium-crosswalk,junmin-zhu/chromium-rivertrail,Chilledheart/chromium,markYoungH/chromium.src,ondra-novak/chromium.src,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,ltilve/chromium,PeterWangIntel/chromium-crosswalk,ondra-novak/chromium.src,littlstar/chromium.src,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,Jonekee/chromium.src,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,rogerwang/chromium,Just-D/chromium-1,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,mogoweb/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Just-D/chromium-1,dednal/chromium.src,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,dushu1203/chromium.src,pozdnyakov/chromium-crosswalk,jaruba/chromium.src,Fireblend/chromium-crosswalk,fujunwei/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,krieger-od/nwjs_chromium.src,patrickm/chromium.src,dushu1203/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,robclark/chromium,timopulkkinen/BubbleFish,markYoungH/chromium.src,M4sse/chromium.src,TheTypoMaster/chromium-crosswalk,rogerwang/chromium,Chilledheart/chromium,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,littlstar/chromium.src,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,robclark/chromium,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,zcbenz/cefode-chromium,M4sse/chromium.src,fujunwei/chromium-crosswalk,markYoungH/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,littlstar/chromium.src,ltilve/chromium,Jonekee/chromium.src,PeterWangIntel/chromium-crosswalk,Chilledheart/chromium,bright-sparks/chromium-spacewalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,krieger-od/nwjs_chromium.src,keishi/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,markYoungH/chromium.src,patrickm/chromium.src,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,littlstar/chromium.src,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,Jonekee/chromium.src,robclark/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,ltilve/chromium,axinging/chromium-crosswalk,dednal/chromium.src,robclark/chromium,anirudhSK/chromium,Chilledheart/chromium,markYoungH/chromium.src,keishi/chromium,krieger-od/nwjs_chromium.src,anirudhSK/chromium,littlstar/chromium.src,Fireblend/chromium-crosswalk,Chilledheart/chromium,Just-D/chromium-1,anirudhSK/chromium,anirudhSK/chromium,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,hujiajie/pa-chromium,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,mogoweb/chromium-crosswalk,pozdnyakov/chromium-crosswalk,ltilve/chromium,Just-D/chromium-1,pozdnyakov/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,Fireblend/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,anirudhSK/chromium,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,keishi/chromium,dushu1203/chromium.src,patrickm/chromium.src,axinging/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,jaruba/chromium.src,ondra-novak/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,nacl-webkit/chrome_deps,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,Pluto-tv/chromium-crosswalk,junmin-zhu/chromium-rivertrail,ltilve/chromium,markYoungH/chromium.src,Pluto-tv/chromium-crosswalk,hgl888/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,markYoungH/chromium.src,patrickm/chromium.src,mohamed--abdel-maksoud/chromium.src,ChromiumWebApps/chromium,dednal/chromium.src,robclark/chromium,Jonekee/chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,hujiajie/pa-chromium,rogerwang/chromium,ChromiumWebApps/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,markYoungH/chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,bright-sparks/chromium-spacewalk,ondra-novak/chromium.src,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,Fireblend/chromium-crosswalk,dushu1203/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,M4sse/chromium.src,ChromiumWebApps/chromium,Pluto-tv/chromium-crosswalk,robclark/chromium,anirudhSK/chromium,patrickm/chromium.src,Chilledheart/chromium,M4sse/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,anirudhSK/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,bright-sparks/chromium-spacewalk,rogerwang/chromium,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,robclark/chromium,junmin-zhu/chromium-rivertrail,ltilve/chromium,dushu1203/chromium.src,mogoweb/chromium-crosswalk,krieger-od/nwjs_chromium.src,zcbenz/cefode-chromium,dednal/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,rogerwang/chromium,hgl888/chromium-crosswalk,krieger-od/nwjs_chromium.src,ltilve/chromium,markYoungH/chromium.src,fujunwei/chromium-crosswalk,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,keishi/chromium,keishi/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,jaruba/chromium.src,pozdnyakov/chromium-crosswalk,anirudhSK/chromium,dednal/chromium.src,markYoungH/chromium.src,keishi/chromium,ondra-novak/chromium.src,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,patrickm/chromium.src,ondra-novak/chromium.src,dednal/chromium.src,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,dednal/chromium.src,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,Jonekee/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,axinging/chromium-crosswalk,Pluto-tv/chromium-crosswalk,nacl-webkit/chrome_deps,axinging/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,M4sse/chromium.src,chuan9/chromium-crosswalk,hgl888/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,axinging/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,jaruba/chromium.src,patrickm/chromium.src,dushu1203/chromium.src,jaruba/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,dednal/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,hgl888/chromium-crosswalk-efl,keishi/chromium,M4sse/chromium.src,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,rogerwang/chromium,dushu1203/chromium.src,keishi/chromium,bright-sparks/chromium-spacewalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,jaruba/chromium.src,ltilve/chromium,rogerwang/chromium,hgl888/chromium-crosswalk,ChromiumWebApps/chromium,rogerwang/chromium,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,littlstar/chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk-efl,keishi/chromium,mohamed--abdel-maksoud/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,Just-D/chromium-1,chuan9/chromium-crosswalk,mogoweb/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,littlstar/chromium.src,Jonekee/chromium.src,patrickm/chromium.src,jaruba/chromium.src,jaruba/chromium.src,ltilve/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,keishi/chromium,junmin-zhu/chromium-rivertrail,markYoungH/chromium.src,hujiajie/pa-chromium,junmin-zhu/chromium-rivertrail,Just-D/chromium-1,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,timopulkkinen/BubbleFish,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk-efl
9482220bf0c69df2558e6d32d193163ac116b167
osquery/tables/system/freebsd/sysctl_utils.cpp
osquery/tables/system/freebsd/sysctl_utils.cpp
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ //#include <sys/sysctl.h> #include <osquery/filesystem.h> #include <osquery/tables.h> #include "osquery/tables/system/posix/sysctl_utils.h" namespace osquery { namespace tables { void genControlInfo(int* oid, size_t oid_size, QueryData& results, const std::map<std::string, std::string>& config) { } void genControlInfoFromName(const std::string& name, QueryData& results, const std::map<std::string, std::string>& config) { } void genAllControls(QueryData& results, const std::map<std::string, std::string>& config, const std::string& subsystem) { } } }
/* * Copyright (c) 2014-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <stddef.h> #include <sys/types.h> #include <sys/sysctl.h> #include <osquery/filesystem.h> #include <osquery/tables.h> #include "osquery/tables/system/posix/sysctl_utils.h" namespace osquery { namespace tables { #define CTL_DEBUG_ITERATE 2 #define CTL_DEBUG_DESCRIPTION 1 #define CTL_DEBUG_TYPE 4 // If the debug iteration fails, prevent endless lookups. #define MAX_CONTROLS 1024 const std::vector<std::string> kControlNames{ "", "kern", "vm", "vfs", "net", "debug", "hw", "user"}; const std::vector<std::string> kControlTypes{ "", "node", "int", "string", "s64", "opaque", "struct"}; void genControlInfo(int* oid, size_t oid_size, QueryData& results, const std::map<std::string, std::string>& config) { Row r; if (oid_size == 0) { return; } r["oid"] = stringFromMIB(oid, oid_size); // Request the description (the canonical name) for the MIB. char response[CTL_MAX_VALUE] = {0}; size_t response_size = CTL_MAX_VALUE; int request[CTL_MAXNAME + 2] = {0, CTL_DEBUG_DESCRIPTION}; memcpy(request + 2, oid, oid_size * sizeof(int)); if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) { return; } r["name"] = std::string(response); if (oid[0] > 0 && oid[0] < static_cast<int>(kControlNames.size())) { r["subsystem"] = kControlNames[oid[0]]; } // Now request structure type. request[1] = CTL_DEBUG_TYPE; if (sysctl(request, oid_size + 2, response, &response_size, 0, 0) != 0) { // Cannot request MIB type (int, string, struct, etc). return; } size_t oid_type = 0; if (response_size > 0) { oid_type = ((size_t)response[0] & CTLTYPE); if (oid_type < kControlTypes.size()) { r["type"] = kControlTypes[((int)response[0])]; } } // Finally request MIB value. if (oid_type > CTLTYPE_NODE && oid_type < CTLTYPE_OPAQUE) { size_t value_size = 0; sysctl(oid, oid_size, 0, &value_size, 0, 0); if (value_size > CTL_MAX_VALUE) { // If the value size is larger than the max value, limit. value_size = CTL_MAX_VALUE; } sysctl(oid, oid_size, response, &value_size, 0, 0); if (oid_type == CTLTYPE_INT) { unsigned int value; memcpy(&value, response, sizeof(int)); r["current_value"] = INTEGER(value); } else if (oid_type == CTLTYPE_STRING) { r["current_value"] = std::string(response); } else if (oid_type == CTLTYPE_S64) { long long value; memcpy(&value, response, value_size); } } // If this MIB was set using sysctl.conf add the value. if (config.count(r.at("name")) > 0) { r["config_value"] = config.at(r["name"]); } results.push_back(r); } void genControlInfoFromName(const std::string& name, QueryData& results, const std::map<std::string, std::string>& config) { int request[CTL_DEBUG_MAXID + 2] = {0}; size_t oid_size = CTL_DEBUG_MAXID; if (sysctlnametomib(name.c_str(), request, &oid_size) != 0) { // MIB lookup failed. return; } genControlInfo((int*)request, oid_size, results, config); } void genAllControls(QueryData& results, const std::map<std::string, std::string>& config, const std::string& subsystem) { int subsystem_limit = 0; if (subsystem.size() != 0) { // If a subsystem was provided, limit the enumeration. auto it = std::find(kControlNames.begin(), kControlNames.end(), subsystem); if (it == kControlNames.end()) { // Subsystem is not known. return; } subsystem_limit = std::distance(kControlNames.begin(), it); } // Use the request to retrieve the MIB vector. int request[CTL_DEBUG_MAXID + 2] = {0, CTL_DEBUG_ITERATE}; size_t request_size = 3; // Write the OID into an integer vector to request the name/value. int response[CTL_DEBUG_MAXID + 2] = {0}; size_t response_size = 0; // Start iterating from OID=1 if no subsystem was provided. request[2] = (subsystem_limit == 0) ? 1 : subsystem_limit; size_t num_controls = 0; while (num_controls++ < MAX_CONTROLS) { // This will walk the MIBs, requesting the 'next' in the response. response_size = sizeof(request); if (sysctl(request, request_size, response, &response_size, 0, 0) != 0) { // Request failed, unhandled serious error. break; } if (subsystem_limit != 0 && response[0] != subsystem_limit) { // The OID search was limited to a subsystem. break; } response_size /= sizeof(int); genControlInfo(response, response_size, results, config); // Set the data for the next OID request. memcpy(request + 2, response, CTL_DEBUG_MAXID * sizeof(int)); request_size = response_size + 2; } } } }
Make sysctls work on FreeBSD (#3242)
Make sysctls work on FreeBSD (#3242)
C++
bsd-3-clause
tburgin/osquery,jedi22/osquery,tburgin/osquery,hackgnar/osquery,jedi22/osquery,PoppySeedPlehzr/osquery,PoppySeedPlehzr/osquery,hackgnar/osquery,tburgin/osquery,PoppySeedPlehzr/osquery,jedi22/osquery,hackgnar/osquery