text
string
meta
dict
/* [auto_generated] boost/numeric/odeint/algebra/norm_result_type.hpp [begin_description] Calculates the type of the norm_inf operation for container types [end_description] Copyright 2013 Karsten Ahnert Copyright 2013 Mario Mulansky Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_NUMERIC_ODEINT_ALGEBRA_NORM_RESULT_TYPE_HPP_INCLUDED #define BOOST_NUMERIC_ODEINT_ALGEBRA_NORM_RESULT_TYPE_HPP_INCLUDED #include <boost/numeric/odeint/algebra/detail/extract_value_type.hpp> namespace boost { namespace numeric { namespace odeint { template< typename S , typename Enabler = void > struct norm_result_type { typedef typename detail::extract_value_type< S >::type type; }; } } } #endif
{ "language": "C++" }
#ifndef BOOST_MPL_AUX_PARTITION_OP_HPP_INCLUDED #define BOOST_MPL_AUX_PARTITION_OP_HPP_INCLUDED // Copyright Eric Friedman 2003 // Copyright Aleksey Gurtovoy 2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/apply.hpp> #include <boost/mpl/eval_if.hpp> #include <boost/mpl/if.hpp> #include <boost/mpl/pair.hpp> #include <boost/mpl/aux_/lambda_spec.hpp> namespace boost { namespace mpl { namespace aux { template< typename Pred, typename In1Op, typename In2Op > struct partition_op { template< typename State, typename T > struct apply { typedef typename State::first first_; typedef typename State::second second_; typedef typename apply1< Pred,T >::type pred_; typedef typename eval_if< pred_ , apply2<In1Op,first_,T> , apply2<In2Op,second_,T> >::type result_; typedef typename if_< pred_ , pair< result_,second_ > , pair< first_,result_ > >::type type; }; }; } // namespace aux BOOST_MPL_AUX_PASS_THROUGH_LAMBDA_SPEC(3, aux::partition_op) }} #endif // BOOST_MPL_AUX_PARTITION_OP_HPP_INCLUDED
{ "language": "C++" }
/* * Copyright (C) 2012 Emweb bv, Herent, Belgium. * * See the LICENSE file for terms of use. */ #include "Wt/WApplication.h" #include "Wt/WContainerWidget.h" #include "Wt/WEnvironment.h" #include "Wt/WGridLayout.h" #include "Wt/WLogger.h" #include "StdGridLayoutImpl2.h" #include "SizeHandle.h" #include "DomElement.h" #include "WebUtils.h" #ifndef WT_DEBUG_JS #include "js/StdGridLayoutImpl2.min.js" #include "js/WtResize.min.js" #endif #ifdef WT_WIN32 #define snprintf _snprintf #endif namespace Wt { LOGGER("WGridLayout2"); StdGridLayoutImpl2::StdGridLayoutImpl2(WLayout *layout, Impl::Grid& grid) : StdLayoutImpl(layout), grid_(grid), needAdjust_(false), needRemeasure_(false), needConfigUpdate_(false) { const char *THIS_JS = "js/StdGridLayoutImpl2.js"; WApplication *app = WApplication::instance(); if (!app->javaScriptLoaded(THIS_JS)) { app->styleSheet().addRule("table.Wt-hcenter", "margin: 0px auto;" "position: relative"); LOAD_JAVASCRIPT(app, THIS_JS, "StdLayout2", wtjs1); LOAD_JAVASCRIPT(app, THIS_JS, "layouts2", appjs1); app->doJavaScript(app->javaScriptClass() + ".layouts2.scheduleAdjust();"); app->doJavaScript("(function(){" "var f=function(){" + app->javaScriptClass() + ".layouts2.scheduleAdjust();" "};" "if($().jquery.indexOf('1.') === 0)" "$(window).load(f);" "else " "$(window).on('load',f);" "})();"); WApplication::instance()->addAutoJavaScript ("if(" + app->javaScriptClass() + ".layouts2) " + app->javaScriptClass() + ".layouts2.adjustNow();"); } } bool StdGridLayoutImpl2::itemResized(WLayoutItem *item) { const unsigned colCount = grid_.columns_.size(); const unsigned rowCount = grid_.rows_.size(); for (unsigned row = 0; row < rowCount; ++row) for (unsigned col = 0; col < colCount; ++col) if (grid_.items_[row][col].item_.get() == item && !grid_.items_[row][col].update_) { grid_.items_[row][col].update_ = true; needAdjust_ = true; return true; } return false; } bool StdGridLayoutImpl2::parentResized() { if (!needRemeasure_) { needRemeasure_ = true; return true; } else return false; } int StdGridLayoutImpl2::nextRowWithItem(int row, int c) const { for (row += grid_.items_[row][c].rowSpan_; row < (int)grid_.rows_.size(); ++row) { for (unsigned col = 0; col < grid_.columns_.size(); col += grid_.items_[row][col].colSpan_) { if (hasItem(row, col)) return row; } } return grid_.rows_.size(); } int StdGridLayoutImpl2::nextColumnWithItem(int row, int col) const { for (;;) { col = col + grid_.items_[row][col].colSpan_; if (col < (int)grid_.columns_.size()) { for (unsigned i = 0; i < grid_.rows_.size(); ++i) if (hasItem(i, col)) return col; } else return grid_.columns_.size(); } } bool StdGridLayoutImpl2::hasItem(int row, int col) const { WLayoutItem *item = grid_.items_[row][col].item_.get(); if (item) { WWidget *w = item->widget(); return !w || !w->isHidden(); } else return false; } DomElement *StdGridLayoutImpl2::createElement(WLayoutItem *item, WApplication *app) { DomElement *c = getImpl(item)->createDomElement(nullptr, true, true, app); c->setProperty(Property::StyleVisibility, "hidden"); return c; } void StdGridLayoutImpl2::updateDom(DomElement& parent) { WApplication *app = WApplication::instance(); if (needConfigUpdate_) { needConfigUpdate_ = false; DomElement *div = DomElement::getForUpdate(this, DomElementType::DIV); for (unsigned i = 0; i < addedItems_.size(); ++i) { WLayoutItem *item = addedItems_[i]; DomElement *c = createElement(item, app); div->addChild(c); } addedItems_.clear(); for (unsigned i = 0; i < removedItems_.size(); ++i) parent.callJavaScript(WT_CLASS ".remove('" + removedItems_[i] + "');", true); removedItems_.clear(); parent.addChild(div); WStringStream js; js << app->javaScriptClass() << ".layouts2.updateConfig('" << id() << "',"; streamConfig(js, app); js << ");"; app->doJavaScript(js.str()); needRemeasure_ = false; needAdjust_ = false; } if (needRemeasure_) { needRemeasure_ = false; WStringStream js; js << app->javaScriptClass() << ".layouts2.setDirty('" << id() << "');"; app->doJavaScript(js.str()); } if (needAdjust_) { needAdjust_ = false; WStringStream js; js << app->javaScriptClass() << ".layouts2.adjust('" << id() << "', ["; bool first = true; const unsigned colCount = grid_.columns_.size(); const unsigned rowCount = grid_.rows_.size(); for (unsigned row = 0; row < rowCount; ++row) for (unsigned col = 0; col < colCount; ++col) if (grid_.items_[row][col].update_) { grid_.items_[row][col].update_ = false; if (!first) js << ","; first = false; js << "[" << (int)row << "," << (int)col << "]"; } js << "]);"; app->doJavaScript(js.str()); } const unsigned colCount = grid_.columns_.size(); const unsigned rowCount = grid_.rows_.size(); for (unsigned i = 0; i < rowCount; ++i) { for (unsigned j = 0; j < colCount; ++j) { WLayoutItem *item = grid_.items_[i][j].item_.get(); if (item) { WLayout *nested = item->layout(); if (nested) (dynamic_cast<StdLayoutImpl *>(nested->impl()))->updateDom(parent); } } } } StdGridLayoutImpl2::~StdGridLayoutImpl2() { WApplication *app = WApplication::instance(); /* * If it is a top-level layout (as opposed to a nested layout), * configure overflow of the container. */ if (parentLayoutImpl() == nullptr) { if (container() == app->root()) { app->setBodyClass(""); app->setHtmlClass(""); } if (app->environment().agentIsIElt(9) && container()) container()->setOverflow(Overflow::Visible); } } int StdGridLayoutImpl2::minimumHeightForRow(int row) const { int minHeight = 0; const unsigned colCount = grid_.columns_.size(); for (unsigned j = 0; j < colCount; ++j) { WLayoutItem *item = grid_.items_[row][j].item_.get(); if (item) minHeight = std::max(minHeight, getImpl(item)->minimumHeight()); } return minHeight; } int StdGridLayoutImpl2::minimumWidthForColumn(int col) const { int minWidth = 0; const unsigned rowCount = grid_.rows_.size(); for (unsigned i = 0; i < rowCount; ++i) { WLayoutItem *item = grid_.items_[i][col].item_.get(); if (item) minWidth = std::max(minWidth, getImpl(item)->minimumWidth()); } return minWidth; } int StdGridLayoutImpl2::minimumWidth() const { const unsigned colCount = grid_.columns_.size(); int total = 0; for (unsigned i = 0; i < colCount; ++i) total += minimumWidthForColumn(i); return total + (colCount-1) * grid_.horizontalSpacing_; } int StdGridLayoutImpl2::minimumHeight() const { const unsigned rowCount = grid_.rows_.size(); int total = 0; for (unsigned i = 0; i < rowCount; ++i) total += minimumHeightForRow(i); return total + (rowCount-1) * grid_.verticalSpacing_; } void StdGridLayoutImpl2::itemAdded(WLayoutItem *item) { addedItems_.push_back(item); update(); } void StdGridLayoutImpl2::itemRemoved(WLayoutItem *item) { Utils::erase(addedItems_, item); removedItems_.push_back(getImpl(item)->id()); update(); } void StdGridLayoutImpl2::update() { WContainerWidget *c = container(); if (c) c->layoutChanged(false); needConfigUpdate_ = true; } void StdGridLayoutImpl2 ::streamConfig(WStringStream& js, const std::vector<Impl::Grid::Section>& sections, bool rows, WApplication *app) { js << "["; for (unsigned i = 0; i < sections.size(); ++i) { if (i != 0) js << ","; js << "[" << sections[i].stretch_ << ","; if (sections[i].resizable_) { SizeHandle::loadJavaScript(app); js << "["; const WLength& size = sections[i].initialSize_; if (size.isAuto()) js << "-1"; else if (size.unit() == LengthUnit::Percentage) js << size.value() << ",1"; else js << size.toPixels(); js << "],"; } else js << "0,"; if (rows) js << minimumHeightForRow(i); else js << minimumWidthForColumn(i); js << "]"; } js << "]"; } void StdGridLayoutImpl2::streamConfig(WStringStream& js, WApplication *app) { js << "{ rows:"; streamConfig(js, grid_.rows_, true, app); js << ", cols:"; streamConfig(js, grid_.columns_, false, app); js << ", items: ["; const unsigned colCount = grid_.columns_.size(); const unsigned rowCount = grid_.rows_.size(); for (unsigned row = 0; row < rowCount; ++row) { for (unsigned col = 0; col < colCount; ++col) { Impl::Grid::Item& item = grid_.items_[row][col]; AlignmentFlag hAlign = item.alignment_ & AlignHorizontalMask; AlignmentFlag vAlign = item.alignment_ & AlignVerticalMask; if (row + col != 0) js << ","; if (item.item_) { std::string id = getImpl(item.item_.get())->id(); js << "{"; if (item.colSpan_ != 1 || item.rowSpan_ != 1) js << "span: [" << item.colSpan_ << "," << item.rowSpan_ << "],"; if (item.alignment_.value()) { unsigned align = 0; if (hAlign != static_cast<AlignmentFlag>(0)) switch (hAlign) { case AlignmentFlag::Left: align |= 0x1; break; case AlignmentFlag::Right: align |= 0x2; break; case AlignmentFlag::Center: align |= 0x4; break; default: break; } if (vAlign != static_cast<AlignmentFlag>(0)) switch (vAlign) { case AlignmentFlag::Top: align |= 0x10; break; case AlignmentFlag::Bottom: align |= 0x20; break; case AlignmentFlag::Middle: align |= 0x40; break; default: break; } js << "align:" << (int)align << ","; } js << "dirty:" << (grid_.items_[row][col].update_ ? 2 : 0) << ",id:'" << id << "'" << "}"; grid_.items_[row][col].update_ = 0; } else js << "null"; } } js << "]}"; } int StdGridLayoutImpl2::pixelSize(const WLength& size) { if (size.unit() == LengthUnit::Percentage) return 0; else return (int)size.toPixels(); } /* * fitWidth, fitHeight: * - from setLayout(AlignmentFlag::Left | AlignmentFlag::Top) * is being deprecated but still needs to be implemented * - nested layouts: handles as other layout items */ DomElement *StdGridLayoutImpl2::createDomElement(DomElement *parent, bool fitWidth, bool fitHeight, WApplication *app) { needAdjust_ = needConfigUpdate_ = needRemeasure_ = false; addedItems_.clear(); removedItems_.clear(); const unsigned colCount = grid_.columns_.size(); const unsigned rowCount = grid_.rows_.size(); int margin[] = { 0, 0, 0, 0}; int maxWidth = 0, maxHeight = 0; if (layout()->parentLayout() == nullptr) { /* * If it is a top-level layout (as opposed to a nested layout), * configure overflow of the container. */ if (container() == app->root()) { /* * Reset body,html default paddings and so on if we are doing layout * in the entire document. */ app->setBodyClass(app->bodyClass() + " Wt-layout"); app->setHtmlClass(app->htmlClass() + " Wt-layout"); } #ifndef WT_TARGET_JAVA layout()->getContentsMargins(margin + 3, margin, margin + 1, margin + 2); #else // WT_TARGET_JAVA margin[3] = layout()->getContentsMargin(Side::Left); margin[0] = layout()->getContentsMargin(Side::Top); margin[1] = layout()->getContentsMargin(Side::Right); margin[2] = layout()->getContentsMargin(Side::Bottom); #endif // WT_TARGET_JAVA maxWidth = pixelSize(container()->maximumWidth()); maxHeight = pixelSize(container()->maximumHeight()); } WStringStream js; js << app->javaScriptClass() << ".layouts2.add(new " WT_CLASS ".StdLayout2(" << app->javaScriptClass() << ",'" << id() << "',"; if (layout()->parentLayout() && dynamic_cast<StdGridLayoutImpl2*>(getImpl(layout()->parentLayout()))) js << "'" << getImpl(layout()->parentLayout())->id() << "',"; else js << "null,"; bool progressive = !app->environment().ajax(); js << (fitWidth ? '1' : '0') << "," << (fitHeight ? '1' : '0') << "," << (progressive ? '1' : '0') << ","; js << maxWidth << "," << maxHeight << ",[" << grid_.horizontalSpacing_ << "," << margin[3] << "," << margin[1] << "],[" << grid_.verticalSpacing_ << "," << margin[0] << "," << margin[2] << "],"; streamConfig(js, app); DomElement *div = DomElement::createNew(DomElementType::DIV); div->setId(id()); div->setProperty(Property::StylePosition, "relative"); DomElement *table = nullptr, *tbody = nullptr, *tr = nullptr; if (progressive) { table = DomElement::createNew(DomElementType::TABLE); WStringStream style; if (maxWidth) style << "max-width: " << maxWidth << "px;"; if (maxHeight) style << "max-height: " << maxHeight << "px;"; style << "width: 100%;"; table->setProperty(Property::Style, style.str()); int totalColStretch = 0; for (unsigned col = 0; col < colCount; ++col) totalColStretch += std::max(0, grid_.columns_[col].stretch_); for (unsigned col = 0; col < colCount; ++col) { DomElement *c = DomElement::createNew(DomElementType::COL); int stretch = std::max(0, grid_.columns_[col].stretch_); if (stretch || totalColStretch == 0) { char buf[30]; double pct = totalColStretch == 0 ? 100.0 / colCount : (100.0 * stretch / totalColStretch); WStringStream ss; ss << "width:" << Utils::round_css_str(pct, 2, buf) << "%;"; c->setProperty(Property::Style, ss.str()); } table->addChild(c); } tbody = DomElement::createNew(DomElementType::TBODY); } #ifndef WT_TARGET_JAVA std::vector<bool> overSpanned(colCount * rowCount, false); #else std::vector<bool> overSpanned; overSpanned.insert(0, colCount * rowCount, false); #endif // WT_TARGET_JAVA int prevRowWithItem = -1; for (unsigned row = 0; row < rowCount; ++row) { if (table) tr = DomElement::createNew(DomElementType::TR); bool rowVisible = false; int prevColumnWithItem = -1; for (unsigned col = 0; col < colCount; ++col) { Impl::Grid::Item& item = grid_.items_[row][col]; if (!overSpanned[row * colCount + col]) { for (int i = 0; i < item.rowSpan_; ++i) for (int j = 0; j < item.colSpan_; ++j) if (i + j > 0) overSpanned[(row + i) * colCount + col + j] = true; AlignmentFlag hAlign = item.alignment_ & AlignHorizontalMask; AlignmentFlag vAlign = item.alignment_ & AlignVerticalMask; DomElement *td = nullptr; if (table) { bool itemVisible = hasItem(row, col); rowVisible = rowVisible || itemVisible; td = DomElement::createNew(DomElementType::TD); if (itemVisible) { int padding[] = { 0, 0, 0, 0 }; int nextRow = nextRowWithItem(row, col); int prevRow = prevRowWithItem; int nextCol = nextColumnWithItem(row, col); int prevCol = prevColumnWithItem; if (prevRow == -1) padding[0] = margin[0]; else padding[0] = (grid_.verticalSpacing_+1) / 2; if (nextRow == (int)rowCount) padding[2] = margin[2]; else padding[2] = grid_.verticalSpacing_ / 2; if (prevCol == -1) padding[3] = margin[3]; else padding[3] = (grid_.horizontalSpacing_ + 1)/2; if (nextCol == (int)colCount) padding[1] = margin[1]; else padding[1] = (grid_.horizontalSpacing_)/2; WStringStream style; if (app->layoutDirection() == LayoutDirection::RightToLeft) std::swap(padding[1], padding[3]); if (padding[0] == padding[1] && padding[0] == padding[2] && padding[0] == padding[3]) { if (padding[0] != 0) style << "padding:" << padding[0] << "px;"; } else style << "padding:" << padding[0] << "px " << padding[1] << "px " << padding[2] << "px " << padding[3] << "px;"; if (static_cast<unsigned int>(vAlign) != 0) switch (vAlign) { case AlignmentFlag::Top: style << "vertical-align:top;"; break; case AlignmentFlag::Middle: style << "vertical-align:middle;"; break; case AlignmentFlag::Bottom: style << "vertical-align:bottom;"; default: break; } td->setProperty(Property::Style, style.str()); if (item.rowSpan_ != 1) td->setProperty(Property::RowSpan, std::to_string(item.rowSpan_)); if (item.colSpan_ != 1) td->setProperty(Property::ColSpan, std::to_string(item.colSpan_)); prevColumnWithItem = col; } } DomElement *c = nullptr; if (!table) { if (item.item_) { c = createElement(item.item_.get(), app); div->addChild(c); } } else if (item.item_) c = getImpl(item.item_.get())->createDomElement(nullptr, true, true, app); if (table) { if (c) { if (!app->environment().agentIsIElt(9)) c->setProperty(Property::StyleBoxSizing, "border-box"); if (static_cast<unsigned int>(hAlign) == 0) hAlign = AlignmentFlag::Justify; switch (hAlign) { case AlignmentFlag::Center: { DomElement *itable = DomElement::createNew(DomElementType::TABLE); itable->setProperty(Property::Class, "Wt-hcenter"); if (static_cast<unsigned int>(vAlign) == 0) itable->setProperty(Property::Style, "height:100%;"); DomElement *irow = DomElement::createNew(DomElementType::TR); DomElement *itd = DomElement::createNew(DomElementType::TD); if (static_cast<unsigned int>(vAlign) == 0) itd->setProperty(Property::Style, "height:100%;"); bool haveMinWidth = !c->getProperty(Property::StyleMinWidth).empty(); itd->addChild(c); if (app->environment().agentIsIElt(9)) { // IE7 and IE8 do support min-width but do not enforce it // properly when in a table. // see http://stackoverflow.com/questions/2356525 // /css-min-width-in-ie6-7-and-8 if (haveMinWidth) { DomElement *spacer = DomElement::createNew(DomElementType::DIV); spacer->setProperty(Property::StyleWidth, c->getProperty(Property::StyleMinWidth)); spacer->setProperty(Property::StyleHeight, "1px"); itd->addChild(spacer); } } irow->addChild(itd); itable->addChild(irow); c = itable; break; } case AlignmentFlag::Right: if (!c->isDefaultInline()) c->setProperty(Property::StyleFloat, "right"); else td->setProperty(Property::StyleTextAlign, "right"); break; case AlignmentFlag::Left: if (!c->isDefaultInline()) c->setProperty(Property::StyleFloat, "left"); else td->setProperty(Property::StyleTextAlign, "left"); break; default: break; } bool haveMinWidth = !c->getProperty(Property::StyleMinWidth).empty(); td->addChild(c); if (app->environment().agentIsIElt(9)) { // IE7 and IE8 do support min-width but do not enforce it properly // when in a table. // see http://stackoverflow.com/questions/2356525 // /css-min-width-in-ie6-7-and-8 if (haveMinWidth) { DomElement *spacer = DomElement::createNew(DomElementType::DIV); spacer->setProperty(Property::StyleWidth, c->getProperty(Property::StyleMinWidth)); spacer->setProperty(Property::StyleHeight, "1px"); td->addChild(spacer); } } } tr->addChild(td); } } } if (tr) { if (!rowVisible) tr->setProperty(Property::StyleDisplay, "hidden"); else prevRowWithItem = row; tbody->addChild(tr); } } js << "));"; if (table) { table->addChild(tbody); div->addChild(table); } div->callJavaScript(js.str()); if (layout()->parentLayout() == nullptr) { WContainerWidget *c = container(); /* * Take the hint: if the container is relative, then we can use an absolute * layout for its contents, under the assumption that a .wtResize or * auto-javascript sets the width too (like in WTreeView, WTableView) */ if (c->positionScheme() == PositionScheme::Relative || c->positionScheme() == PositionScheme::Absolute) { div->setProperty(Property::StylePosition, "absolute"); div->setProperty(Property::StyleLeft, "0"); div->setProperty(Property::StyleRight, "0"); } else if (app->environment().agentIsIE()) { /* * position: relative element needs to be in a position: relative * parent otherwise scrolling is broken */ if (app->environment().agentIsIE() && c->parent()->positionScheme() != PositionScheme::Static) parent->setProperty(Property::StylePosition, "relative"); } AlignmentFlag hAlign = c->contentAlignment() & AlignHorizontalMask; switch (hAlign) { case AlignmentFlag::Center: { DomElement *itable = DomElement::createNew(DomElementType::TABLE); itable->setProperty(Property::Class, "Wt-hcenter"); if (fitHeight) itable->setProperty(Property::Style, "height:100%;"); DomElement *irow = DomElement::createNew(DomElementType::TR); DomElement *itd = DomElement::createNew(DomElementType::TD); if (fitHeight) itd->setProperty(Property::Style, "height:100%;"); itd->addChild(div); irow->addChild(itd); itable->addChild(irow); itable->setId(id() + "l"); div = itable; break; } case AlignmentFlag::Left: break; case AlignmentFlag::Right: div->setProperty(Property::StyleFloat, "right"); break; default: break; } } return div; } }
{ "language": "C++" }
// Copyright 2013 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 "chromeos/dbus/fake_shill_device_client.h" #include <algorithm> #include "base/bind.h" #include "base/location.h" #include "base/memory/ptr_util.h" #include "base/single_thread_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chromeos/dbus/dbus_thread_manager.h" #include "chromeos/dbus/shill_manager_client.h" #include "chromeos/dbus/shill_property_changed_observer.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_path.h" #include "dbus/object_proxy.h" #include "dbus/values_util.h" #include "net/base/ip_endpoint.h" #include "third_party/cros_system_api/dbus/service_constants.h" namespace chromeos { namespace { const char kSimPuk[] = "12345678"; // Matches pseudomodem. const int kSimPinMinLength = 4; const int kSimPukRetryCount = 10; const char kFailedMessage[] = "Failed"; void ErrorFunction(const std::string& device_path, const std::string& error_name, const std::string& error_message) { LOG(ERROR) << "Shill Error for: " << device_path << ": " << error_name << " : " << error_message; } void PostError(const std::string& error, const ShillDeviceClient::ErrorCallback& error_callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, error, kFailedMessage)); } void PostNotFoundError(const ShillDeviceClient::ErrorCallback& error_callback) { PostError(shill::kErrorResultNotFound, error_callback); } bool IsReadOnlyProperty(const std::string& name) { if (name == shill::kCarrierProperty) return true; return false; } } // namespace const char FakeShillDeviceClient::kDefaultSimPin[] = "1111"; const int FakeShillDeviceClient::kSimPinRetryCount = 3; FakeShillDeviceClient::FakeShillDeviceClient() : initial_tdls_busy_count_(0), tdls_busy_count_(0), weak_ptr_factory_(this) {} FakeShillDeviceClient::~FakeShillDeviceClient() { } // ShillDeviceClient overrides. void FakeShillDeviceClient::Init(dbus::Bus* bus) {} void FakeShillDeviceClient::AddPropertyChangedObserver( const dbus::ObjectPath& device_path, ShillPropertyChangedObserver* observer) { GetObserverList(device_path).AddObserver(observer); } void FakeShillDeviceClient::RemovePropertyChangedObserver( const dbus::ObjectPath& device_path, ShillPropertyChangedObserver* observer) { GetObserverList(device_path).RemoveObserver(observer); } void FakeShillDeviceClient::GetProperties( const dbus::ObjectPath& device_path, const DictionaryValueCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FakeShillDeviceClient::PassStubDeviceProperties, weak_ptr_factory_.GetWeakPtr(), device_path, callback)); } void FakeShillDeviceClient::ProposeScan( const dbus::ObjectPath& device_path, const VoidDBusMethodCallback& callback) { PostVoidCallback(callback, DBUS_METHOD_CALL_SUCCESS); } void FakeShillDeviceClient::SetProperty(const dbus::ObjectPath& device_path, const std::string& name, const base::Value& value, const base::Closure& callback, const ErrorCallback& error_callback) { if (IsReadOnlyProperty(name)) PostError(shill::kErrorResultInvalidArguments, error_callback); SetPropertyInternal(device_path, name, value, callback, error_callback); } void FakeShillDeviceClient::SetPropertyInternal( const dbus::ObjectPath& device_path, const std::string& name, const base::Value& value, const base::Closure& callback, const ErrorCallback& error_callback) { base::DictionaryValue* device_properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion(device_path.value(), &device_properties)) { PostNotFoundError(error_callback); return; } device_properties->SetWithoutPathExpansion(name, value.DeepCopy()); base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(&FakeShillDeviceClient::NotifyObserversPropertyChanged, weak_ptr_factory_.GetWeakPtr(), device_path, name)); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::ClearProperty( const dbus::ObjectPath& device_path, const std::string& name, const VoidDBusMethodCallback& callback) { base::DictionaryValue* device_properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion(device_path.value(), &device_properties)) { PostVoidCallback(callback, DBUS_METHOD_CALL_FAILURE); return; } device_properties->RemoveWithoutPathExpansion(name, NULL); PostVoidCallback(callback, DBUS_METHOD_CALL_SUCCESS); } void FakeShillDeviceClient::AddIPConfig( const dbus::ObjectPath& device_path, const std::string& method, const ObjectPathDBusMethodCallback& callback) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(callback, DBUS_METHOD_CALL_SUCCESS, dbus::ObjectPath())); } void FakeShillDeviceClient::RequirePin(const dbus::ObjectPath& device_path, const std::string& pin, bool require, const base::Closure& callback, const ErrorCallback& error_callback) { VLOG(1) << "RequirePin: " << device_path.value(); if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } if (!SimTryPin(device_path.value(), pin)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultIncorrectPin, "")); return; } SimLockStatus status = GetSimLockStatus(device_path.value()); status.lock_enabled = require; SetSimLockStatus(device_path.value(), status); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::EnterPin(const dbus::ObjectPath& device_path, const std::string& pin, const base::Closure& callback, const ErrorCallback& error_callback) { VLOG(1) << "EnterPin: " << device_path.value(); if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } if (!SimTryPin(device_path.value(), pin)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultIncorrectPin, "")); return; } SetSimLocked(device_path.value(), false); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::UnblockPin(const dbus::ObjectPath& device_path, const std::string& puk, const std::string& pin, const base::Closure& callback, const ErrorCallback& error_callback) { VLOG(1) << "UnblockPin: " << device_path.value(); if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } if (!SimTryPuk(device_path.value(), puk)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultIncorrectPin, "")); return; } if (pin.length() < kSimPinMinLength) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultInvalidArguments, "")); return; } sim_pin_[device_path.value()] = pin; SetSimLocked(device_path.value(), false); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::ChangePin(const dbus::ObjectPath& device_path, const std::string& old_pin, const std::string& new_pin, const base::Closure& callback, const ErrorCallback& error_callback) { VLOG(1) << "ChangePin: " << device_path.value(); if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } if (!SimTryPin(device_path.value(), old_pin)) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultIncorrectPin, "")); return; } if (new_pin.length() < kSimPinMinLength) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultInvalidArguments, "")); return; } sim_pin_[device_path.value()] = new_pin; base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::Register(const dbus::ObjectPath& device_path, const std::string& network_id, const base::Closure& callback, const ErrorCallback& error_callback) { if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::SetCarrier(const dbus::ObjectPath& device_path, const std::string& carrier, const base::Closure& callback, const ErrorCallback& error_callback) { SetPropertyInternal(device_path, shill::kCarrierProperty, base::StringValue(carrier), callback, error_callback); } void FakeShillDeviceClient::Reset(const dbus::ObjectPath& device_path, const base::Closure& callback, const ErrorCallback& error_callback) { if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::PerformTDLSOperation( const dbus::ObjectPath& device_path, const std::string& operation, const std::string& peer, const StringCallback& callback, const ErrorCallback& error_callback) { if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } // Use -1 to emulate a TDLS failure. if (tdls_busy_count_ == -1) { base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorDhcpFailed, "Failed")); return; } if (operation != shill::kTDLSStatusOperation && tdls_busy_count_ > 0) { --tdls_busy_count_; base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::Bind(error_callback, shill::kErrorResultInProgress, "In-Progress")); return; } tdls_busy_count_ = initial_tdls_busy_count_; std::string result; if (operation == shill::kTDLSDiscoverOperation) { if (tdls_state_.empty()) tdls_state_ = shill::kTDLSDisconnectedState; } else if (operation == shill::kTDLSSetupOperation) { if (tdls_state_.empty()) tdls_state_ = shill::kTDLSConnectedState; } else if (operation == shill::kTDLSTeardownOperation) { if (tdls_state_.empty()) tdls_state_ = shill::kTDLSDisconnectedState; } else if (operation == shill::kTDLSStatusOperation) { result = tdls_state_; } base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, result)); } void FakeShillDeviceClient::AddWakeOnPacketConnection( const dbus::ObjectPath& device_path, const net::IPEndPoint& ip_endpoint, const base::Closure& callback, const ErrorCallback& error_callback) { if (!stub_devices_.HasKey(device_path.value())) { PostNotFoundError(error_callback); return; } wake_on_packet_connections_[device_path].insert(ip_endpoint); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::RemoveWakeOnPacketConnection( const dbus::ObjectPath& device_path, const net::IPEndPoint& ip_endpoint, const base::Closure& callback, const ErrorCallback& error_callback) { const auto device_iter = wake_on_packet_connections_.find(device_path); if (!stub_devices_.HasKey(device_path.value()) || device_iter == wake_on_packet_connections_.end()) { PostNotFoundError(error_callback); return; } const auto endpoint_iter = device_iter->second.find(ip_endpoint); if (endpoint_iter == device_iter->second.end()) { PostNotFoundError(error_callback); return; } device_iter->second.erase(endpoint_iter); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } void FakeShillDeviceClient::RemoveAllWakeOnPacketConnections( const dbus::ObjectPath& device_path, const base::Closure& callback, const ErrorCallback& error_callback) { const auto iter = wake_on_packet_connections_.find(device_path); if (!stub_devices_.HasKey(device_path.value()) || iter == wake_on_packet_connections_.end()) { PostNotFoundError(error_callback); return; } wake_on_packet_connections_.erase(iter); base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, callback); } ShillDeviceClient::TestInterface* FakeShillDeviceClient::GetTestInterface() { return this; } // ShillDeviceClient::TestInterface overrides. void FakeShillDeviceClient::AddDevice(const std::string& device_path, const std::string& type, const std::string& name) { DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()-> AddDevice(device_path); base::DictionaryValue* properties = GetDeviceProperties(device_path); properties->SetStringWithoutPathExpansion(shill::kTypeProperty, type); properties->SetStringWithoutPathExpansion(shill::kNameProperty, name); properties->SetStringWithoutPathExpansion(shill::kDBusObjectProperty, device_path); properties->SetStringWithoutPathExpansion( shill::kDBusServiceProperty, modemmanager::kModemManager1ServiceName); if (type == shill::kTypeCellular) { properties->SetBooleanWithoutPathExpansion( shill::kCellularAllowRoamingProperty, false); } } void FakeShillDeviceClient::RemoveDevice(const std::string& device_path) { DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()-> RemoveDevice(device_path); stub_devices_.RemoveWithoutPathExpansion(device_path, NULL); } void FakeShillDeviceClient::ClearDevices() { DBusThreadManager::Get()->GetShillManagerClient()->GetTestInterface()-> ClearDevices(); stub_devices_.Clear(); } void FakeShillDeviceClient::SetDeviceProperty(const std::string& device_path, const std::string& name, const base::Value& value) { VLOG(1) << "SetDeviceProperty: " << device_path << ": " << name << " = " << value; SetPropertyInternal(dbus::ObjectPath(device_path), name, value, base::Bind(&base::DoNothing), base::Bind(&ErrorFunction, device_path)); } std::string FakeShillDeviceClient::GetDevicePathForType( const std::string& type) { for (base::DictionaryValue::Iterator iter(stub_devices_); !iter.IsAtEnd(); iter.Advance()) { const base::DictionaryValue* properties = NULL; if (!iter.value().GetAsDictionary(&properties)) continue; std::string prop_type; if (!properties->GetStringWithoutPathExpansion( shill::kTypeProperty, &prop_type) || prop_type != type) continue; return iter.key(); } return std::string(); } void FakeShillDeviceClient::SetTDLSBusyCount(int count) { tdls_busy_count_ = std::max(count, -1); } void FakeShillDeviceClient::SetTDLSState(const std::string& state) { tdls_state_ = state; } void FakeShillDeviceClient::SetSimLocked(const std::string& device_path, bool locked) { SimLockStatus status = GetSimLockStatus(device_path); status.type = locked ? shill::kSIMLockPin : ""; status.retries_left = kSimPinRetryCount; SetSimLockStatus(device_path, status); } // Private Methods ------------------------------------------------------------- FakeShillDeviceClient::SimLockStatus FakeShillDeviceClient::GetSimLockStatus( const std::string& device_path) { SimLockStatus status; base::DictionaryValue* device_properties = nullptr; base::DictionaryValue* simlock_dict = nullptr; if (stub_devices_.GetDictionaryWithoutPathExpansion(device_path, &device_properties) && device_properties->GetDictionaryWithoutPathExpansion( shill::kSIMLockStatusProperty, &simlock_dict)) { simlock_dict->GetStringWithoutPathExpansion(shill::kSIMLockTypeProperty, &status.type); simlock_dict->GetIntegerWithoutPathExpansion( shill::kSIMLockRetriesLeftProperty, &status.retries_left); simlock_dict->GetBooleanWithoutPathExpansion(shill::kSIMLockEnabledProperty, &status.lock_enabled); if (status.type == shill::kSIMLockPin && status.retries_left == 0) status.retries_left = kSimPinRetryCount; } return status; } void FakeShillDeviceClient::SetSimLockStatus(const std::string& device_path, const SimLockStatus& status) { base::DictionaryValue* device_properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion(device_path, &device_properties)) { NOTREACHED() << "Device not found: " << device_path; return; } base::DictionaryValue* simlock_dict = nullptr; if (!device_properties->GetDictionaryWithoutPathExpansion( shill::kSIMLockStatusProperty, &simlock_dict)) { simlock_dict = new base::DictionaryValue; device_properties->SetWithoutPathExpansion(shill::kSIMLockStatusProperty, simlock_dict); } simlock_dict->Clear(); simlock_dict->SetStringWithoutPathExpansion(shill::kSIMLockTypeProperty, status.type); simlock_dict->SetIntegerWithoutPathExpansion( shill::kSIMLockRetriesLeftProperty, status.retries_left); simlock_dict->SetBooleanWithoutPathExpansion(shill::kSIMLockEnabledProperty, status.lock_enabled); NotifyObserversPropertyChanged(dbus::ObjectPath(device_path), shill::kSIMLockStatusProperty); } bool FakeShillDeviceClient::SimTryPin(const std::string& device_path, const std::string& pin) { SimLockStatus status = GetSimLockStatus(device_path); if (status.type == shill::kSIMLockPuk) { VLOG(1) << "SimTryPin called with PUK locked."; return false; // PUK locked, PIN won't work. } if (pin.length() < kSimPinMinLength) return false; std::string sim_pin = sim_pin_[device_path]; if (sim_pin.empty()) { sim_pin = kDefaultSimPin; sim_pin_[device_path] = sim_pin; } if (pin == sim_pin) { status.type = ""; status.retries_left = kSimPinRetryCount; SetSimLockStatus(device_path, status); return true; } VLOG(1) << "SIM PIN: " << pin << " != " << sim_pin << " Retries left: " << (status.retries_left - 1); if (--status.retries_left <= 0) { status.retries_left = kSimPukRetryCount; status.type = shill::kSIMLockPuk; status.lock_enabled = true; } SetSimLockStatus(device_path, status); return false; } bool FakeShillDeviceClient::SimTryPuk(const std::string& device_path, const std::string& puk) { SimLockStatus status = GetSimLockStatus(device_path); if (status.type != shill::kSIMLockPuk) { VLOG(1) << "PUK Not locked"; return true; // Not PUK locked. } if (status.retries_left == 0) { VLOG(1) << "PUK: No retries left"; return false; // Permanently locked. } if (puk == kSimPuk) { status.type = ""; status.retries_left = kSimPinRetryCount; SetSimLockStatus(device_path, status); return true; } --status.retries_left; VLOG(1) << "SIM PUK: " << puk << " != " << kSimPuk << " Retries left: " << status.retries_left; SetSimLockStatus(device_path, status); return false; } void FakeShillDeviceClient::PassStubDeviceProperties( const dbus::ObjectPath& device_path, const DictionaryValueCallback& callback) const { const base::DictionaryValue* device_properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion( device_path.value(), &device_properties)) { base::DictionaryValue empty_dictionary; callback.Run(DBUS_METHOD_CALL_FAILURE, empty_dictionary); return; } callback.Run(DBUS_METHOD_CALL_SUCCESS, *device_properties); } // Posts a task to run a void callback with status code |status|. void FakeShillDeviceClient::PostVoidCallback( const VoidDBusMethodCallback& callback, DBusMethodCallStatus status) { base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE, base::Bind(callback, status)); } void FakeShillDeviceClient::NotifyObserversPropertyChanged( const dbus::ObjectPath& device_path, const std::string& property) { base::DictionaryValue* dict = NULL; std::string path = device_path.value(); if (!stub_devices_.GetDictionaryWithoutPathExpansion(path, &dict)) { LOG(ERROR) << "Notify for unknown service: " << path; return; } base::Value* value = NULL; if (!dict->GetWithoutPathExpansion(property, &value)) { LOG(ERROR) << "Notify for unknown property: " << path << " : " << property; return; } for (auto& observer : GetObserverList(device_path)) observer.OnPropertyChanged(property, *value); } base::DictionaryValue* FakeShillDeviceClient::GetDeviceProperties( const std::string& device_path) { base::DictionaryValue* properties = NULL; if (!stub_devices_.GetDictionaryWithoutPathExpansion( device_path, &properties)) { properties = new base::DictionaryValue; stub_devices_.SetWithoutPathExpansion(device_path, properties); } return properties; } FakeShillDeviceClient::PropertyObserverList& FakeShillDeviceClient::GetObserverList(const dbus::ObjectPath& device_path) { auto iter = observer_list_.find(device_path); if (iter != observer_list_.end()) return *(iter->second); PropertyObserverList* observer_list = new PropertyObserverList(); observer_list_[device_path] = base::WrapUnique(observer_list); return *observer_list; } } // namespace chromeos
{ "language": "C++" }
#include <set> using namespace std; /* * Longest Increasing Subsequence O(nlogn) * At a given iteration i, k-th element (1-indexed) in set is the * smallest element that has a size k increasing subsequence ending in it */ int lis(int arr[], int n) { multiset<int> s; multiset<int>::iterator it; for(int i = 0; i < n; i++) { s.insert(arr[i]); it = s.upper_bound(arr[i]); //non-decreasing //it = ++s.lower_bound(arr[i]); //strictly increasing if (it != s.end()) s.erase(it); } return s.size(); } #include <cstdio> #define MAXN 1000009 int a[MAXN], n; int main() { n = 0; while(scanf("%d", &a[n]) != EOF) n++; for(int i = 0; i < n; i++) { scanf("%d", &a[i]); } printf("%d\n", n-lis(a, n)); return 0; }
{ "language": "C++" }
// (C) Copyright Gennadiy Rozental 2001. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // Description : contains definition for all test tools in test toolbox // *************************************************************************** #ifndef BOOST_TEST_UTILS_LAZY_OSTREAM_HPP #define BOOST_TEST_UTILS_LAZY_OSTREAM_HPP // Boost.Test #include <boost/test/detail/config.hpp> // STL #include <iosfwd> #include <boost/test/detail/suppress_warnings.hpp> //____________________________________________________________________________// // ************************************************************************** // // ************** lazy_ostream ************** // // ************************************************************************** // namespace network_boost { namespace unit_test { class lazy_ostream { public: virtual ~lazy_ostream() {} static lazy_ostream& instance() { static lazy_ostream inst; return inst; } friend std::ostream& operator<<( std::ostream& ostr, lazy_ostream const& o ) { return o( ostr ); } // access method bool empty() const { return m_empty; } // actual printing interface; to be accessed only by this class and children virtual std::ostream& operator()( std::ostream& ostr ) const { return ostr; } protected: explicit lazy_ostream( bool p_empty = true ) : m_empty( p_empty ) {} private: // Data members bool m_empty; }; //____________________________________________________________________________// template<typename PrevType, typename T, typename StorageT=T const&> class lazy_ostream_impl : public lazy_ostream { public: lazy_ostream_impl( PrevType const& prev, T const& value ) : lazy_ostream( false ) , m_prev( prev ) , m_value( value ) { } virtual std::ostream& operator()( std::ostream& ostr ) const { return m_prev(ostr) << m_value; } private: // Data members PrevType const& m_prev; StorageT m_value; }; //____________________________________________________________________________// template<typename T> inline lazy_ostream_impl<lazy_ostream,T> operator<<( lazy_ostream const& prev, T const& v ) { return lazy_ostream_impl<lazy_ostream,T>( prev, v ); } //____________________________________________________________________________// template<typename PrevPrevType, typename TPrev, typename T> inline lazy_ostream_impl<lazy_ostream_impl<PrevPrevType,TPrev>,T> operator<<( lazy_ostream_impl<PrevPrevType,TPrev> const& prev, T const& v ) { typedef lazy_ostream_impl<PrevPrevType,TPrev> PrevType; return lazy_ostream_impl<PrevType,T>( prev, v ); } //____________________________________________________________________________// #if BOOST_TEST_USE_STD_LOCALE template<typename R,typename S> inline lazy_ostream_impl<lazy_ostream,R& (BOOST_TEST_CALL_DECL *)(S&),R& (BOOST_TEST_CALL_DECL *)(S&)> operator<<( lazy_ostream const& prev, R& (BOOST_TEST_CALL_DECL *man)(S&) ) { typedef R& (BOOST_TEST_CALL_DECL * ManipType)(S&); return lazy_ostream_impl<lazy_ostream,ManipType,ManipType>( prev, man ); } //____________________________________________________________________________// template<typename PrevPrevType, typename TPrev,typename R,typename S> inline lazy_ostream_impl<lazy_ostream_impl<PrevPrevType,TPrev>,R& (BOOST_TEST_CALL_DECL *)(S&),R& (BOOST_TEST_CALL_DECL *)(S&)> operator<<( lazy_ostream_impl<PrevPrevType,TPrev> const& prev, R& (BOOST_TEST_CALL_DECL *man)(S&) ) { typedef R& (BOOST_TEST_CALL_DECL * ManipType)(S&); return lazy_ostream_impl<lazy_ostream_impl<PrevPrevType,TPrev>,ManipType,ManipType>( prev, man ); } //____________________________________________________________________________// #endif #define BOOST_TEST_LAZY_MSG( M ) (::network_boost::unit_test::lazy_ostream::instance() << M) } // namespace unit_test } // namespace network_boost #include <boost/test/detail/enable_warnings.hpp> #endif // BOOST_TEST_UTILS_LAZY_OSTREAM_HPP
{ "language": "C++" }
const char *neoGloss_vert_src = "uniform vec3 u_eye;\n" "layout(location = 0) in vec3 in_pos;\n" "layout(location = 1) in vec3 in_normal;\n" "layout(location = 2) in vec4 in_color;\n" "layout(location = 3) in vec2 in_tex0;\n" "out vec3 v_normal;\n" "out vec3 v_light;\n" "out vec2 v_tex0;\n" "out float v_fog;\n" "void\n" "main(void)\n" "{\n" " vec4 Vertex = u_world * vec4(in_pos, 1.0);\n" " gl_Position = u_proj * u_view * Vertex;\n" " vec3 Normal = mat3(u_world) * in_normal;\n" " v_tex0 = in_tex0;\n" " vec3 viewVec = normalize(u_eye - Vertex.xyz);\n" " vec3 Light = normalize(viewVec - u_lightDirection[0].xyz);\n" " v_normal = 0.5*(1.0 + vec3(0.0, 0.0, 1.0)); // compress\n" " v_light = 0.5*(1.0 + Light); //\n" " v_fog = DoFog(gl_Position.w);\n" "}\n" ;
{ "language": "C++" }
/**************************************************************************** * * Copyright (c) 2020 Estimation and Control Library (ECL). All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * 3. Neither the name ECL nor the names of its contributors may be * used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ /** * @file sensor_range_finder.hpp * Range finder class containing all the required checks * * @author Mathieu Bresciani <brescianimathieu@gmail.com> * */ #pragma once #include "Sensor.hpp" #include <matrix/math.hpp> namespace estimator { namespace sensor { class SensorRangeFinder : public Sensor { public: SensorRangeFinder() = default; ~SensorRangeFinder() override = default; void runChecks(uint64_t current_time_us, const matrix::Dcmf &R_to_earth); bool isHealthy() const override { return _is_sample_valid; } bool isDataHealthy() const override { return _is_sample_ready && _is_sample_valid; } void setSample(const rangeSample &sample) { _sample = sample; _is_sample_ready = true; } // This is required because of the ring buffer // TODO: move the ring buffer here rangeSample* getSampleAddress() { return &_sample; } void setPitchOffset(float new_pitch_offset) { if (fabsf(_pitch_offset_rad - new_pitch_offset) > FLT_EPSILON) { _sin_pitch_offset = sinf(new_pitch_offset); _cos_pitch_offset = cosf(new_pitch_offset); _pitch_offset_rad = new_pitch_offset; } } void setCosMaxTilt(float cos_max_tilt) { _range_cos_max_tilt = cos_max_tilt; } void setLimits(float min_distance, float max_distance) { _rng_valid_min_val = min_distance; _rng_valid_max_val = max_distance; } float getCosTilt() const { return _cos_tilt_rng_to_earth; } void setRange(float rng) { _sample.rng = rng; } float getRange() const { return _sample.rng; } float getDistBottom() const { return _sample.rng * _cos_tilt_rng_to_earth; } void setDataReadiness(bool is_ready) { _is_sample_ready = is_ready; } void setValidity(bool is_valid) { _is_sample_valid = is_valid; } float getValidMinVal() const { return _rng_valid_min_val; } float getValidMaxVal() const { return _rng_valid_max_val; } private: void updateSensorToEarthRotation(const matrix::Dcmf &R_to_earth); void updateValidity(uint64_t current_time_us); void updateDtDataLpf(uint64_t current_time_us); bool isSampleOutOfDate(uint64_t current_time_us) const; bool isDataContinuous() const { return _dt_data_lpf < 2e6f; } bool isTiltOk() const { return _cos_tilt_rng_to_earth > _range_cos_max_tilt; } bool isDataInRange() const; void updateStuckCheck(); rangeSample _sample{}; bool _is_sample_ready{}; ///< true when new range finder data has fallen behind the fusion time horizon and is available to be fused bool _is_sample_valid{}; ///< true if range finder sample retrieved from buffer is valid uint64_t _time_last_valid_us{}; ///< time the last range finder measurement was ready (uSec) /* * Stuck check */ bool _is_stuck{}; float _stuck_threshold{0.1f}; ///< minimum variation in range finder reading required to declare a range finder 'unstuck' when readings recommence after being out of range (m) float _stuck_min_val{}; ///< minimum value for new rng measurement when being stuck float _stuck_max_val{}; ///< maximum value for new rng measurement when being stuck /* * Data regularity check */ static constexpr float _dt_update{0.01f}; ///< delta time since last ekf update TODO: this should be a parameter float _dt_data_lpf{}; ///< filtered value of the delta time elapsed since the last range measurement came into the filter (uSec) /* * Tilt check */ float _cos_tilt_rng_to_earth{}; ///< 2,2 element of the rotation matrix from sensor frame to earth frame float _range_cos_max_tilt{0.7071f}; ///< cosine of the maximum tilt angle from the vertical that permits use of range finder and flow data float _pitch_offset_rad{3.14f}; ///< range finder tilt rotation about the Y body axis float _sin_pitch_offset{0.0f}; ///< sine of the range finder tilt rotation about the Y body axis float _cos_pitch_offset{-1.0f}; ///< cosine of the range finder tilt rotation about the Y body axis /* * Range check */ float _rng_valid_min_val{}; ///< minimum distance that the rangefinder can measure (m) float _rng_valid_max_val{}; ///< maximum distance that the rangefinder can measure (m) /* * Quality check */ uint64_t _time_bad_quality_us{}; ///< timestamp at which range finder signal quality was 0 (used for hysteresis) uint64_t _quality_hyst_us{1000000}; ///< minimum duration during which the reported range finder signal quality needs to be non-zero in order to be declared valid (us) }; } // namespace sensor } // namespace estimator
{ "language": "C++" }
/* -*- c++ -*- * Copyright (c) 2012-2019 by the GalSim developers team on GitHub * https://github.com/GalSim-developers * * This file is part of GalSim: The modular galaxy image simulation toolkit. * https://github.com/GalSim-developers/GalSim * * GalSim is free software: 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 disclaimer given in the accompanying LICENSE * file. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions, and the disclaimer given in the documentation * and/or other materials provided with the distribution. */ #ifndef GalSim_ImageArith_H #define GalSim_ImageArith_H #include <complex> #include "galsim/Image.h" namespace galsim { // These ops are not defined by the standard library, but might be required below. inline std::complex<double> operator*(double x, const std::complex<float>& y) { return std::complex<double>(x*y.real(), x*y.imag()); } inline std::complex<double> operator/(double x, const std::complex<float>& y) { return x * (1.F / y); } inline std::complex<float>& operator+=(std::complex<float>& x, const std::complex<double>& y) { return x += std::complex<float>(y); } // // Templates for stepping through image pixels // Not all of these are used for the below arithmetic, but we keep them all // here anyway. // /** * @brief Call a unary function on each pixel value */ template <typename T, typename Op> void for_each_pixel_ref(const BaseImage<T>& image, Op& f) { const T* ptr = image.getData(); if (ptr) { const int skip = image.getNSkip(); const int step = image.getStep(); const int nrow = image.getNRow(); const int ncol = image.getNCol(); if (step == 1) { for (int j=0; j<nrow; j++, ptr+=skip) for (int i=0; i<ncol; i++) f(*ptr++); } else { for (int j=0; j<nrow; j++, ptr+=skip) for (int i=0; i<ncol; i++, ptr+=step) f(*ptr); } } } template <typename T, typename Op> void for_each_pixel(const BaseImage<T>& image, Op f) { for_each_pixel_ref(image, f); } /** * @brief Call a function of (value, i, j) on each pixel value */ template <typename T, typename Op> void for_each_pixel_ij_ref(const BaseImage<T>& image, Op& f) { const T* ptr = image.getData(); if (ptr) { const int skip = image.getNSkip(); const int step = image.getStep(); const int xmin = image.getXMin(); const int xmax = image.getXMax(); const int ymin = image.getYMin(); const int ymax = image.getYMax(); if (step == 1) { for (int j=ymin; j<=ymax; j++, ptr+=skip) for (int i=xmin; i<=xmax; i++) f(*ptr++,i,j); } else { for (int j=ymin; j<=ymax; j++, ptr+=skip) for (int i=xmin; i<=xmax; i++, ptr+=step) f(*ptr,i,j); } } } template <typename T, typename Op> void for_each_pixel_ij(const BaseImage<T>& image, Op f) { for_each_pixel_ij_ref(image, f); } /** * @brief Replace image with a function of its pixel values. */ template <typename T, typename Op> void transform_pixel_ref(ImageView<T> image, Op& f) { T* ptr = image.getData(); if (ptr) { const int skip = image.getNSkip(); const int step = image.getStep(); const int nrow = image.getNRow(); const int ncol = image.getNCol(); if (step == 1) { for (int j=0; j<nrow; j++, ptr+=skip) for (int i=0; i<ncol; i++, ++ptr) *ptr = f(*ptr); } else { for (int j=0; j<nrow; j++, ptr+=skip) for (int i=0; i<ncol; i++, ptr+=step) *ptr = f(*ptr); } } } template <typename T, typename Op> void transform_pixel(ImageView<T> image, Op f) { transform_pixel_ref(image, f); } /** * @brief Assign function of 2 images to 1st */ template <typename T1, typename T2, typename Op> void transform_pixel_ref(ImageView<T1> image1, const BaseImage<T2>& image2, Op& f) { T1* ptr1 = image1.getData(); if (ptr1) { if (!image1.getBounds().isSameShapeAs(image2.getBounds())) throw ImageError("transform_pixel image bounds are not same shape"); const int skip1 = image1.getNSkip(); const int step1 = image1.getStep(); const int nrow = image1.getNRow(); const int ncol = image1.getNCol(); const T2* ptr2 = image2.getData(); const int skip2 = image2.getNSkip(); const int step2 = image2.getStep(); if (step1 == 1 && step2 == 1) { for (int j=0; j<nrow; j++, ptr1+=skip1, ptr2+=skip2) for (int i=0; i<ncol; i++, ++ptr1, ++ptr2) *ptr1 = f(*ptr1,T1(*ptr2)); } else { for (int j=0; j<nrow; j++, ptr1+=skip1, ptr2+=skip2) for (int i=0; i<ncol; i++, ptr1+=step1, ptr2+=step2) *ptr1 = f(*ptr1,T1(*ptr2)); } } } template <typename T1, typename T2, typename Op> void transform_pixel(ImageView<T1> image1, const BaseImage<T2>& image2, Op f) { transform_pixel_ref(image1, image2, f); } // Some functionals that are useful for operating on images: template <typename T> class ConstReturn { public: ConstReturn(const T v): val(v) {} inline T operator()(const T ) const { return val; } private: T val; }; template <typename T> class ReturnInverse { public: inline T operator()(const T val) const { return val==T(0) ? T(0.) : T(1./val); } }; template <typename T, typename T2> class AddConstant { const T2 _x; public: AddConstant(const T2 x) : _x(x) {} inline T operator()(const T val) const { return T(_x + val); } }; template <typename T, typename T2> class MultiplyConstant { const T2 _x; public: MultiplyConstant(const T2 x) : _x(x) {} inline T operator()(const T val) const { return T(_x * val); } }; template <typename T, typename T2, bool is_int> class DivideConstant // is_int=False { const T2 _invx; public: DivideConstant(const T2 x) : _invx(T2(1)/x) {} inline T operator()(const T val) const { return T(val * _invx); } }; template <typename T, typename T2> class DivideConstant<T,T2,true> { const T2 _x; public: DivideConstant(const T2 x) : _x(x) {} inline T operator()(const T val) const { return T(val / _x); } }; // All code between the @cond and @endcond is excluded from Doxygen documentation //! @cond // Default uses T1 as the result type template <typename T1, typename T2> struct ResultType { typedef T1 type; }; // Specialize relevant cases where T2 should be the result type template <> struct ResultType<float,double> { typedef double type; }; template <> struct ResultType<int32_t,double> { typedef double type; }; template <> struct ResultType<int16_t,double> { typedef double type; }; template <> struct ResultType<uint32_t,double> { typedef double type; }; template <> struct ResultType<uint16_t,double> { typedef double type; }; template <> struct ResultType<int32_t,float> { typedef float type; }; template <> struct ResultType<int16_t,float> { typedef float type; }; template <> struct ResultType<uint32_t,float> { typedef float type; }; template <> struct ResultType<uint16_t,float> { typedef float type; }; template <> struct ResultType<int16_t,int32_t> { typedef int32_t type; }; template <> struct ResultType<uint16_t,uint32_t> { typedef uint32_t type; }; // For convenience below... #define CT std::complex<T> // // Image + Scalar // template <typename T1, typename T2> class SumIX : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; SumIX(const BaseImage<T1>& im, const T2 x) : AssignableToImage<result_type>(im.getBounds()), _im(im), _x(x) {} void assignTo(ImageView<result_type> rhs) const { rhs = _im; rhs += _x; } private: const BaseImage<T1>& _im; const T2 _x; }; // Currently, the only valid type for x is the value type of im. // The reason is that making the type of x a template opens the door // to any class, not just POD. I don't know of an easy way to make // this only valid for T2 = POD types like int16_t, int32_t, float, double. // So if we do want to allow mixed types for these, we'd probably have to // specifically overload each one by hand. // Update: we do allow arithmetic between complex images and their corresponding real scalar. template <typename T> inline SumIX<T,T> operator+(const BaseImage<T>& im, T x) { return SumIX<T,T>(im,x); } template <typename T> inline SumIX<T,T> operator+(T x, const BaseImage<T>& im) { return SumIX<T,T>(im,x); } template <typename T> inline ImageView<T> operator+=(ImageView<T> im, T x) { transform_pixel(im, AddConstant<T,T>(x)); return im; } template <typename T> inline ImageAlloc<T>& operator+=(ImageAlloc<T>& im, const T& x) { im.view() += x; return im; } template <typename T> inline SumIX<CT,T> operator+(const BaseImage<CT>& im, T x) { return SumIX<CT,T>(im,x); } template <typename T> inline SumIX<CT,T> operator+(T x, const BaseImage<CT>& im) { return SumIX<CT,T>(im,x); } template <typename T> inline ImageView<CT> operator+=(ImageView<CT> im, T x) { transform_pixel(im, AddConstant<CT,T>(x)); return im; } template <typename T> inline ImageAlloc<CT>& operator+=(ImageAlloc<CT>& im, const T& x) { im.view() += x; return im; } // // Image - Scalar // template <typename T> inline SumIX<T,T> operator-(const BaseImage<T>& im, T x) { return SumIX<T,T>(im,-x); } template <typename T> inline ImageView<T> operator-=(ImageView<T> im, const T& x) { im += T(-x); return im; } template <typename T> inline ImageAlloc<T>& operator-=(ImageAlloc<T>& im, const T& x) { im.view() -= x; return im; } template <typename T> inline SumIX<CT,T> operator-(const BaseImage<CT>& im, T x) { return SumIX<CT,T>(im,-x); } template <typename T> inline ImageView<CT> operator-=(ImageView<CT> im, T x) { im += T(-x); return im; } template <typename T> inline ImageAlloc<CT>& operator-=(ImageAlloc<CT>& im, const T& x) { im.view() -= x; return im; } // // Image * Scalar // template <typename T1, typename T2> class ProdIX : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; ProdIX(const BaseImage<T1>& im, const T2 x) : AssignableToImage<result_type>(im.getBounds()), _im(im), _x(x) {} void assignTo(ImageView<result_type> rhs) const { rhs = _im; rhs *= _x; } private: const BaseImage<T1>& _im; const T2 _x; }; template <typename T> inline ProdIX<T,T> operator*(const BaseImage<T>& im, T x) { return ProdIX<T,T>(im,x); } template <typename T> inline ProdIX<T,T> operator*(T x, const BaseImage<T>& im) { return ProdIX<T,T>(im,x); } template <typename T> inline ImageView<T> operator*=(ImageView<T> im, const T& x) { transform_pixel(im, MultiplyConstant<T,T>(x)); return im; } template <typename T> inline ImageAlloc<T>& operator*=(ImageAlloc<T>& im, const T& x) { im.view() *= x; return im; } template <typename T> inline ProdIX<CT,T> operator*(const BaseImage<CT>& im, T x) { return ProdIX<CT,T>(im,x); } template <typename T> inline ProdIX<CT,T> operator*(T x, const BaseImage<CT>& im) { return ProdIX<CT,T>(im,x); } template <typename T> inline ImageView<CT> operator*=(ImageView<CT> im, T x) { transform_pixel(im, MultiplyConstant<CT,T>(x)); return im; } template <typename T> inline ImageAlloc<CT>& operator*=(ImageAlloc<CT>& im, const T& x) { im.view() *= x; return im; } // Specialize variants that can be sped up using SSE ImageView<float> operator*=(ImageView<float> im, float x); ImageView<std::complex<float> > operator*=(ImageView<std::complex<float> > im, float x); ImageView<std::complex<float> > operator*=(ImageView<std::complex<float> > im, std::complex<float> x); ImageView<double> operator*=(ImageView<double> im, double x); ImageView<std::complex<double> > operator*=(ImageView<std::complex<double> > im, double x); ImageView<std::complex<double> > operator*=(ImageView<std::complex<double> > im, std::complex<double> x); // // Image / Scalar // template <typename T1, typename T2> class QuotIX : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; QuotIX(const BaseImage<T1>& im, const T2 x) : AssignableToImage<result_type>(im.getBounds()), _im(im), _x(x) {} void assignTo(ImageView<result_type> rhs) const { rhs = _im; rhs /= _x; } private: const BaseImage<T1>& _im; const T2 _x; }; template <typename T> inline QuotIX<T,T> operator/(const BaseImage<T>& im, T x) { return QuotIX<T,T>(im,x); } #define INT(T) std::numeric_limits<T>::is_integer template <typename T> inline ImageView<T> operator/=(ImageView<T> im, T x) { transform_pixel(im, DivideConstant<T,T,INT(T)>(x)); return im; } template <typename T> inline ImageAlloc<T>& operator/=(ImageAlloc<T>& im, const T& x) { im.view() /= x; return im; } template <typename T> inline QuotIX<CT,T> operator/(const BaseImage<CT>& im, T x) { return QuotIX<CT,T>(im,x); } template <typename T> inline ImageView<CT> operator/=(ImageView<CT> im, T x) { transform_pixel(im, DivideConstant<CT,T,INT(T)>(x)); return im; } template <typename T> inline ImageAlloc<CT>& operator/=(ImageAlloc<CT>& im, const T& x) { im.view() /= x; return im; } #undef CT // // Image + Image // template <typename T1, typename T2> class SumII : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; SumII(const BaseImage<T1>& im1, const BaseImage<T2>& im2) : AssignableToImage<result_type>(im1.getBounds()), _im1(im1), _im2(im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 + im2, but bounds not the same shape"); } void assignTo(ImageView<result_type> rhs) const { rhs = _im1; rhs += _im2; } private: const BaseImage<T1>& _im1; const BaseImage<T2>& _im2; }; template <typename T1, typename T2> inline SumII<T1,T2> operator+(const BaseImage<T1>& im1, const BaseImage<T2>& im2) { return SumII<T1,T2>(im1,im2); } template <typename T1, typename T2> inline ImageView<T1> operator+=(ImageView<T1> im1, const BaseImage<T2>& im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 += im2, but bounds not the same shape"); transform_pixel(im1, im2, std::plus<T1>()); return im1; } template <typename T1, typename T2> inline ImageAlloc<T1>& operator+=(ImageAlloc<T1>& im, const BaseImage<T2>& im2) { im.view() += im2; return im; } // // Image - Image // template <typename T1, typename T2> class DiffII : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; DiffII(const BaseImage<T1>& im1, const BaseImage<T2>& im2) : AssignableToImage<result_type>(im1.getBounds()), _im1(im1), _im2(im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 - im2, but bounds not the same shape"); } void assignTo(ImageView<result_type> rhs) const { rhs = _im1; rhs -= _im2; } private: const BaseImage<T1>& _im1; const BaseImage<T2>& _im2; }; template <typename T1, typename T2> inline DiffII<T1,T2> operator-(const BaseImage<T1>& im1, const BaseImage<T2>& im2) { return DiffII<T1,T2>(im1,im2); } template <typename T1, typename T2> inline ImageView<T1> operator-=(ImageView<T1> im1, const BaseImage<T2>& im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 -= im2, but bounds not the same shape"); transform_pixel(im1, im2, std::minus<T1>()); return im1; } template <typename T1, typename T2> inline ImageAlloc<T1>& operator-=(ImageAlloc<T1>& im, const BaseImage<T2>& im2) { im.view() -= im2; return im; } // // Image * Image // template <typename T1, typename T2> class ProdII : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; ProdII(const BaseImage<T1>& im1, const BaseImage<T2>& im2) : AssignableToImage<result_type>(im1.getBounds()), _im1(im1), _im2(im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 * im2, but bounds not the same shape"); } void assignTo(ImageView<result_type> rhs) const { rhs = _im1; rhs *= _im2; } private: const BaseImage<T1>& _im1; const BaseImage<T2>& _im2; }; template <typename T1, typename T2> inline ProdII<T1,T2> operator*(const BaseImage<T1>& im1, const BaseImage<T2>& im2) { return ProdII<T1,T2>(im1,im2); } template <typename T1, typename T2> inline ImageView<T1> operator*=(ImageView<T1> im1, const BaseImage<T2>& im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 *= im2, but bounds not the same shape"); transform_pixel(im1, im2, std::multiplies<T1>()); return im1; } template <typename T1, typename T2> inline ImageAlloc<T1>& operator*=(ImageAlloc<T1>& im, const BaseImage<T2>& im2) { im.view() *= im2; return im; } // Specialize variants that can be sped up using SSE ImageView<float> operator*=(ImageView<float> im1, const BaseImage<float>& im2); ImageView<std::complex<float> > operator*=(ImageView<std::complex<float> > im1, const BaseImage<float>& im2); ImageView<std::complex<float> > operator*=(ImageView<std::complex<float> > im1, const BaseImage<std::complex<float> >& im2); ImageView<double> operator*=(ImageView<double> im1, const BaseImage<double>& im2); ImageView<std::complex<double> > operator*=(ImageView<std::complex<double> > im1, const BaseImage<double>& im2); ImageView<std::complex<double> > operator*=(ImageView<std::complex<double> > im1, const BaseImage<std::complex<double> >& im2); // // Image / Image // template <typename T1, typename T2> class QuotII : public AssignableToImage<typename ResultType<T1,T2>::type> { public: typedef typename ResultType<T1,T2>::type result_type; QuotII(const BaseImage<T1>& im1, const BaseImage<T2>& im2) : AssignableToImage<result_type>(im1.getBounds()), _im1(im1), _im2(im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 / im2, but bounds not the same shape"); } void assignTo(ImageView<result_type> rhs) const { rhs = _im1; rhs /= _im2; } private: const BaseImage<T1>& _im1; const BaseImage<T2>& _im2; }; template <typename T1, typename T2> inline QuotII<T1,T2> operator/(const BaseImage<T1>& im1, const BaseImage<T2>& im2) { return QuotII<T1,T2>(im1,im2); } template <typename T1, typename T2> inline ImageView<T1> operator/=(ImageView<T1> im1, const BaseImage<T2>& im2) { if (!im1.getBounds().isSameShapeAs(im2.getBounds())) throw ImageError("Attempt im1 /= im2, but bounds not the same shape"); transform_pixel(im1, im2, std::divides<T1>()); return im1; } template <typename T1, typename T2> inline ImageAlloc<T1>& operator/=(ImageAlloc<T1>& im, const BaseImage<T2>& im2) { im.view() /= im2; return im; } //! @endcond } // namespace galsim #endif
{ "language": "C++" }
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*- #ifndef __javax_swing_event_ListDataListener__ #define __javax_swing_event_ListDataListener__ #pragma interface #include <java/lang/Object.h> extern "Java" { namespace javax { namespace swing { namespace event { class ListDataEvent; class ListDataListener; } } } } class javax::swing::event::ListDataListener : public ::java::lang::Object { public: virtual void contentsChanged(::javax::swing::event::ListDataEvent *) = 0; virtual void intervalAdded(::javax::swing::event::ListDataEvent *) = 0; virtual void intervalRemoved(::javax::swing::event::ListDataEvent *) = 0; static ::java::lang::Class class$; } __attribute__ ((java_interface)); #endif // __javax_swing_event_ListDataListener__
{ "language": "C++" }
#include <iostream> #include <queue> #include <stdio.h> #include <string.h> using namespace std; int N; char order[10]; int dir[6][3] = { {0,0,1}, {0,1,0}, {1,0,0}, {0,0,-1}, {0,-1,0}, {-1,0,0} }; const int MAXN = 20; int vis[MAXN][MAXN][MAXN]; char map[MAXN][MAXN][MAXN]; typedef struct my_node{ int x,y,z,steps; }node; int s_x, s_y, s_z; int e_x, e_y, e_z; int main(){ while(scanf("%s %d",order, &N)!=EOF){ for(int k=0; k<N; k++){ for(int i=0; i<N; i++){ scanf("%s",map[i][k]); } } /* cout<<"______________"<<endl; for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ cout<<map[j][i]<<endl; } } cout<<"--------------"<<endl; */ scanf("%d%d%d",&s_x,&s_y,&s_z); scanf("%d%d%d",&e_x,&e_y,&e_z); swap(s_x,s_y); swap(e_x,e_y); swap(s_y,s_z); swap(e_y,e_z); memset(vis,0,sizeof(vis)); node cur,next; cur.x = s_x, cur.y = s_y, cur.z = s_z, cur.steps=0; vis[cur.x][cur.y][cur.z]=1; queue<node> Q; Q.push(cur); int ans = -1; while(!Q.empty()){ cur = Q.front(); Q.pop(); //cout<<cur.x<<" "<<cur.y<<" "<<cur.z<<" "<<map[cur.x][cur.y][cur.z]<<endl; if(cur.x==e_x && cur.y==e_y && cur.z == e_z){ ans = cur.steps; break; } for(int i=0; i<6; i++){ int n_x = cur.x+dir[i][0]; int n_y = cur.y+dir[i][1]; int n_z = cur.z+dir[i][2]; if(n_x >=0 && n_x<N && n_y>=0 && n_y<N && n_z>=0 && n_z<N && vis[n_x][n_y][n_z]==0&& map[n_x][n_y][n_z]!='X'){ next.x = n_x, next.y = n_y, next.z = n_z, next.steps = cur.steps+1; vis[n_x][n_y][n_z]=1; Q.push(next); } } } scanf("%s",order); if(ans==-1){ cout<<"NO ROUTE"<<endl; }else{ cout<<N<<" "<<ans<<endl; } } return 0; }
{ "language": "C++" }
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE127_Buffer_Underread__wchar_t_alloca_cpy_82a.cpp Label Definition File: CWE127_Buffer_Underread.stack.label.xml Template File: sources-sink-82a.tmpl.cpp */ /* * @description * CWE: 127 Buffer Under-read * BadSource: Set data pointer to before the allocated memory buffer * GoodSource: Set data pointer to the allocated memory buffer * Sinks: cpy * BadSink : Copy data to string using wcscpy * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer * * */ #include "std_testcase.h" #include "CWE127_Buffer_Underread__wchar_t_alloca_cpy_82.h" namespace CWE127_Buffer_Underread__wchar_t_alloca_cpy_82 { #ifndef OMITBAD void bad() { wchar_t * data; wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); wmemset(dataBuffer, L'A', 100-1); dataBuffer[100-1] = L'\0'; /* FLAW: Set data pointer to before the allocated memory buffer */ data = dataBuffer - 8; CWE127_Buffer_Underread__wchar_t_alloca_cpy_82_base* baseObject = new CWE127_Buffer_Underread__wchar_t_alloca_cpy_82_bad; baseObject->action(data); delete baseObject; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; wchar_t * dataBuffer = (wchar_t *)ALLOCA(100*sizeof(wchar_t)); wmemset(dataBuffer, L'A', 100-1); dataBuffer[100-1] = L'\0'; /* FIX: Set data pointer to the allocated memory buffer */ data = dataBuffer; CWE127_Buffer_Underread__wchar_t_alloca_cpy_82_base* baseObject = new CWE127_Buffer_Underread__wchar_t_alloca_cpy_82_goodG2B; baseObject->action(data); delete baseObject; } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE127_Buffer_Underread__wchar_t_alloca_cpy_82; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
{ "language": "C++" }
// Boost.Range library // // Copyright Thorsten Ottosen 2003-2004. Use, modification and // distribution is subject to the Boost Software License, Version // 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // For more information, see http://www.boost.org/libs/range/ // #ifndef BOOST_RANGE_RBEGIN_HPP #define BOOST_RANGE_RBEGIN_HPP #if defined(_MSC_VER) # pragma once #endif #include <boost/range/end.hpp> #include <boost/range/reverse_iterator.hpp> namespace boost { #ifdef BOOST_NO_FUNCTION_TEMPLATE_ORDERING template< class C > inline BOOST_DEDUCED_TYPENAME range_reverse_iterator<C>::type rbegin( C& c ) { return BOOST_DEDUCED_TYPENAME range_reverse_iterator<C>::type( boost::end( c ) ); } #else template< class C > inline BOOST_DEDUCED_TYPENAME range_reverse_iterator<C>::type rbegin( C& c ) { typedef BOOST_DEDUCED_TYPENAME range_reverse_iterator<C>::type iter_type; return iter_type( boost::end( c ) ); } template< class C > inline BOOST_DEDUCED_TYPENAME range_reverse_iterator<const C>::type rbegin( const C& c ) { typedef BOOST_DEDUCED_TYPENAME range_reverse_iterator<const C>::type iter_type; return iter_type( boost::end( c ) ); } #endif // BOOST_NO_FUNCTION_TEMPLATE_ORDERING template< class T > inline BOOST_DEDUCED_TYPENAME range_reverse_iterator<const T>::type const_rbegin( const T& r ) { return boost::rbegin( r ); } } // namespace 'boost' #endif
{ "language": "C++" }
/* ********************************************************************** * Copyright (c) 2002-2012, International Business Machines Corporation * and others. All Rights Reserved. ********************************************************************** * Date Name Description * 01/21/2002 aliu Creation. ********************************************************************** */ #include "unicode/utypes.h" #if !UCONFIG_NO_TRANSLITERATION #include "unicode/uniset.h" #include "unicode/utf16.h" #include "strrepl.h" #include "rbt_data.h" #include "util.h" U_NAMESPACE_BEGIN UnicodeReplacer::~UnicodeReplacer() {} UOBJECT_DEFINE_RTTI_IMPLEMENTATION(StringReplacer) /** * Construct a StringReplacer that sets the emits the given output * text and sets the cursor to the given position. * @param theOutput text that will replace input text when the * replace() method is called. May contain stand-in characters * that represent nested replacers. * @param theCursorPos cursor position that will be returned by * the replace() method * @param theData transliterator context object that translates * stand-in characters to UnicodeReplacer objects */ StringReplacer::StringReplacer(const UnicodeString& theOutput, int32_t theCursorPos, const TransliterationRuleData* theData) { output = theOutput; cursorPos = theCursorPos; hasCursor = TRUE; data = theData; isComplex = TRUE; } /** * Construct a StringReplacer that sets the emits the given output * text and does not modify the cursor. * @param theOutput text that will replace input text when the * replace() method is called. May contain stand-in characters * that represent nested replacers. * @param theData transliterator context object that translates * stand-in characters to UnicodeReplacer objects */ StringReplacer::StringReplacer(const UnicodeString& theOutput, const TransliterationRuleData* theData) { output = theOutput; cursorPos = 0; hasCursor = FALSE; data = theData; isComplex = TRUE; } /** * Copy constructor. */ StringReplacer::StringReplacer(const StringReplacer& other) : UnicodeFunctor(other), UnicodeReplacer(other) { output = other.output; cursorPos = other.cursorPos; hasCursor = other.hasCursor; data = other.data; isComplex = other.isComplex; } /** * Destructor */ StringReplacer::~StringReplacer() { } /** * Implement UnicodeFunctor */ UnicodeFunctor* StringReplacer::clone() const { return new StringReplacer(*this); } /** * Implement UnicodeFunctor */ UnicodeReplacer* StringReplacer::toReplacer() const { return const_cast<StringReplacer *>(this); } /** * UnicodeReplacer API */ int32_t StringReplacer::replace(Replaceable& text, int32_t start, int32_t limit, int32_t& cursor) { int32_t outLen; int32_t newStart = 0; // NOTE: It should be possible to _always_ run the complex // processing code; just slower. If not, then there is a bug // in the complex processing code. // Simple (no nested replacers) Processing Code : if (!isComplex) { text.handleReplaceBetween(start, limit, output); outLen = output.length(); // Setup default cursor position (for cursorPos within output) newStart = cursorPos; } // Complex (nested replacers) Processing Code : else { /* When there are segments to be copied, use the Replaceable.copy() * API in order to retain out-of-band data. Copy everything to the * end of the string, then copy them back over the key. This preserves * the integrity of indices into the key and surrounding context while * generating the output text. */ UnicodeString buf; int32_t oOutput; // offset into 'output' isComplex = FALSE; // The temporary buffer starts at tempStart, and extends // to destLimit. The start of the buffer has a single // character from before the key. This provides style // data when addition characters are filled into the // temporary buffer. If there is nothing to the left, use // the non-character U+FFFF, which Replaceable subclasses // should treat specially as a "no-style character." // destStart points to the point after the style context // character, so it is tempStart+1 or tempStart+2. int32_t tempStart = text.length(); // start of temp buffer int32_t destStart = tempStart; // copy new text to here if (start > 0) { int32_t len = U16_LENGTH(text.char32At(start-1)); text.copy(start-len, start, tempStart); destStart += len; } else { UnicodeString str((UChar) 0xFFFF); text.handleReplaceBetween(tempStart, tempStart, str); destStart++; } int32_t destLimit = destStart; for (oOutput=0; oOutput<output.length(); ) { if (oOutput == cursorPos) { // Record the position of the cursor newStart = destLimit - destStart; // relative to start } UChar32 c = output.char32At(oOutput); UnicodeReplacer* r = data->lookupReplacer(c); if (r == NULL) { // Accumulate straight (non-segment) text. buf.append(c); } else { isComplex = TRUE; // Insert any accumulated straight text. if (buf.length() > 0) { text.handleReplaceBetween(destLimit, destLimit, buf); destLimit += buf.length(); buf.truncate(0); } // Delegate output generation to replacer object int32_t len = r->replace(text, destLimit, destLimit, cursor); destLimit += len; } oOutput += U16_LENGTH(c); } // Insert any accumulated straight text. if (buf.length() > 0) { text.handleReplaceBetween(destLimit, destLimit, buf); destLimit += buf.length(); } if (oOutput == cursorPos) { // Record the position of the cursor newStart = destLimit - destStart; // relative to start } outLen = destLimit - destStart; // Copy new text to start, and delete it text.copy(destStart, destLimit, start); text.handleReplaceBetween(tempStart + outLen, destLimit + outLen, UnicodeString()); // Delete the old text (the key) text.handleReplaceBetween(start + outLen, limit + outLen, UnicodeString()); } if (hasCursor) { // Adjust the cursor for positions outside the key. These // refer to code points rather than code units. If cursorPos // is within the output string, then use newStart, which has // already been set above. if (cursorPos < 0) { newStart = start; int32_t n = cursorPos; // Outside the output string, cursorPos counts code points while (n < 0 && newStart > 0) { newStart -= U16_LENGTH(text.char32At(newStart-1)); ++n; } newStart += n; } else if (cursorPos > output.length()) { newStart = start + outLen; int32_t n = cursorPos - output.length(); // Outside the output string, cursorPos counts code points while (n > 0 && newStart < text.length()) { newStart += U16_LENGTH(text.char32At(newStart)); --n; } newStart += n; } else { // Cursor is within output string. It has been set up above // to be relative to start. newStart += start; } cursor = newStart; } return outLen; } /** * UnicodeReplacer API */ UnicodeString& StringReplacer::toReplacerPattern(UnicodeString& rule, UBool escapeUnprintable) const { rule.truncate(0); UnicodeString quoteBuf; int32_t cursor = cursorPos; // Handle a cursor preceding the output if (hasCursor && cursor < 0) { while (cursor++ < 0) { ICU_Utility::appendToRule(rule, (UChar)0x0040 /*@*/, TRUE, escapeUnprintable, quoteBuf); } // Fall through and append '|' below } for (int32_t i=0; i<output.length(); ++i) { if (hasCursor && i == cursor) { ICU_Utility::appendToRule(rule, (UChar)0x007C /*|*/, TRUE, escapeUnprintable, quoteBuf); } UChar c = output.charAt(i); // Ok to use 16-bits here UnicodeReplacer* r = data->lookupReplacer(c); if (r == NULL) { ICU_Utility::appendToRule(rule, c, FALSE, escapeUnprintable, quoteBuf); } else { UnicodeString buf; r->toReplacerPattern(buf, escapeUnprintable); buf.insert(0, (UChar)0x20); buf.append((UChar)0x20); ICU_Utility::appendToRule(rule, buf, TRUE, escapeUnprintable, quoteBuf); } } // Handle a cursor after the output. Use > rather than >= because // if cursor == output.length() it is at the end of the output, // which is the default position, so we need not emit it. if (hasCursor && cursor > output.length()) { cursor -= output.length(); while (cursor-- > 0) { ICU_Utility::appendToRule(rule, (UChar)0x0040 /*@*/, TRUE, escapeUnprintable, quoteBuf); } ICU_Utility::appendToRule(rule, (UChar)0x007C /*|*/, TRUE, escapeUnprintable, quoteBuf); } // Flush quoteBuf out to result ICU_Utility::appendToRule(rule, -1, TRUE, escapeUnprintable, quoteBuf); return rule; } /** * Implement UnicodeReplacer */ void StringReplacer::addReplacementSetTo(UnicodeSet& toUnionTo) const { UChar32 ch; for (int32_t i=0; i<output.length(); i+=U16_LENGTH(ch)) { ch = output.char32At(i); UnicodeReplacer* r = data->lookupReplacer(ch); if (r == NULL) { toUnionTo.add(ch); } else { r->addReplacementSetTo(toUnionTo); } } } /** * UnicodeFunctor API */ void StringReplacer::setData(const TransliterationRuleData* d) { data = d; int32_t i = 0; while (i<output.length()) { UChar32 c = output.char32At(i); UnicodeFunctor* f = data->lookup(c); if (f != NULL) { f->setData(data); } i += U16_LENGTH(c); } } U_NAMESPACE_END #endif /* #if !UCONFIG_NO_TRANSLITERATION */ //eof
{ "language": "C++" }
/* * Copyright 2006-2008 The FLWOR Foundation. * * 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 "stdafx.h" #include "compiler/expression/expr.h" #include "compiler/expression/fo_expr.h" #include "compiler/expression/path_expr.h" #include "compiler/expression/flwor_expr.h" #include "compiler/expression/script_exprs.h" #include "compiler/expression/update_exprs.h" #include "compiler/expression/function_item_expr.h" #include "compiler/expression/expr_iter.h" #include "compiler/rewriter/tools/dataflow_annotations.h" #include "compiler/rewriter/framework/rewriter_context.h" #include "types/typeops.h" #include "functions/function.h" #include "functions/udf.h" #include "functions/library.h" #include "diagnostics/assert.h" namespace zorba { #define SORTED_NODES(e) \ e->setProducesSortedNodes(ANNOTATION_TRUE) #define PROPOGATE_SORTED_NODES(src, tgt) \ tgt->setProducesSortedNodes(src->getProducesSortedNodes()) #define DISTINCT_NODES(e) \ e->setProducesDistinctNodes(ANNOTATION_TRUE) #define PROPOGATE_DISTINCT_NODES(src, tgt) \ tgt->setProducesDistinctNodes(src->getProducesDistinctNodes()) /******************************************************************************* Determine whether an expr produces sorted and/or distinct nodes or not. ********************************************************************************/ void DataflowAnnotationsComputer::compute(expr* e) { switch(e->get_expr_kind()) { case var_decl_expr_kind: compute_var_decl_expr(static_cast<var_decl_expr*>(e)); break; case var_set_expr_kind: compute_var_set_expr(static_cast<var_set_expr*>(e)); break; case block_expr_kind: compute_block_expr(static_cast<block_expr *>(e)); break; case apply_expr_kind: { apply_expr* exp = static_cast<apply_expr *>(e); if (exp->discardsXDM()) { SORTED_NODES(exp); DISTINCT_NODES(exp); } else { default_walk(e); PROPOGATE_SORTED_NODES(exp->get_expr(), exp); PROPOGATE_DISTINCT_NODES(exp->get_expr(), exp); } break; } case exit_catcher_expr_kind: { default_walk(e); generic_compute(e); break; } case exit_expr_kind: { default_walk(e); SORTED_NODES(e); DISTINCT_NODES(e); break; } case flowctl_expr_kind: // TODO case while_expr_kind: // TODO break; case promote_expr_kind: case cast_expr_kind: case name_cast_expr_kind: case castable_expr_kind: case instanceof_expr_kind: { default_walk(e); SORTED_NODES(e); DISTINCT_NODES(e); break; } case treat_expr_kind: { default_walk(e); if (!generic_compute(e)) { treat_expr* ue = static_cast<treat_expr*>(e); PROPOGATE_SORTED_NODES(ue->get_input(), e); PROPOGATE_DISTINCT_NODES(ue->get_input(), e); } break; } case wrapper_expr_kind: { default_walk(e); wrapper_expr* ue = static_cast<wrapper_expr*>(e); PROPOGATE_SORTED_NODES(ue->get_input(), e); PROPOGATE_DISTINCT_NODES(ue->get_input(), e); break; } case function_trace_expr_kind: { default_walk(e); function_trace_expr* ue = static_cast<function_trace_expr*>(e); PROPOGATE_SORTED_NODES(ue->get_input(), e); PROPOGATE_DISTINCT_NODES(ue->get_input(), e); break; } case var_expr_kind: compute_var_expr(static_cast<var_expr *>(e)); break; case flwor_expr_kind: compute_flwor_expr(static_cast<flwor_expr *>(e)); break; case trycatch_expr_kind: compute_trycatch_expr(static_cast<trycatch_expr *>(e)); break; case if_expr_kind: compute_if_expr(static_cast<if_expr *>(e)); break; case fo_expr_kind: compute_fo_expr(static_cast<fo_expr *>(e)); break; case validate_expr_kind: compute_validate_expr(static_cast<validate_expr *>(e)); break; case extension_expr_kind: compute_extension_expr(static_cast<extension_expr *>(e)); break; case relpath_expr_kind: compute_relpath_expr(static_cast<relpath_expr *>(e)); break; case axis_step_expr_kind: compute_axis_step_expr(static_cast<axis_step_expr *>(e)); break; case match_expr_kind: compute_match_expr(static_cast<match_expr *>(e)); break; case const_expr_kind: compute_const_expr(static_cast<const_expr *>(e)); break; case order_expr_kind: compute_order_expr(static_cast<order_expr *>(e)); break; case elem_expr_kind: case doc_expr_kind: case attr_expr_kind: case namespace_expr_kind: case text_expr_kind: case pi_expr_kind: { default_walk(e); SORTED_NODES(e); DISTINCT_NODES(e); break; } case json_direct_object_expr_kind: case json_object_expr_kind: case json_array_expr_kind: { default_walk(e); SORTED_NODES(e); DISTINCT_NODES(e); } case dynamic_function_invocation_expr_kind: // TODO case argument_placeholder_expr_kind: // TODO case function_item_expr_kind: // TODO case delete_expr_kind: // TODO case insert_expr_kind: // TODO case rename_expr_kind: // TODO case replace_expr_kind: // TODO case transform_expr_kind: // TODO #ifndef ZORBA_NO_FULL_TEXT case ft_expr_kind: // TODO #endif case eval_expr_kind: // TODO case debugger_expr_kind: // TODO break; default: ZORBA_ASSERT(false); } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::default_walk(expr* e) { ExprIterator iter(e); while(!iter.done()) { expr* child = (**iter); if (child != NULL) { compute(child); } iter.next(); } } /******************************************************************************* Return true if the given expr does not produce duplicate nodes and returns all nodes in document order. Without any info about the kind of the expr, the only thing we can do here is checks whether the expression has a return type with a quantifier of ONE or QUESTION. If so, the expression cannot have dup nodes or nodes out of sorted order. ********************************************************************************/ bool DataflowAnnotationsComputer::generic_compute(expr* e) { xqtref_t rt = e->get_return_type(); SequenceType::Quantifier quant = rt->get_quantifier(); if (quant == SequenceType::QUANT_ONE || quant == SequenceType::QUANT_QUESTION) { SORTED_NODES(e); DISTINCT_NODES(e); return true; } if (TypeOps::is_subtype(e->get_type_manager(), *rt, *GENV_TYPESYSTEM.ANY_SIMPLE_TYPE, e->get_loc())) { SORTED_NODES(e); DISTINCT_NODES(e); return true; } return false; } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_var_decl_expr(var_decl_expr* e) { generic_compute(e); default_walk(e); var_expr* varExpr = e->get_var_expr(); expr* initExpr = e->get_init_expr(); if (initExpr != NULL && !varExpr->is_mutable()) { PROPOGATE_SORTED_NODES(initExpr, varExpr); PROPOGATE_DISTINCT_NODES(initExpr, varExpr); } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_var_set_expr(var_set_expr* e) { generic_compute(e); default_walk(e); } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_block_expr(block_expr* e) { default_walk(e); if (!generic_compute(e) && e->size() > 0) { PROPOGATE_SORTED_NODES((*e)[e->size()-1], e); PROPOGATE_DISTINCT_NODES((*e)[e->size()-1], e); } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_var_expr(var_expr* e) { if (!generic_compute(e)) { if (e->get_kind() == var_expr::let_var) { PROPOGATE_SORTED_NODES(e->get_forlet_clause()->get_expr(), e); PROPOGATE_DISTINCT_NODES(e->get_forlet_clause()->get_expr(), e); } } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_flwor_expr(flwor_expr* e) { default_walk(e); if (! generic_compute(e)) { flwor_expr::clause_list_t::const_iterator ite = e->clause_begin(); flwor_expr::clause_list_t::const_iterator end = e->clause_end(); const forletwin_clause* fc = NULL; csize numForClauses = 0; for (; ite != end; ++ite) { const flwor_clause* clause = *ite; switch (clause->get_kind()) { case flwor_clause::for_clause: { const forletwin_clause* flc = static_cast<const forletwin_clause*>(clause); expr* domainExpr = flc->get_expr(); xqtref_t domainType = domainExpr->get_return_type(); SequenceType::Quantifier domainQuant = domainType->get_quantifier(); if (domainQuant != SequenceType::QUANT_ONE && domainQuant != SequenceType::QUANT_QUESTION) { fc = flc; ++numForClauses; } break; } case flwor_clause::let_clause: case flwor_clause::where_clause: case flwor_clause::count_clause: case flwor_clause::materialize_clause: { break; } case flwor_clause::window_clause: case flwor_clause::orderby_clause: case flwor_clause::groupby_clause: { return; } default: { ZORBA_ASSERT(false); } } } if (numForClauses == 1) { expr* retExpr = e->get_return_expr(); const var_expr* var = retExpr->get_var(); if (var != NULL && var == fc->get_var()) { PROPOGATE_SORTED_NODES(fc->get_expr(), e); PROPOGATE_DISTINCT_NODES(fc->get_expr(), e); } } else if (numForClauses == 0) { expr* retExpr = e->get_return_expr(); PROPOGATE_SORTED_NODES(retExpr, e); PROPOGATE_DISTINCT_NODES(retExpr, e); } } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_trycatch_expr(trycatch_expr* e) { default_walk(e); generic_compute(e); } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_if_expr(if_expr* e) { default_walk(e); generic_compute(e); } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_fo_expr(fo_expr* e) { default_walk(e); if (!generic_compute(e)) { const function* f = e->get_func(); ulong nArgs = e->num_args(); FunctionConsts::AnnotationValue sorted = f->producesSortedNodes(); if (sorted == FunctionConsts::YES) { SORTED_NODES(e); } else if (sorted == FunctionConsts::NO) { e->setProducesSortedNodes(ANNOTATION_FALSE); } else { BoolAnnotationValue sorted = ANNOTATION_FALSE; for (ulong i = 0; i < nArgs; ++i) { if (f->propagatesSortedNodes(i)) { sorted = e->get_arg(i)->getProducesSortedNodes(); break; } } e->setProducesSortedNodes(sorted); } FunctionConsts::AnnotationValue distinct = f->producesDistinctNodes(); if (distinct == FunctionConsts::YES) { DISTINCT_NODES(e); } else if (distinct == FunctionConsts::NO) { e->setProducesDistinctNodes(ANNOTATION_FALSE); } else { BoolAnnotationValue distinct = ANNOTATION_FALSE; for (ulong i = 0; i < nArgs; ++i) { if (f->propagatesDistinctNodes(i)) { distinct = e->get_arg(i)->getProducesDistinctNodes(); break; } } e->setProducesDistinctNodes(distinct); } } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_validate_expr(validate_expr* e) { default_walk(e); if (!generic_compute(e)) { PROPOGATE_SORTED_NODES(e->get_input(), e); PROPOGATE_DISTINCT_NODES(e->get_input(), e); } } void DataflowAnnotationsComputer::compute_extension_expr(extension_expr* e) { default_walk(e); if (!generic_compute(e)) { PROPOGATE_SORTED_NODES(e->get_input(), e); PROPOGATE_DISTINCT_NODES(e->get_input(), e); } } /******************************************************************************* ********************************************************************************/ void DataflowAnnotationsComputer::compute_relpath_expr(relpath_expr* e) { default_walk(e); if (!generic_compute(e)) { csize num_steps = e->size(); bool only_child_axes = true; ulong num_desc_axes = 0; ulong num_following_axes = 0; bool reverse_axes = false; for (csize i = 1; i < num_steps; ++i) { assert((*e)[i]->get_expr_kind() == axis_step_expr_kind); axis_step_expr* ase = static_cast<axis_step_expr *>((*e)[i]); reverse_axes = reverse_axes || ase->is_reverse_axis(); axis_kind_t axis = ase->getAxis(); if (axis == axis_kind_descendant || axis == axis_kind_descendant_or_self) num_desc_axes++; if (axis == axis_kind_following || axis == axis_kind_following_sibling) num_following_axes++; if (axis != axis_kind_child && axis != axis_kind_attribute && axis != axis_kind_self) { if (only_child_axes && i == num_steps - 1 && num_desc_axes == 1) { // no sort/distinct needed if path expr consists of a number of child // axes and a single descendant axis as the last step in the path. ; } else { only_child_axes = false; } } } if (only_child_axes) { PROPOGATE_SORTED_NODES((*e)[0], e); PROPOGATE_DISTINCT_NODES((*e)[0], e); } else { xqtref_t crt = (*e)[0]->get_return_type(); if (crt->max_card() <= 1) { bool sorted = false; bool distinct = false; if (num_steps == 2) { distinct = true; sorted = true; } else if (only_child_axes) { sorted = true; distinct = true; } else { if (reverse_axes == false && num_desc_axes <= 1 && num_following_axes == 0) { distinct = true; } } e->setProducesSortedNodes((sorted ? ANNOTATION_TRUE : ANNOTATION_FALSE)); e->setProducesDistinctNodes((distinct ? ANNOTATION_TRUE : ANNOTATION_FALSE)); } } } } void DataflowAnnotationsComputer::compute_axis_step_expr(axis_step_expr* e) { return; } void DataflowAnnotationsComputer::compute_match_expr(match_expr* e) { ZORBA_ASSERT(false); } void DataflowAnnotationsComputer::compute_const_expr(const_expr* e) { default_walk(e); generic_compute(e); } void DataflowAnnotationsComputer::compute_order_expr(order_expr* e) { default_walk(e); generic_compute(e); } //////////////////////////////////////////////////////////////////////////////// // // // // // // //////////////////////////////////////////////////////////////////////////////// SourceFinder::~SourceFinder() { UdfSourcesMap::iterator ite1 = theUdfSourcesMap.begin(); UdfSourcesMap::iterator end1 = theUdfSourcesMap.end(); for (; ite1 != end1; ++ite1) { delete ite1->second; } VarSourcesMap::iterator ite2 = theVarSourcesMap.begin(); VarSourcesMap::iterator end2 = theVarSourcesMap.end(); for (; ite2 != end2; ++ite2) { delete ite2->second; } } /******************************************************************************* If the result of the given expr may contain costructed nodes, find the node- constructor exprs where such nodes may come from. If "node" is inside a UDF, "udfCaller" contains the fo expr that invoked that UDF. ********************************************************************************/ void SourceFinder::findNodeSources(expr* node, std::vector<expr*>& sources) { user_function* startingUdf = node->get_udf(); findNodeSourcesRec(node, sources, startingUdf); for (csize i = 0; i < sources.size(); ++i) { expr* source = sources[i]; ZORBA_ASSERT(source->get_expr_kind() == doc_expr_kind || source->get_expr_kind() == elem_expr_kind); user_function* udf = source->get_udf(); if (udf) udf->invalidatePlan(); } } /******************************************************************************* ********************************************************************************/ void SourceFinder::findNodeSourcesRec( expr* node, std::vector<expr*>& sources, user_function* currentUdf) { TypeManager* tm = node->get_type_manager(); RootTypeManager& rtm = GENV_TYPESYSTEM; xqtref_t retType = node->get_return_type(); if (TypeOps::is_subtype(tm, *retType, *rtm.ANY_SIMPLE_TYPE, node->get_loc())) return; switch(node->get_expr_kind()) { case const_expr_kind: { return; } case var_expr_kind: { var_expr* e = static_cast<var_expr*>(node); switch (e->get_kind()) { case var_expr::for_var: case var_expr::let_var: case var_expr::win_var: case var_expr::wincond_out_var: case var_expr::wincond_in_var: case var_expr::groupby_var: case var_expr::non_groupby_var: { VarSourcesMap::iterator ite = theVarSourcesMap.find(e); std::vector<expr*>* varSources; if (ite == theVarSourcesMap.end()) { varSources = new std::vector<expr*>; theVarSourcesMap.insert(VarSourcesPair(e, varSources)); findNodeSourcesRec(e->get_domain_expr(), *varSources, currentUdf); } else { varSources = (*ite).second; } std::vector<expr*>::const_iterator ite2 = (*varSources).begin(); std::vector<expr*>::const_iterator end2 = (*varSources).end(); for (; ite2 != end2; ++ite2) { if (std::find(sources.begin(), sources.end(), *ite2) == sources.end()) sources.push_back(*ite2); } return; } case var_expr::wincond_in_pos_var: case var_expr::wincond_out_pos_var: case var_expr::pos_var: case var_expr::score_var: case var_expr::count_var: { return; } case var_expr::copy_var: { // A copy var holds a standalone copy of the node produced by its domain // expr. Although such a copy is a constructed tree, it was not constructed // by node-constructor exprs, and as a resylt, a copy var is not a source. return; } case var_expr::prolog_var: case var_expr::local_var: { VarSourcesMap::iterator ite = theVarSourcesMap.find(e); std::vector<expr*>* varSources; if (ite == theVarSourcesMap.end()) { varSources = new std::vector<expr*>;; theVarSourcesMap.insert(VarSourcesPair(e, varSources)); var_expr::VarSetExprs::const_iterator ite2 = e->setExprsBegin(); var_expr::VarSetExprs::const_iterator end2 = e->setExprsEnd(); for (; ite2 != end2; ++ite2) { var_set_expr* setExpr = *ite2; if (setExpr->get_udf() != NULL && !setExpr->get_udf()->isOptimized()) continue; findNodeSourcesRec(setExpr->get_expr(), *varSources, currentUdf); } } else { varSources = (*ite).second; } std::vector<expr*>::const_iterator ite2 = (*varSources).begin(); std::vector<expr*>::const_iterator end2 = (*varSources).end(); for (; ite2 != end2; ++ite2) { if (std::find(sources.begin(), sources.end(), *ite2) == sources.end()) sources.push_back(*ite2); } return; } case var_expr::catch_var: { // If in the try clause there is an fn:error that generates nodes, it will // be (conservatively) treated as a "must copy" function, so all of those // nodes will be in standalone trees. return; } case var_expr::arg_var: { theVarSourcesMap.insert(VarSourcesPair(e, nullptr)); return; } case var_expr::eval_var: default: { ZORBA_ASSERT(false); } } break; } case fo_expr_kind: { fo_expr* e = static_cast<fo_expr *>(node); function* f = e->get_func(); if (f->isUdf() && static_cast<user_function*>(f)->getBody() != NULL) { user_function* udf = static_cast<user_function*>(f); bool recursive = (currentUdf ? currentUdf->isMutuallyRecursiveWith(udf) : false); if (recursive) { currentUdf->addRecursiveCall(e); } else { UdfSourcesMap::iterator ite = theUdfSourcesMap.find(udf); std::vector<expr*>* udfSources; if (ite == theUdfSourcesMap.end()) { // must do this before calling findNodeSourcesRec in order to break // recursion cycle udfSources = new std::vector<expr*>; theUdfSourcesMap.insert(UdfSourcesPair(udf, udfSources)); findNodeSourcesRec(udf->getBody(), *udfSources, udf); if (udf->isRecursive()) { std::vector<fo_expr*>::const_iterator ite = udf->getRecursiveCalls().begin(); std::vector<fo_expr*>::const_iterator end = udf->getRecursiveCalls().end(); for (; ite != end; ++ite) { findNodeSourcesRec((*ite), *udfSources, NULL); } } } else { udfSources = (*ite).second; } csize numUdfSources = udfSources->size(); for (csize i = 0; i < numUdfSources; ++i) { expr* source = (*udfSources)[i]; if (std::find(sources.begin(), sources.end(), source) == sources.end()) sources.push_back(source); } // if an arg var of this udf has been marked as a source before, it // means that that var is consumed in some unsafe operation, so we // now have to find the sources of the arg exprs and mark them. csize numArgs = e->num_args(); for (csize i = 0; i < numArgs; ++i) { var_expr* argVar = udf->getArgVar(i); if (theVarSourcesMap.find(argVar) != theVarSourcesMap.end()) { findNodeSourcesRec(e->get_arg(i), sources, currentUdf); } } } // not recursive call } // f->isUdf() else { csize numArgs = e->num_args(); for (csize i = 0; i < numArgs; ++i) { if (f->propagatesInputNodes(e, i)) { findNodeSourcesRec(e->get_arg(i), sources, currentUdf); } } } return; } case doc_expr_kind: case elem_expr_kind: { if (std::find(sources.begin(), sources.end(), node) == sources.end()) { sources.push_back(node); } std::vector<expr*> enclosedExprs; node->get_fo_exprs_of_kind(FunctionConsts::OP_ENCLOSED_1, false, enclosedExprs); std::vector<expr*>::const_iterator ite = enclosedExprs.begin(); std::vector<expr*>::const_iterator end = enclosedExprs.end(); for (; ite != end; ++ite) { fo_expr* fo = static_cast<fo_expr*>(*ite); assert(fo->get_func()->getKind() == FunctionConsts::OP_ENCLOSED_1); findNodeSourcesRec(fo, sources, currentUdf); } return; } case attr_expr_kind: case namespace_expr_kind: case text_expr_kind: case pi_expr_kind: { return; } case json_direct_object_expr_kind: case json_object_expr_kind: case json_array_expr_kind: { // TODO? We need to drill inside a json pair or array constructor only // if we are coming from an unbox or flatten call ???? break; } case relpath_expr_kind: { relpath_expr* e = static_cast<relpath_expr *>(node); findNodeSourcesRec((*e)[0], sources, currentUdf); return; } case flwor_expr_kind: { flwor_expr* e = static_cast<flwor_expr *>(node); // We don't need to drill down to the domain exprs of variables that // are not referenced in the return clause. findNodeSourcesRec(e->get_return_expr(), sources, currentUdf); return; } case if_expr_kind: { if_expr* e = static_cast<if_expr *>(node); findNodeSourcesRec(e->get_then_expr(), sources, currentUdf); findNodeSourcesRec(e->get_else_expr(), sources, currentUdf); return; } case trycatch_expr_kind: { break; } case promote_expr_kind: case treat_expr_kind: case order_expr_kind: case wrapper_expr_kind: case function_trace_expr_kind: case extension_expr_kind: case validate_expr_kind: { break; } case transform_expr_kind: { transform_expr* e = static_cast<transform_expr*>(node); findNodeSourcesRec(e->getReturnExpr(), sources, currentUdf); return; } case block_expr_kind: { block_expr* e = static_cast<block_expr*>(node); findNodeSourcesRec((*e)[e->size()-1], sources, currentUdf); return; } case var_decl_expr_kind: case var_set_expr_kind: { return; } case apply_expr_kind: { break; } case exit_catcher_expr_kind: { exit_catcher_expr* e = static_cast<exit_catcher_expr*>(node); std::vector<expr*>::const_iterator ite = e->exitExprsBegin(); std::vector<expr*>::const_iterator end = e->exitExprsEnd(); for (; ite != end; ++ite) { exit_expr* ex = static_cast<exit_expr*>(*ite); findNodeSourcesRec(ex->get_expr(), sources, currentUdf); } break; } case eval_expr_kind: { eval_expr* e = static_cast<eval_expr*>(node); // Make sure that the eval iterator will produce standalone trees. e->setNodeCopy(true); return; } case debugger_expr_kind: { break; } case dynamic_function_invocation_expr_kind: { // Conservatively assume that the function item that is going to be executed // is going to propagate its inputs, so find the sources in the arguments. // TODO: look for function_item_expr in the subtree to check if this assumption // is really true. break; } case argument_placeholder_expr_kind: { return; } case function_item_expr_kind: { //function_item_expr* e = static_cast<function_item_expr*>(node); // TODO return; } case castable_expr_kind: case cast_expr_kind: case instanceof_expr_kind: case name_cast_expr_kind: case axis_step_expr_kind: case match_expr_kind: case delete_expr_kind: case insert_expr_kind: case rename_expr_kind: case replace_expr_kind: case while_expr_kind: case exit_expr_kind: case flowctl_expr_kind: #ifndef ZORBA_NO_FULL_TEXT case ft_expr_kind: #endif default: ZORBA_ASSERT(false); } ExprIterator iter(node); while(!iter.done()) { expr* child = (**iter); if (child != NULL) { findNodeSourcesRec(child, sources, currentUdf); } iter.next(); } } /******************************************************************************* This method is called when we serialize a udf, if the query has an eval expr. ********************************************************************************/ void SourceFinder::findLocalNodeSources( expr* node, std::vector<expr*>& sources) { TypeManager* tm = node->get_type_manager(); RootTypeManager& rtm = GENV_TYPESYSTEM; xqtref_t retType = node->get_return_type(); if (TypeOps::is_subtype(tm, *retType, *rtm.ANY_SIMPLE_TYPE, node->get_loc())) return; switch(node->get_expr_kind()) { case const_expr_kind: { return; } case var_expr_kind: { var_expr* e = static_cast<var_expr*>(node); switch (e->get_kind()) { case var_expr::for_var: case var_expr::let_var: case var_expr::win_var: case var_expr::wincond_out_var: case var_expr::wincond_in_var: case var_expr::groupby_var: case var_expr::non_groupby_var: { VarSourcesMap::iterator ite = theVarSourcesMap.find(e); std::vector<expr*>* varSources; if (ite == theVarSourcesMap.end()) { varSources = new std::vector<expr*>; theVarSourcesMap.insert(VarSourcesPair(e, varSources)); findLocalNodeSources(e->get_domain_expr(), *varSources); } else { varSources = (*ite).second; } std::vector<expr*>::const_iterator ite2 = (*varSources).begin(); std::vector<expr*>::const_iterator end2 = (*varSources).end(); for (; ite2 != end2; ++ite2) { if (std::find(sources.begin(), sources.end(), *ite2) == sources.end()) sources.push_back(*ite2); } return; } case var_expr::wincond_in_pos_var: case var_expr::wincond_out_pos_var: case var_expr::pos_var: case var_expr::score_var: case var_expr::count_var: { return; } case var_expr::copy_var: { // A copy var holds a standalone copy of the node produced by its domain // expr. Although such a copy is a constructed tree, it was not constructed // by node-constructor exprs, and as a result, a copy var is not a source. return; } case var_expr::arg_var: { return; } case var_expr::prolog_var: case var_expr::local_var: { VarSourcesMap::iterator ite = theVarSourcesMap.find(e); std::vector<expr*>* varSources; if (ite == theVarSourcesMap.end()) { varSources = new std::vector<expr*>;; theVarSourcesMap.insert(VarSourcesPair(e, varSources)); var_expr::VarSetExprs::const_iterator ite2 = e->setExprsBegin(); var_expr::VarSetExprs::const_iterator end2 = e->setExprsEnd(); for (; ite2 != end2; ++ite2) { var_set_expr* setExpr = *ite2; findLocalNodeSources(setExpr->get_expr(), *varSources); } } else { varSources = (*ite).second; } std::vector<expr*>::const_iterator ite2 = (*varSources).begin(); std::vector<expr*>::const_iterator end2 = (*varSources).end(); for (; ite2 != end2; ++ite2) { if (std::find(sources.begin(), sources.end(), *ite2) == sources.end()) sources.push_back(*ite2); } return; } case var_expr::catch_var: { // If in the try clause there is an fn:error that generates nodes, it will // be (conservatively) treated as a "must copy" function, so all of those // nodes will be in standalone trees. return; } case var_expr::eval_var: default: { ZORBA_ASSERT(false); } } break; } case doc_expr_kind: case elem_expr_kind: { if (std::find(sources.begin(), sources.end(), node) == sources.end()) { sources.push_back(node); } std::vector<expr*> enclosedExprs; node->get_fo_exprs_of_kind(FunctionConsts::OP_ENCLOSED_1, false, enclosedExprs); std::vector<expr*>::const_iterator ite = enclosedExprs.begin(); std::vector<expr*>::const_iterator end = enclosedExprs.end(); for (; ite != end; ++ite) { fo_expr* fo = static_cast<fo_expr*>(*ite); assert(fo->get_func()->getKind() == FunctionConsts::OP_ENCLOSED_1); findLocalNodeSources(fo, sources); } return; } case attr_expr_kind: case namespace_expr_kind: case text_expr_kind: case pi_expr_kind: { return; } case json_direct_object_expr_kind: case json_object_expr_kind: case json_array_expr_kind: { // TODO? We need to drill inside a json pair or array constructor only // if we are coming from an unbox or flatten call ???? break; } case relpath_expr_kind: { relpath_expr* e = static_cast<relpath_expr *>(node); findLocalNodeSources((*e)[0], sources); return; } case flwor_expr_kind: { flwor_expr* e = static_cast<flwor_expr *>(node); // We don't need to drill down to the domain exprs of variables that // are not referenced in the return clause. findLocalNodeSources(e->get_return_expr(), sources); return; } case if_expr_kind: { if_expr* e = static_cast<if_expr *>(node); findLocalNodeSources(e->get_then_expr(), sources); findLocalNodeSources(e->get_else_expr(), sources); return; } case trycatch_expr_kind: { break; } case fo_expr_kind: { fo_expr* e = static_cast<fo_expr *>(node); function* f = e->get_func(); if (f->isUdf() && static_cast<user_function*>(f)->getBody() != NULL) { csize numArgs = e->num_args(); for (csize i = 0; i < numArgs; ++i) { findLocalNodeSources(e->get_arg(i), sources); } } else { csize numArgs = e->num_args(); for (csize i = 0; i < numArgs; ++i) { if (f->propagatesInputNodes(e, i)) { findLocalNodeSources(e->get_arg(i), sources); } } } return; } case promote_expr_kind: case treat_expr_kind: case order_expr_kind: case wrapper_expr_kind: case function_trace_expr_kind: case extension_expr_kind: case validate_expr_kind: { break; } case transform_expr_kind: { transform_expr* e = static_cast<transform_expr*>(node); findLocalNodeSources(e->getReturnExpr(), sources); return; } case block_expr_kind: { block_expr* e = static_cast<block_expr*>(node); findLocalNodeSources((*e)[e->size()-1], sources); return; } case var_decl_expr_kind: case var_set_expr_kind: { return; } case apply_expr_kind: { break; } case exit_catcher_expr_kind: { exit_catcher_expr* e = static_cast<exit_catcher_expr*>(node); std::vector<expr*>::const_iterator ite = e->exitExprsBegin(); std::vector<expr*>::const_iterator end = e->exitExprsEnd(); for (; ite != end; ++ite) { exit_expr* ex = static_cast<exit_expr*>(*ite); findLocalNodeSources(ex->get_expr(), sources); } break; } case eval_expr_kind: { eval_expr* e = static_cast<eval_expr*>(node); // Make sure that the eval iterator will produce standalone trees. e->setNodeCopy(true); return; } case debugger_expr_kind: { break; } case dynamic_function_invocation_expr_kind: { // Conservatively assume that the function item that is going to be executed // is going to propagate its inputs, so find the sources in the arguments. // TODO: look for function_item_expr in the subtree to check if this assumption // is really true. break; } case function_item_expr_kind: { //function_item_expr* e = static_cast<function_item_expr*>(node); // TODO return; } case castable_expr_kind: case cast_expr_kind: case instanceof_expr_kind: case name_cast_expr_kind: case axis_step_expr_kind: case match_expr_kind: case delete_expr_kind: case insert_expr_kind: case rename_expr_kind: case replace_expr_kind: case while_expr_kind: case exit_expr_kind: case flowctl_expr_kind: #ifndef ZORBA_NO_FULL_TEXT case ft_expr_kind: #endif default: ZORBA_ASSERT(false); } ExprIterator iter(node); while(!iter.done()) { expr* child = (**iter); if (child != NULL) { findLocalNodeSources(child, sources); } iter.next(); } } } /* vim:set et sw=2 ts=2: */
{ "language": "C++" }
#ifndef BOOST_MPL_PROTECT_HPP_INCLUDED #define BOOST_MPL_PROTECT_HPP_INCLUDED // Copyright Peter Dimov 2001 // Copyright Aleksey Gurtovoy 2002-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/mpl for documentation. // $Id$ // $Date$ // $Revision$ #include <boost/mpl/aux_/arity.hpp> #include <boost/mpl/aux_/config/dtp.hpp> #include <boost/mpl/aux_/nttp_decl.hpp> #include <boost/mpl/aux_/na_spec.hpp> namespace boost { namespace mpl { template< typename BOOST_MPL_AUX_NA_PARAM(T) , int not_le_ = 0 > struct protect : T { #if BOOST_WORKAROUND(__EDG_VERSION__, == 238) typedef mpl::protect type; #else typedef protect type; #endif }; #if defined(BOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES) namespace aux { template< BOOST_MPL_AUX_NTTP_DECL(int, N), typename T > struct arity< protect<T>, N > : arity<T,N> { }; } // namespace aux #endif BOOST_MPL_AUX_NA_SPEC_MAIN(1, protect) #if !defined(BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT) BOOST_MPL_AUX_NA_SPEC_TEMPLATE_ARITY(1, 1, protect) #endif }} #endif // BOOST_MPL_PROTECT_HPP_INCLUDED
{ "language": "C++" }
include "fzn_table_bool.mzn"; include "fzn_table_bool_reif.mzn"; %-----------------------------------------------------------------------------% % A table constraint: table(x, t) represents the constraint x in t where we % consider each row in t to be a tuple and t as a set of tuples. %-----------------------------------------------------------------------------% predicate table_bool(array[int] of var bool: x, array[int, int] of bool: t) = fzn_table_bool(x, t); predicate table_bool_reif(array[int] of var bool: x, array[int, int] of bool: t, var bool: b) = fzn_table_bool_reif(x, t, b); %-----------------------------------------------------------------------------%
{ "language": "C++" }
// Copyright 2015 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. #ifndef CONTENT_PUBLIC_CHILD_CHILD_THREAD_H_ #define CONTENT_PUBLIC_CHILD_CHILD_THREAD_H_ #include <string> #include "base/logging.h" #include "build/build_config.h" #include "content/common/content_export.h" #include "ipc/ipc_sender.h" #if defined(OS_WIN) #include <windows.h> #endif namespace base { struct UserMetricsAction; } namespace service_manager { class InterfaceProvider; class InterfaceRegistry; } namespace content { class ServiceManagerConnection; // An abstract base class that contains logic shared between most child // processes of the embedder. class CONTENT_EXPORT ChildThread : public IPC::Sender { public: // Returns the one child thread for this process. Note that this can only be // accessed when running on the child thread itself. static ChildThread* Get(); ~ChildThread() override {} #if defined(OS_WIN) // Request that the given font be loaded by the browser so it's cached by the // OS. Please see ChildProcessHost::PreCacheFont for details. virtual void PreCacheFont(const LOGFONT& log_font) = 0; // Release cached font. virtual void ReleaseCachedFonts() = 0; #endif // Sends over a base::UserMetricsAction to be recorded by user metrics as // an action. Once a new user metric is added, run // tools/metrics/actions/extract_actions.py // to add the metric to actions.xml, then update the <owner>s and // <description> sections. Make sure to include the actions.xml file when you // upload your code for review! // // WARNING: When using base::UserMetricsAction, base::UserMetricsAction // and a string literal parameter must be on the same line, e.g. // RenderThread::Get()->RecordAction( // base::UserMetricsAction("my extremely long action name")); // because otherwise our processing scripts won't pick up on new actions. virtual void RecordAction(const base::UserMetricsAction& action) = 0; // Sends over a string to be recorded by user metrics as a computed action. // When you use this you need to also update the rules for extracting known // actions in chrome/tools/extract_actions.py. virtual void RecordComputedAction(const std::string& action) = 0; // Returns the ServiceManagerConnection for the thread (from which a // service_manager::Connector can be obtained). virtual ServiceManagerConnection* GetServiceManagerConnection() = 0; // Returns the InterfaceRegistry that this process uses to expose interfaces // to the browser. virtual service_manager::InterfaceRegistry* GetInterfaceRegistry() = 0; // Returns the InterfaceProvider that this process can use to bind // interfaces exposed to it by the browser. virtual service_manager::InterfaceProvider* GetRemoteInterfaces() = 0; }; } // namespace content #endif // CONTENT_PUBLIC_CHILD_CHILD_THREAD_H_
{ "language": "C++" }
/* Copyright (c) 2018 Anakin Authors All Rights Reserve. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef ANAKIN_SABER_FUNCS_IMPL_CUDA_SABER_SEQUENCE_POOL_H #define ANAKIN_SABER_FUNCS_IMPL_CUDA_SABER_SEQUENCE_POOL_H #include "saber/funcs/impl/impl_sequence_pool.h" #include "saber/saber_funcs_param.h" #include <functional> #include <map> namespace anakin { namespace saber { template <DataType OpDtype> class SaberSequencePool<NV, OpDtype> : public ImplBase < NV, OpDtype, SequencePoolParam<NV> > { public: typedef Tensor<NV> DataTensor_in; typedef Tensor<NV> DataTensor_out; typedef Tensor<NV> OpTensor; typedef typename DataTrait<NV, OpDtype>::Dtype DataType_in; typedef typename DataTrait<NV, OpDtype>::Dtype DataType_out; typedef typename DataTrait<NV, OpDtype>::Dtype DataType_op; SaberSequencePool() = default; ~SaberSequencePool() {} virtual SaberStatus init(const std::vector<DataTensor_in*>& inputs, std::vector<DataTensor_out*>& outputs, SequencePoolParam<NV>& param, Context<NV>& ctx) override; virtual SaberStatus create(const std::vector<DataTensor_in*>& inputs, std::vector<DataTensor_out*>& outputs, SequencePoolParam<NV>& param, Context<NV>& ctx) { return SaberSuccess; } virtual SaberStatus dispatch(const std::vector<DataTensor_in*>& inputs, std::vector<DataTensor_out*>& outputs, SequencePoolParam<NV>& param) override; private: typedef std::function<void(DataType_out*, const DataType_in*, const int, \ const int*, const int, Context<NV>* ctx)> seq_pool_direct_kernel; std::map<SequencePoolType, seq_pool_direct_kernel> kernel_direct_map; }; } } #endif
{ "language": "C++" }
/****************************************************************************** * $Id: ogr_xplane_nav_reader.cpp * * Project: X-Plane nav.dat file reader header * Purpose: Definition of classes for X-Plane nav.dat file reader * Author: Even Rouault, even dot rouault at mines dash paris dot org * ****************************************************************************** * Copyright (c) 2008, Even Rouault * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included * in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef _OGR_XPLANE_NAV_READER_H_INCLUDED #define _OGR_XPLANE_NAV_READER_H_INCLUDED #include "ogr_xplane.h" #include "ogr_xplane_reader.h" /************************************************************************/ /* OGRXPlaneILSLayer */ /************************************************************************/ class OGRXPlaneILSLayer : public OGRXPlaneLayer { public: OGRXPlaneILSLayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszAptICAO, const char* pszRwyNum, const char* pszSubType, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange, double dfTrueHeading); }; /************************************************************************/ /* OGRXPlaneVORLayer */ /************************************************************************/ class OGRXPlaneVORLayer : public OGRXPlaneLayer { public: OGRXPlaneVORLayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszNavaidName, const char* pszSubType, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange, double dfSlavedVariation); }; /************************************************************************/ /* OGRXPlaneNDBLayer */ /************************************************************************/ class OGRXPlaneNDBLayer : public OGRXPlaneLayer { public: OGRXPlaneNDBLayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszNavaidName, const char* pszSubType, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange); }; /************************************************************************/ /* OGRXPlaneGSLayer */ /************************************************************************/ class OGRXPlaneGSLayer : public OGRXPlaneLayer { public: OGRXPlaneGSLayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszAptICAO, const char* pszRwyNum, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange, double dfTrueHeading, double dfSlope); }; /************************************************************************/ /* OGRXPlaneMarkerLayer */ /************************************************************************/ class OGRXPlaneMarkerLayer : public OGRXPlaneLayer { public: OGRXPlaneMarkerLayer(); OGRFeature* AddFeature(const char* pszAptICAO, const char* pszRwyNum, const char* pszSubType, double dfLat, double dfLon, double dfEle, double dfTrueHeading); }; /************************************************************************/ /* OGRXPlaneDMEILSLayer */ /************************************************************************/ class OGRXPlaneDMEILSLayer : public OGRXPlaneLayer { public: OGRXPlaneDMEILSLayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszAptICAO, const char* pszRwyNum, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange, double dfDMEBias); }; /************************************************************************/ /* OGRXPlaneDMELayer */ /************************************************************************/ class OGRXPlaneDMELayer : public OGRXPlaneLayer { public: OGRXPlaneDMELayer(); OGRFeature* AddFeature(const char* pszNavaidID, const char* pszNavaidName, const char* pszSubType, double dfLat, double dfLon, double dfEle, double dfFreq, double dfRange, double dfDMEBias); }; enum { NAVAID_NDB = 2, NAVAID_VOR = 3, /* VOR, VORTAC or VOR-DME.*/ NAVAID_LOC_ILS = 4, /* Localiser that is part of a full ILS */ NAVAID_LOC_STANDALONE = 5, /* Stand-alone localiser (LOC), also including a LDA (Landing Directional Aid) or SDF (Simplified Directional Facility) */ NAVAID_GS = 6, /* Glideslope */ NAVAID_OM = 7, /* Outer marker */ NAVAID_MM = 8, /* Middle marker */ NAVAID_IM = 9, /* Inner marker */ NAVAID_DME_COLOC = 12, /* DME (including the DME element of an ILS, VORTAC or VOR-DME) */ NAVAID_DME_STANDALONE = 13, /* DME (including the DME element of an NDB-DME) */ }; /************************************************************************/ /* OGRXPlaneNavReader */ /************************************************************************/ class OGRXPlaneNavReader : public OGRXPlaneReader { private: OGRXPlaneILSLayer* poILSLayer; OGRXPlaneVORLayer* poVORLayer; OGRXPlaneNDBLayer* poNDBLayer; OGRXPlaneGSLayer* poGSLayer ; OGRXPlaneMarkerLayer* poMarkerLayer; OGRXPlaneDMELayer* poDMELayer; OGRXPlaneDMEILSLayer* poDMEILSLayer; private: OGRXPlaneNavReader(); void ParseRecord(int nType); protected: virtual void Read(); public: OGRXPlaneNavReader( OGRXPlaneDataSource* poDataSource ); virtual OGRXPlaneReader* CloneForLayer(OGRXPlaneLayer* poLayer); virtual int IsRecognizedVersion( const char* pszVersionString); }; #endif
{ "language": "C++" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/greengrass/Greengrass_EXPORTS.h> #include <aws/greengrass/GreengrassRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/greengrass/model/SoftwareToUpdate.h> #include <aws/greengrass/model/UpdateAgentLogLevel.h> #include <aws/core/utils/memory/stl/AWSVector.h> #include <aws/greengrass/model/UpdateTargetsArchitecture.h> #include <aws/greengrass/model/UpdateTargetsOperatingSystem.h> #include <utility> namespace Aws { namespace Greengrass { namespace Model { /** */ class AWS_GREENGRASS_API CreateSoftwareUpdateJobRequest : public GreengrassRequest { public: CreateSoftwareUpdateJobRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "CreateSoftwareUpdateJob"; } Aws::String SerializePayload() const override; Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override; /** * A client token used to correlate requests and responses. */ inline const Aws::String& GetAmznClientToken() const{ return m_amznClientToken; } /** * A client token used to correlate requests and responses. */ inline bool AmznClientTokenHasBeenSet() const { return m_amznClientTokenHasBeenSet; } /** * A client token used to correlate requests and responses. */ inline void SetAmznClientToken(const Aws::String& value) { m_amznClientTokenHasBeenSet = true; m_amznClientToken = value; } /** * A client token used to correlate requests and responses. */ inline void SetAmznClientToken(Aws::String&& value) { m_amznClientTokenHasBeenSet = true; m_amznClientToken = std::move(value); } /** * A client token used to correlate requests and responses. */ inline void SetAmznClientToken(const char* value) { m_amznClientTokenHasBeenSet = true; m_amznClientToken.assign(value); } /** * A client token used to correlate requests and responses. */ inline CreateSoftwareUpdateJobRequest& WithAmznClientToken(const Aws::String& value) { SetAmznClientToken(value); return *this;} /** * A client token used to correlate requests and responses. */ inline CreateSoftwareUpdateJobRequest& WithAmznClientToken(Aws::String&& value) { SetAmznClientToken(std::move(value)); return *this;} /** * A client token used to correlate requests and responses. */ inline CreateSoftwareUpdateJobRequest& WithAmznClientToken(const char* value) { SetAmznClientToken(value); return *this;} inline const Aws::String& GetS3UrlSignerRole() const{ return m_s3UrlSignerRole; } inline bool S3UrlSignerRoleHasBeenSet() const { return m_s3UrlSignerRoleHasBeenSet; } inline void SetS3UrlSignerRole(const Aws::String& value) { m_s3UrlSignerRoleHasBeenSet = true; m_s3UrlSignerRole = value; } inline void SetS3UrlSignerRole(Aws::String&& value) { m_s3UrlSignerRoleHasBeenSet = true; m_s3UrlSignerRole = std::move(value); } inline void SetS3UrlSignerRole(const char* value) { m_s3UrlSignerRoleHasBeenSet = true; m_s3UrlSignerRole.assign(value); } inline CreateSoftwareUpdateJobRequest& WithS3UrlSignerRole(const Aws::String& value) { SetS3UrlSignerRole(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithS3UrlSignerRole(Aws::String&& value) { SetS3UrlSignerRole(std::move(value)); return *this;} inline CreateSoftwareUpdateJobRequest& WithS3UrlSignerRole(const char* value) { SetS3UrlSignerRole(value); return *this;} inline const SoftwareToUpdate& GetSoftwareToUpdate() const{ return m_softwareToUpdate; } inline bool SoftwareToUpdateHasBeenSet() const { return m_softwareToUpdateHasBeenSet; } inline void SetSoftwareToUpdate(const SoftwareToUpdate& value) { m_softwareToUpdateHasBeenSet = true; m_softwareToUpdate = value; } inline void SetSoftwareToUpdate(SoftwareToUpdate&& value) { m_softwareToUpdateHasBeenSet = true; m_softwareToUpdate = std::move(value); } inline CreateSoftwareUpdateJobRequest& WithSoftwareToUpdate(const SoftwareToUpdate& value) { SetSoftwareToUpdate(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithSoftwareToUpdate(SoftwareToUpdate&& value) { SetSoftwareToUpdate(std::move(value)); return *this;} inline const UpdateAgentLogLevel& GetUpdateAgentLogLevel() const{ return m_updateAgentLogLevel; } inline bool UpdateAgentLogLevelHasBeenSet() const { return m_updateAgentLogLevelHasBeenSet; } inline void SetUpdateAgentLogLevel(const UpdateAgentLogLevel& value) { m_updateAgentLogLevelHasBeenSet = true; m_updateAgentLogLevel = value; } inline void SetUpdateAgentLogLevel(UpdateAgentLogLevel&& value) { m_updateAgentLogLevelHasBeenSet = true; m_updateAgentLogLevel = std::move(value); } inline CreateSoftwareUpdateJobRequest& WithUpdateAgentLogLevel(const UpdateAgentLogLevel& value) { SetUpdateAgentLogLevel(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithUpdateAgentLogLevel(UpdateAgentLogLevel&& value) { SetUpdateAgentLogLevel(std::move(value)); return *this;} inline const Aws::Vector<Aws::String>& GetUpdateTargets() const{ return m_updateTargets; } inline bool UpdateTargetsHasBeenSet() const { return m_updateTargetsHasBeenSet; } inline void SetUpdateTargets(const Aws::Vector<Aws::String>& value) { m_updateTargetsHasBeenSet = true; m_updateTargets = value; } inline void SetUpdateTargets(Aws::Vector<Aws::String>&& value) { m_updateTargetsHasBeenSet = true; m_updateTargets = std::move(value); } inline CreateSoftwareUpdateJobRequest& WithUpdateTargets(const Aws::Vector<Aws::String>& value) { SetUpdateTargets(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithUpdateTargets(Aws::Vector<Aws::String>&& value) { SetUpdateTargets(std::move(value)); return *this;} inline CreateSoftwareUpdateJobRequest& AddUpdateTargets(const Aws::String& value) { m_updateTargetsHasBeenSet = true; m_updateTargets.push_back(value); return *this; } inline CreateSoftwareUpdateJobRequest& AddUpdateTargets(Aws::String&& value) { m_updateTargetsHasBeenSet = true; m_updateTargets.push_back(std::move(value)); return *this; } inline CreateSoftwareUpdateJobRequest& AddUpdateTargets(const char* value) { m_updateTargetsHasBeenSet = true; m_updateTargets.push_back(value); return *this; } inline const UpdateTargetsArchitecture& GetUpdateTargetsArchitecture() const{ return m_updateTargetsArchitecture; } inline bool UpdateTargetsArchitectureHasBeenSet() const { return m_updateTargetsArchitectureHasBeenSet; } inline void SetUpdateTargetsArchitecture(const UpdateTargetsArchitecture& value) { m_updateTargetsArchitectureHasBeenSet = true; m_updateTargetsArchitecture = value; } inline void SetUpdateTargetsArchitecture(UpdateTargetsArchitecture&& value) { m_updateTargetsArchitectureHasBeenSet = true; m_updateTargetsArchitecture = std::move(value); } inline CreateSoftwareUpdateJobRequest& WithUpdateTargetsArchitecture(const UpdateTargetsArchitecture& value) { SetUpdateTargetsArchitecture(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithUpdateTargetsArchitecture(UpdateTargetsArchitecture&& value) { SetUpdateTargetsArchitecture(std::move(value)); return *this;} inline const UpdateTargetsOperatingSystem& GetUpdateTargetsOperatingSystem() const{ return m_updateTargetsOperatingSystem; } inline bool UpdateTargetsOperatingSystemHasBeenSet() const { return m_updateTargetsOperatingSystemHasBeenSet; } inline void SetUpdateTargetsOperatingSystem(const UpdateTargetsOperatingSystem& value) { m_updateTargetsOperatingSystemHasBeenSet = true; m_updateTargetsOperatingSystem = value; } inline void SetUpdateTargetsOperatingSystem(UpdateTargetsOperatingSystem&& value) { m_updateTargetsOperatingSystemHasBeenSet = true; m_updateTargetsOperatingSystem = std::move(value); } inline CreateSoftwareUpdateJobRequest& WithUpdateTargetsOperatingSystem(const UpdateTargetsOperatingSystem& value) { SetUpdateTargetsOperatingSystem(value); return *this;} inline CreateSoftwareUpdateJobRequest& WithUpdateTargetsOperatingSystem(UpdateTargetsOperatingSystem&& value) { SetUpdateTargetsOperatingSystem(std::move(value)); return *this;} private: Aws::String m_amznClientToken; bool m_amznClientTokenHasBeenSet; Aws::String m_s3UrlSignerRole; bool m_s3UrlSignerRoleHasBeenSet; SoftwareToUpdate m_softwareToUpdate; bool m_softwareToUpdateHasBeenSet; UpdateAgentLogLevel m_updateAgentLogLevel; bool m_updateAgentLogLevelHasBeenSet; Aws::Vector<Aws::String> m_updateTargets; bool m_updateTargetsHasBeenSet; UpdateTargetsArchitecture m_updateTargetsArchitecture; bool m_updateTargetsArchitectureHasBeenSet; UpdateTargetsOperatingSystem m_updateTargetsOperatingSystem; bool m_updateTargetsOperatingSystemHasBeenSet; }; } // namespace Model } // namespace Greengrass } // namespace Aws
{ "language": "C++" }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // 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. // Author: kenton@google.com (Kenton Varda) // Based on original Protocol Buffers design by // Sanjay Ghemawat, Jeff Dean, and others. // // This file makes extensive use of RFC 3092. :) #include <algorithm> #include <google/protobuf/descriptor_database.h> #include <google/protobuf/descriptor.h> #include <google/protobuf/descriptor.pb.h> #include <google/protobuf/text_format.h> #include <google/protobuf/stubs/strutil.h> #include <google/protobuf/stubs/common.h> #include <google/protobuf/testing/googletest.h> #include <gtest/gtest.h> namespace google { namespace protobuf { namespace { static void AddToDatabase(SimpleDescriptorDatabase* database, const char* file_text) { FileDescriptorProto file_proto; EXPECT_TRUE(TextFormat::ParseFromString(file_text, &file_proto)); database->Add(file_proto); } static void ExpectContainsType(const FileDescriptorProto& proto, const string& type_name) { for (int i = 0; i < proto.message_type_size(); i++) { if (proto.message_type(i).name() == type_name) return; } ADD_FAILURE() << "\"" << proto.name() << "\" did not contain expected type \"" << type_name << "\"."; } // =================================================================== #if GTEST_HAS_PARAM_TEST // SimpleDescriptorDatabase, EncodedDescriptorDatabase, and // DescriptorPoolDatabase call for very similar tests. Instead of writing // three nearly-identical sets of tests, we use parameterized tests to apply // the same code to all three. // The parameterized test runs against a DescriptarDatabaseTestCase. We have // implementations for each of the three classes we want to test. class DescriptorDatabaseTestCase { public: virtual ~DescriptorDatabaseTestCase() {} virtual DescriptorDatabase* GetDatabase() = 0; virtual bool AddToDatabase(const FileDescriptorProto& file) = 0; }; // Factory function type. typedef DescriptorDatabaseTestCase* DescriptorDatabaseTestCaseFactory(); // Specialization for SimpleDescriptorDatabase. class SimpleDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { public: static DescriptorDatabaseTestCase* New() { return new SimpleDescriptorDatabaseTestCase; } virtual ~SimpleDescriptorDatabaseTestCase() {} virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { return database_.Add(file); } private: SimpleDescriptorDatabase database_; }; // Specialization for EncodedDescriptorDatabase. class EncodedDescriptorDatabaseTestCase : public DescriptorDatabaseTestCase { public: static DescriptorDatabaseTestCase* New() { return new EncodedDescriptorDatabaseTestCase; } virtual ~EncodedDescriptorDatabaseTestCase() {} virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { string data; file.SerializeToString(&data); return database_.AddCopy(data.data(), data.size()); } private: EncodedDescriptorDatabase database_; }; // Specialization for DescriptorPoolDatabase. class DescriptorPoolDatabaseTestCase : public DescriptorDatabaseTestCase { public: static DescriptorDatabaseTestCase* New() { return new EncodedDescriptorDatabaseTestCase; } DescriptorPoolDatabaseTestCase() : database_(pool_) {} virtual ~DescriptorPoolDatabaseTestCase() {} virtual DescriptorDatabase* GetDatabase() { return &database_; } virtual bool AddToDatabase(const FileDescriptorProto& file) { return pool_.BuildFile(file); } private: DescriptorPool pool_; DescriptorPoolDatabase database_; }; // ------------------------------------------------------------------- class DescriptorDatabaseTest : public testing::TestWithParam<DescriptorDatabaseTestCaseFactory*> { protected: virtual void SetUp() { test_case_.reset(GetParam()()); database_ = test_case_->GetDatabase(); } void AddToDatabase(const char* file_descriptor_text) { FileDescriptorProto file_proto; EXPECT_TRUE(TextFormat::ParseFromString(file_descriptor_text, &file_proto)); EXPECT_TRUE(test_case_->AddToDatabase(file_proto)); } void AddToDatabaseWithError(const char* file_descriptor_text) { FileDescriptorProto file_proto; EXPECT_TRUE(TextFormat::ParseFromString(file_descriptor_text, &file_proto)); EXPECT_FALSE(test_case_->AddToDatabase(file_proto)); } scoped_ptr<DescriptorDatabaseTestCase> test_case_; DescriptorDatabase* database_; }; TEST_P(DescriptorDatabaseTest, FindFileByName) { AddToDatabase( "name: \"foo.proto\" " "message_type { name:\"Foo\" }"); AddToDatabase( "name: \"bar.proto\" " "message_type { name:\"Bar\" }"); { FileDescriptorProto file; EXPECT_TRUE(database_->FindFileByName("foo.proto", &file)); EXPECT_EQ("foo.proto", file.name()); ExpectContainsType(file, "Foo"); } { FileDescriptorProto file; EXPECT_TRUE(database_->FindFileByName("bar.proto", &file)); EXPECT_EQ("bar.proto", file.name()); ExpectContainsType(file, "Bar"); } { // Fails to find undefined files. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileByName("baz.proto", &file)); } } TEST_P(DescriptorDatabaseTest, FindFileContainingSymbol) { AddToDatabase( "name: \"foo.proto\" " "message_type { " " name: \"Foo\" " " field { name:\"qux\" }" " nested_type { name: \"Grault\" } " " enum_type { name: \"Garply\" } " "} " "enum_type { " " name: \"Waldo\" " " value { name:\"FRED\" } " "} " "extension { name: \"plugh\" } " "service { " " name: \"Xyzzy\" " " method { name: \"Thud\" } " "}" ); AddToDatabase( "name: \"bar.proto\" " "package: \"corge\" " "message_type { name: \"Bar\" }"); { FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Foo", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find fields. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.qux", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find nested types. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.Grault", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find nested enums. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Foo.Garply", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find enum types. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Waldo", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find enum values. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Waldo.FRED", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find extensions. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("plugh", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find services. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Xyzzy", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find methods. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("Xyzzy.Thud", &file)); EXPECT_EQ("foo.proto", file.name()); } { // Can find things in packages. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingSymbol("corge.Bar", &file)); EXPECT_EQ("bar.proto", file.name()); } { // Fails to find undefined symbols. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileContainingSymbol("Baz", &file)); } { // Names must be fully-qualified. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileContainingSymbol("Bar", &file)); } } TEST_P(DescriptorDatabaseTest, FindFileContainingExtension) { AddToDatabase( "name: \"foo.proto\" " "message_type { " " name: \"Foo\" " " extension_range { start: 1 end: 1000 } " " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " " extendee: \".Foo\" }" "}"); AddToDatabase( "name: \"bar.proto\" " "package: \"corge\" " "dependency: \"foo.proto\" " "message_type { " " name: \"Bar\" " " extension_range { start: 1 end: 1000 } " "} " "extension { name:\"grault\" extendee: \".Foo\" number:32 } " "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); { FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingExtension("Foo", 5, &file)); EXPECT_EQ("foo.proto", file.name()); } { FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingExtension("Foo", 32, &file)); EXPECT_EQ("bar.proto", file.name()); } { // Can find extensions for qualified type names. FileDescriptorProto file; EXPECT_TRUE(database_->FindFileContainingExtension("corge.Bar", 70, &file)); EXPECT_EQ("bar.proto", file.name()); } { // Can't find extensions whose extendee was not fully-qualified in the // FileDescriptorProto. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileContainingExtension("Bar", 56, &file)); EXPECT_FALSE( database_->FindFileContainingExtension("corge.Bar", 56, &file)); } { // Can't find non-existent extension numbers. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileContainingExtension("Foo", 12, &file)); } { // Can't find extensions for non-existent types. FileDescriptorProto file; EXPECT_FALSE( database_->FindFileContainingExtension("NoSuchType", 5, &file)); } { // Can't find extensions for unqualified type names. FileDescriptorProto file; EXPECT_FALSE(database_->FindFileContainingExtension("Bar", 70, &file)); } } TEST_P(DescriptorDatabaseTest, FindAllExtensionNumbers) { AddToDatabase( "name: \"foo.proto\" " "message_type { " " name: \"Foo\" " " extension_range { start: 1 end: 1000 } " " extension { name:\"qux\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " " extendee: \".Foo\" }" "}"); AddToDatabase( "name: \"bar.proto\" " "package: \"corge\" " "dependency: \"foo.proto\" " "message_type { " " name: \"Bar\" " " extension_range { start: 1 end: 1000 } " "} " "extension { name:\"grault\" extendee: \".Foo\" number:32 } " "extension { name:\"garply\" extendee: \".corge.Bar\" number:70 } " "extension { name:\"waldo\" extendee: \"Bar\" number:56 } "); { vector<int> numbers; EXPECT_TRUE(database_->FindAllExtensionNumbers("Foo", &numbers)); ASSERT_EQ(2, numbers.size()); sort(numbers.begin(), numbers.end()); EXPECT_EQ(5, numbers[0]); EXPECT_EQ(32, numbers[1]); } { vector<int> numbers; EXPECT_TRUE(database_->FindAllExtensionNumbers("corge.Bar", &numbers)); // Note: won't find extension 56 due to the name not being fully qualified. ASSERT_EQ(1, numbers.size()); EXPECT_EQ(70, numbers[0]); } { // Can't find extensions for non-existent types. vector<int> numbers; EXPECT_FALSE(database_->FindAllExtensionNumbers("NoSuchType", &numbers)); } { // Can't find extensions for unqualified types. vector<int> numbers; EXPECT_FALSE(database_->FindAllExtensionNumbers("Bar", &numbers)); } } TEST_P(DescriptorDatabaseTest, ConflictingFileError) { AddToDatabase( "name: \"foo.proto\" " "message_type { " " name: \"Foo\" " "}"); AddToDatabaseWithError( "name: \"foo.proto\" " "message_type { " " name: \"Bar\" " "}"); } TEST_P(DescriptorDatabaseTest, ConflictingTypeError) { AddToDatabase( "name: \"foo.proto\" " "message_type { " " name: \"Foo\" " "}"); AddToDatabaseWithError( "name: \"bar.proto\" " "message_type { " " name: \"Foo\" " "}"); } TEST_P(DescriptorDatabaseTest, ConflictingExtensionError) { AddToDatabase( "name: \"foo.proto\" " "extension { name:\"foo\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " " extendee: \".Foo\" }"); AddToDatabaseWithError( "name: \"bar.proto\" " "extension { name:\"bar\" label:LABEL_OPTIONAL type:TYPE_INT32 number:5 " " extendee: \".Foo\" }"); } INSTANTIATE_TEST_CASE_P(Simple, DescriptorDatabaseTest, testing::Values(&SimpleDescriptorDatabaseTestCase::New)); INSTANTIATE_TEST_CASE_P(MemoryConserving, DescriptorDatabaseTest, testing::Values(&EncodedDescriptorDatabaseTestCase::New)); INSTANTIATE_TEST_CASE_P(Pool, DescriptorDatabaseTest, testing::Values(&DescriptorPoolDatabaseTestCase::New)); #endif // GTEST_HAS_PARAM_TEST TEST(EncodedDescriptorDatabaseExtraTest, FindNameOfFileContainingSymbol) { // Create two files, one of which is in two parts. FileDescriptorProto file1, file2a, file2b; file1.set_name("foo.proto"); file1.set_package("foo"); file1.add_message_type()->set_name("Foo"); file2a.set_name("bar.proto"); file2b.set_package("bar"); file2b.add_message_type()->set_name("Bar"); // Normal serialization allows our optimization to kick in. string data1 = file1.SerializeAsString(); // Force out-of-order serialization to test slow path. string data2 = file2b.SerializeAsString() + file2a.SerializeAsString(); // Create EncodedDescriptorDatabase containing both files. EncodedDescriptorDatabase db; db.Add(data1.data(), data1.size()); db.Add(data2.data(), data2.size()); // Test! string filename; EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo", &filename)); EXPECT_EQ("foo.proto", filename); EXPECT_TRUE(db.FindNameOfFileContainingSymbol("foo.Foo.Blah", &filename)); EXPECT_EQ("foo.proto", filename); EXPECT_TRUE(db.FindNameOfFileContainingSymbol("bar.Bar", &filename)); EXPECT_EQ("bar.proto", filename); EXPECT_FALSE(db.FindNameOfFileContainingSymbol("foo", &filename)); EXPECT_FALSE(db.FindNameOfFileContainingSymbol("bar", &filename)); EXPECT_FALSE(db.FindNameOfFileContainingSymbol("baz.Baz", &filename)); } // =================================================================== class MergedDescriptorDatabaseTest : public testing::Test { protected: MergedDescriptorDatabaseTest() : forward_merged_(&database1_, &database2_), reverse_merged_(&database2_, &database1_) {} virtual void SetUp() { AddToDatabase(&database1_, "name: \"foo.proto\" " "message_type { name:\"Foo\" extension_range { start: 1 end: 100 } } " "extension { name:\"foo_ext\" extendee: \".Foo\" number:3 " " label:LABEL_OPTIONAL type:TYPE_INT32 } "); AddToDatabase(&database2_, "name: \"bar.proto\" " "message_type { name:\"Bar\" extension_range { start: 1 end: 100 } } " "extension { name:\"bar_ext\" extendee: \".Bar\" number:5 " " label:LABEL_OPTIONAL type:TYPE_INT32 } "); // baz.proto exists in both pools, with different definitions. AddToDatabase(&database1_, "name: \"baz.proto\" " "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " "message_type { name:\"FromPool1\" } " "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " " label:LABEL_OPTIONAL type:TYPE_INT32 } " "extension { name:\"database1_only_ext\" extendee: \".Baz\" number:13 " " label:LABEL_OPTIONAL type:TYPE_INT32 } "); AddToDatabase(&database2_, "name: \"baz.proto\" " "message_type { name:\"Baz\" extension_range { start: 1 end: 100 } } " "message_type { name:\"FromPool2\" } " "extension { name:\"baz_ext\" extendee: \".Baz\" number:12 " " label:LABEL_OPTIONAL type:TYPE_INT32 } "); } SimpleDescriptorDatabase database1_; SimpleDescriptorDatabase database2_; MergedDescriptorDatabase forward_merged_; MergedDescriptorDatabase reverse_merged_; }; TEST_F(MergedDescriptorDatabaseTest, FindFileByName) { { // Can find file that is only in database1_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileByName("foo.proto", &file)); EXPECT_EQ("foo.proto", file.name()); ExpectContainsType(file, "Foo"); } { // Can find file that is only in database2_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileByName("bar.proto", &file)); EXPECT_EQ("bar.proto", file.name()); ExpectContainsType(file, "Bar"); } { // In forward_merged_, database1_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileByName("baz.proto", &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool1"); } { // In reverse_merged_, database2_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE(reverse_merged_.FindFileByName("baz.proto", &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool2"); } { // Can't find non-existent file. FileDescriptorProto file; EXPECT_FALSE(forward_merged_.FindFileByName("no_such.proto", &file)); } } TEST_F(MergedDescriptorDatabaseTest, FindFileContainingSymbol) { { // Can find file that is only in database1_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Foo", &file)); EXPECT_EQ("foo.proto", file.name()); ExpectContainsType(file, "Foo"); } { // Can find file that is only in database2_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Bar", &file)); EXPECT_EQ("bar.proto", file.name()); ExpectContainsType(file, "Bar"); } { // In forward_merged_, database1_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("Baz", &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool1"); } { // In reverse_merged_, database2_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE(reverse_merged_.FindFileContainingSymbol("Baz", &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool2"); } { // FromPool1 only shows up in forward_merged_ because it is masked by // database2_'s baz.proto in reverse_merged_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileContainingSymbol("FromPool1", &file)); EXPECT_FALSE(reverse_merged_.FindFileContainingSymbol("FromPool1", &file)); } { // Can't find non-existent symbol. FileDescriptorProto file; EXPECT_FALSE( forward_merged_.FindFileContainingSymbol("NoSuchType", &file)); } } TEST_F(MergedDescriptorDatabaseTest, FindFileContainingExtension) { { // Can find file that is only in database1_. FileDescriptorProto file; EXPECT_TRUE( forward_merged_.FindFileContainingExtension("Foo", 3, &file)); EXPECT_EQ("foo.proto", file.name()); ExpectContainsType(file, "Foo"); } { // Can find file that is only in database2_. FileDescriptorProto file; EXPECT_TRUE( forward_merged_.FindFileContainingExtension("Bar", 5, &file)); EXPECT_EQ("bar.proto", file.name()); ExpectContainsType(file, "Bar"); } { // In forward_merged_, database1_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE( forward_merged_.FindFileContainingExtension("Baz", 12, &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool1"); } { // In reverse_merged_, database2_'s baz.proto takes precedence. FileDescriptorProto file; EXPECT_TRUE( reverse_merged_.FindFileContainingExtension("Baz", 12, &file)); EXPECT_EQ("baz.proto", file.name()); ExpectContainsType(file, "FromPool2"); } { // Baz's extension 13 only shows up in forward_merged_ because it is // masked by database2_'s baz.proto in reverse_merged_. FileDescriptorProto file; EXPECT_TRUE(forward_merged_.FindFileContainingExtension("Baz", 13, &file)); EXPECT_FALSE(reverse_merged_.FindFileContainingExtension("Baz", 13, &file)); } { // Can't find non-existent extension. FileDescriptorProto file; EXPECT_FALSE( forward_merged_.FindFileContainingExtension("Foo", 6, &file)); } } TEST_F(MergedDescriptorDatabaseTest, FindAllExtensionNumbers) { { // Message only has extension in database1_ vector<int> numbers; EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Foo", &numbers)); ASSERT_EQ(1, numbers.size()); EXPECT_EQ(3, numbers[0]); } { // Message only has extension in database2_ vector<int> numbers; EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Bar", &numbers)); ASSERT_EQ(1, numbers.size()); EXPECT_EQ(5, numbers[0]); } { // Merge results from the two databases. vector<int> numbers; EXPECT_TRUE(forward_merged_.FindAllExtensionNumbers("Baz", &numbers)); ASSERT_EQ(2, numbers.size()); sort(numbers.begin(), numbers.end()); EXPECT_EQ(12, numbers[0]); EXPECT_EQ(13, numbers[1]); } { vector<int> numbers; EXPECT_TRUE(reverse_merged_.FindAllExtensionNumbers("Baz", &numbers)); ASSERT_EQ(2, numbers.size()); sort(numbers.begin(), numbers.end()); EXPECT_EQ(12, numbers[0]); EXPECT_EQ(13, numbers[1]); } { // Can't find extensions for a non-existent message. vector<int> numbers; EXPECT_FALSE(reverse_merged_.FindAllExtensionNumbers("Blah", &numbers)); } } } // anonymous namespace } // namespace protobuf } // namespace google
{ "language": "C++" }
#ifdef USE_LEVELDB #ifndef CAFFE_UTIL_DB_LEVELDB_HPP #define CAFFE_UTIL_DB_LEVELDB_HPP #include <string> #include "leveldb/db.h" #include "leveldb/write_batch.h" #include "caffe/util/db.hpp" namespace caffe { namespace db { class LevelDBCursor : public Cursor { public: explicit LevelDBCursor(leveldb::Iterator* iter) : iter_(iter) { SeekToFirst(); CHECK(iter_->status().ok()) << iter_->status().ToString(); } ~LevelDBCursor() { delete iter_; } virtual void SeekToFirst() { iter_->SeekToFirst(); } virtual void Next() { iter_->Next(); } virtual string key() { return iter_->key().ToString(); } virtual string value() { return iter_->value().ToString(); } virtual bool valid() { return iter_->Valid(); } private: leveldb::Iterator* iter_; }; class LevelDBTransaction : public Transaction { public: explicit LevelDBTransaction(leveldb::DB* db) : db_(db) { CHECK_NOTNULL(db_); } virtual void Put(const string& key, const string& value) { batch_.Put(key, value); } virtual void Commit() { leveldb::Status status = db_->Write(leveldb::WriteOptions(), &batch_); CHECK(status.ok()) << "Failed to write batch to leveldb " << std::endl << status.ToString(); } private: leveldb::DB* db_; leveldb::WriteBatch batch_; DISABLE_COPY_AND_ASSIGN(LevelDBTransaction); }; class LevelDB : public DB { public: LevelDB() : db_(NULL) { } virtual ~LevelDB() { Close(); } virtual void Open(const string& source, Mode mode); virtual void Close() { if (db_ != NULL) { delete db_; db_ = NULL; } } virtual LevelDBCursor* NewCursor() { return new LevelDBCursor(db_->NewIterator(leveldb::ReadOptions())); } virtual LevelDBTransaction* NewTransaction() { return new LevelDBTransaction(db_); } private: leveldb::DB* db_; }; } // namespace db } // namespace caffe #endif // CAFFE_UTIL_DB_LEVELDB_HPP #endif // USE_LEVELDB
{ "language": "C++" }
/** * This code is released under the * Apache License Version 2.0 http://www.apache.org/licenses/. * * (c) Daniel Lemire, http://lemire.me/en/ */ #ifndef CODECS_H_ #define CODECS_H_ #include "common.h" #include "util.h" #include "bitpackinghelpers.h" namespace FastPForLib { class NotEnoughStorage : public std::runtime_error { public: size_t required; // number of 32-bit symbols required NotEnoughStorage(const size_t req) : runtime_error(""), required(req) {} }; class IntegerCODEC { public: /** * You specify input and input length, as well as * output and output length. nvalue gets modified to * reflect how much was used. If the new value of * nvalue is more than the original value, we can * consider this a buffer overrun. * * You are responsible for allocating the memory (length * for *in and nvalue for *out). */ virtual void encodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) = 0; virtual void encodeArray(const uint64_t *in, const size_t length, uint32_t *out, size_t &nvalue) { throw std::logic_error("Not implemented!"); } /** * Usage is similar to decodeArray except that it returns a pointer * incremented from in. In theory it should be in+length. If the * returned pointer is less than in+length, then this generally means * that the decompression is not finished (some scheme compress * the bulk of the data one way, and they then they compress remaining * integers using another scheme). * * As with encodeArray, you need to have length element allocated * for *in and at least nvalue elements allocated for out. The value * of the variable nvalue gets updated with the number actually use * (if nvalue exceeds the original value, there might be a buffer * overrun). */ virtual const uint32_t *decodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) = 0; virtual const uint32_t *decodeArray(const uint32_t *in, const size_t length, uint64_t *out, size_t &nvalue) { throw std::logic_error("Not implemented!"); } virtual ~IntegerCODEC() {} /** * Will compress the content of a vector into * another vector. * * This is offered for convenience. It might be slow. */ virtual std::vector<uint32_t> compress(const std::vector<uint32_t> &data) { std::vector<uint32_t> compresseddata(data.size() * 2 + 1024); // allocate plenty of memory size_t memavailable = compresseddata.size(); encodeArray(&data[0], data.size(), &compresseddata[0], memavailable); compresseddata.resize(memavailable); return compresseddata; } /** * Will uncompress the content of a vector into * another vector. Some CODECs know exactly how much data to uncompress, * others need to uncompress it all to know how data there is to uncompress... * So it useful to have a hint (expected_uncompressed_size) that tells how * much data there will be to uncompress. Otherwise, the code will * try to guess, but the result is uncertain and inefficient. You really * ought to keep track of how many symbols you had compressed. * * For convenience. Might be slow. */ virtual std::vector<uint32_t> uncompress(const std::vector<uint32_t> &compresseddata, size_t expected_uncompressed_size = 0) { std::vector<uint32_t> data( expected_uncompressed_size); // allocate plenty of memory size_t memavailable = data.size(); try { decodeArray(&compresseddata[0], compresseddata.size(), &data[0], memavailable); } catch (NotEnoughStorage &nes) { data.resize(nes.required + 1024); decodeArray(&compresseddata[0], compresseddata.size(), &data[0], memavailable); } data.resize(memavailable); return data; } virtual std::string name() const = 0; }; /****************** * This just copies the data, no compression. */ class JustCopy : public IntegerCODEC { public: void encodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) { memcpy(out, in, sizeof(uint32_t) * length); nvalue = length; } // like encodeArray, but we don't actually copy void fakeencodeArray(const uint32_t * /*in*/, const size_t length, size_t &nvalue) { nvalue = length; } const uint32_t *decodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) { memcpy(out, in, sizeof(uint32_t) * length); nvalue = length; return in + length; } std::string name() const { return "JustCopy"; } }; /******** * This uses a single bit width for the whole array. * It has fast decompression and random access, but * relatively poor compression. Included as an example. */ class PackedCODEC : public IntegerCODEC { public: enum { BlockSize = 32 }; void encodeArray(const uint32_t *in, const size_t length, uint32_t *out, size_t &nvalue) { checkifdivisibleby(length, 32); const uint32_t b = maxbits(in, in + length); out[0] = static_cast<uint32_t>(length); out[1] = b; out += 2; for (uint32_t run = 0; run < length / 32; ++run, in += 32, out += b) { fastpackwithoutmask(in, out, b); } nvalue = 2 + length * b / 32; } #ifndef NDEBUG const uint32_t *decodeArray(const uint32_t *in, const size_t length, #else const uint32_t *decodeArray(const uint32_t *in, const size_t /*length*/, #endif uint32_t *out, size_t &nvalue) { nvalue = in[0]; const uint32_t b = in[1]; assert(length >= nvalue * b / 32); in += 2; for (uint32_t run = 0; run < nvalue / 32; ++run, in += b, out += 32) { fastunpack(in, out, b); } return in; } std::string name() const { return "PackedCODEC"; } }; } // namespace FastPFor #endif /* CODECS_H_ */
{ "language": "C++" }
//===-- sancov.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 a command-line tool for reading and analyzing sanitizer // coverage. //===----------------------------------------------------------------------===// #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringExtras.h" #include "llvm/ADT/Twine.h" #include "llvm/DebugInfo/Symbolize/Symbolize.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCDisassembler/MCDisassembler.h" #include "llvm/MC/MCInst.h" #include "llvm/MC/MCInstPrinter.h" #include "llvm/MC/MCInstrAnalysis.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCObjectFileInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/Object/Archive.h" #include "llvm/Object/Binary.h" #include "llvm/Object/COFF.h" #include "llvm/Object/ELFObjectFile.h" #include "llvm/Object/MachO.h" #include "llvm/Object/ObjectFile.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Errc.h" #include "llvm/Support/ErrorOr.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/LineIterator.h" #include "llvm/Support/MD5.h" #include "llvm/Support/ManagedStatic.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/Path.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/Regex.h" #include "llvm/Support/SHA1.h" #include "llvm/Support/Signals.h" #include "llvm/Support/SourceMgr.h" #include "llvm/Support/SpecialCaseList.h" #include "llvm/Support/TargetRegistry.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/ToolOutputFile.h" #include "llvm/Support/YAMLParser.h" #include "llvm/Support/raw_ostream.h" #include <algorithm> #include <set> #include <stdio.h> #include <string> #include <utility> #include <vector> using namespace llvm; namespace { // --------- COMMAND LINE FLAGS --------- enum ActionType { CoveredFunctionsAction, HtmlReportAction, MergeAction, NotCoveredFunctionsAction, PrintAction, PrintCovPointsAction, StatsAction, SymbolizeAction }; cl::opt<ActionType> Action( cl::desc("Action (required)"), cl::Required, cl::values( clEnumValN(PrintAction, "print", "Print coverage addresses"), clEnumValN(PrintCovPointsAction, "print-coverage-pcs", "Print coverage instrumentation points addresses."), clEnumValN(CoveredFunctionsAction, "covered-functions", "Print all covered funcions."), clEnumValN(NotCoveredFunctionsAction, "not-covered-functions", "Print all not covered funcions."), clEnumValN(StatsAction, "print-coverage-stats", "Print coverage statistics."), clEnumValN(HtmlReportAction, "html-report", "REMOVED. Use -symbolize & coverage-report-server.py."), clEnumValN(SymbolizeAction, "symbolize", "Produces a symbolized JSON report from binary report."), clEnumValN(MergeAction, "merge", "Merges reports."))); static cl::list<std::string> ClInputFiles(cl::Positional, cl::OneOrMore, cl::desc("<action> <binary files...> <.sancov files...> " "<.symcov files...>")); static cl::opt<bool> ClDemangle("demangle", cl::init(true), cl::desc("Print demangled function name.")); static cl::opt<bool> ClSkipDeadFiles("skip-dead-files", cl::init(true), cl::desc("Do not list dead source files in reports.")); static cl::opt<std::string> ClStripPathPrefix( "strip_path_prefix", cl::init(""), cl::desc("Strip this prefix from file paths in reports.")); static cl::opt<std::string> ClBlacklist("blacklist", cl::init(""), cl::desc("Blacklist file (sanitizer blacklist format).")); static cl::opt<bool> ClUseDefaultBlacklist( "use_default_blacklist", cl::init(true), cl::Hidden, cl::desc("Controls if default blacklist should be used.")); static const char *const DefaultBlacklistStr = "fun:__sanitizer_.*\n" "src:/usr/include/.*\n" "src:.*/libc\\+\\+/.*\n"; // --------- FORMAT SPECIFICATION --------- struct FileHeader { uint32_t Bitness; uint32_t Magic; }; static const uint32_t BinCoverageMagic = 0xC0BFFFFF; static const uint32_t Bitness32 = 0xFFFFFF32; static const uint32_t Bitness64 = 0xFFFFFF64; static Regex SancovFileRegex("(.*)\\.[0-9]+\\.sancov"); static Regex SymcovFileRegex(".*\\.symcov"); // --------- MAIN DATASTRUCTURES ---------- // Contents of .sancov file: list of coverage point addresses that were // executed. struct RawCoverage { explicit RawCoverage(std::unique_ptr<std::set<uint64_t>> Addrs) : Addrs(std::move(Addrs)) {} // Read binary .sancov file. static ErrorOr<std::unique_ptr<RawCoverage>> read(const std::string &FileName); std::unique_ptr<std::set<uint64_t>> Addrs; }; // Coverage point has an opaque Id and corresponds to multiple source locations. struct CoveragePoint { explicit CoveragePoint(const std::string &Id) : Id(Id) {} std::string Id; SmallVector<DILineInfo, 1> Locs; }; // Symcov file content: set of covered Ids plus information about all available // coverage points. struct SymbolizedCoverage { // Read json .symcov file. static std::unique_ptr<SymbolizedCoverage> read(const std::string &InputFile); std::set<std::string> CoveredIds; std::string BinaryHash; std::vector<CoveragePoint> Points; }; struct CoverageStats { size_t AllPoints; size_t CovPoints; size_t AllFns; size_t CovFns; }; // --------- ERROR HANDLING --------- static void fail(const llvm::Twine &E) { errs() << "ERROR: " << E << "\n"; exit(1); } static void failIf(bool B, const llvm::Twine &E) { if (B) fail(E); } static void failIfError(std::error_code Error) { if (!Error) return; errs() << "ERROR: " << Error.message() << "(" << Error.value() << ")\n"; exit(1); } template <typename T> static void failIfError(const ErrorOr<T> &E) { failIfError(E.getError()); } static void failIfError(Error Err) { if (Err) { logAllUnhandledErrors(std::move(Err), errs(), "ERROR: "); exit(1); } } template <typename T> static void failIfError(Expected<T> &E) { failIfError(E.takeError()); } static void failIfNotEmpty(const llvm::Twine &E) { if (E.str().empty()) return; fail(E); } template <typename T> static void failIfEmpty(const std::unique_ptr<T> &Ptr, const std::string &Message) { if (Ptr.get()) return; fail(Message); } // ----------- Coverage I/O ---------- template <typename T> static void readInts(const char *Start, const char *End, std::set<uint64_t> *Ints) { const T *S = reinterpret_cast<const T *>(Start); const T *E = reinterpret_cast<const T *>(End); std::copy(S, E, std::inserter(*Ints, Ints->end())); } ErrorOr<std::unique_ptr<RawCoverage>> RawCoverage::read(const std::string &FileName) { ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) return BufOrErr.getError(); std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { errs() << "File too small (<8): " << Buf->getBufferSize() << '\n'; return make_error_code(errc::illegal_byte_sequence); } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); if (Header->Magic != BinCoverageMagic) { errs() << "Wrong magic: " << Header->Magic << '\n'; return make_error_code(errc::illegal_byte_sequence); } auto Addrs = llvm::make_unique<std::set<uint64_t>>(); switch (Header->Bitness) { case Bitness64: readInts<uint64_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; case Bitness32: readInts<uint32_t>(Buf->getBufferStart() + 8, Buf->getBufferEnd(), Addrs.get()); break; default: errs() << "Unsupported bitness: " << Header->Bitness << '\n'; return make_error_code(errc::illegal_byte_sequence); } return std::unique_ptr<RawCoverage>(new RawCoverage(std::move(Addrs))); } // Print coverage addresses. raw_ostream &operator<<(raw_ostream &OS, const RawCoverage &CoverageData) { for (auto Addr : *CoverageData.Addrs) { OS << "0x"; OS.write_hex(Addr); OS << "\n"; } return OS; } static raw_ostream &operator<<(raw_ostream &OS, const CoverageStats &Stats) { OS << "all-edges: " << Stats.AllPoints << "\n"; OS << "cov-edges: " << Stats.CovPoints << "\n"; OS << "all-functions: " << Stats.AllFns << "\n"; OS << "cov-functions: " << Stats.CovFns << "\n"; return OS; } // Helper for writing out JSON. Handles indents and commas using // scope variables for objects and arrays. class JSONWriter { public: JSONWriter(raw_ostream &Out) : OS(Out) {} JSONWriter(const JSONWriter &) = delete; ~JSONWriter() { OS << "\n"; } void operator<<(StringRef S) { printJSONStringLiteral(S, OS); } // Helper RAII class to output JSON objects. class Object { public: Object(JSONWriter *W, raw_ostream &OS) : W(W), OS(OS) { OS << "{"; W->Indent++; } Object(const Object &) = delete; ~Object() { W->Indent--; OS << "\n"; W->indent(); OS << "}"; } void key(StringRef Key) { Index++; if (Index > 0) OS << ","; OS << "\n"; W->indent(); printJSONStringLiteral(Key, OS); OS << " : "; } private: JSONWriter *W; raw_ostream &OS; int Index = -1; }; std::unique_ptr<Object> object() { return make_unique<Object>(this, OS); } // Helper RAII class to output JSON arrays. class Array { public: Array(raw_ostream &OS) : OS(OS) { OS << "["; } Array(const Array &) = delete; ~Array() { OS << "]"; } void next() { Index++; if (Index > 0) OS << ", "; } private: raw_ostream &OS; int Index = -1; }; std::unique_ptr<Array> array() { return make_unique<Array>(OS); } private: void indent() { OS.indent(Indent * 2); } static void printJSONStringLiteral(StringRef S, raw_ostream &OS) { if (S.find('"') == std::string::npos) { OS << "\"" << S << "\""; return; } OS << "\""; for (char Ch : S.bytes()) { if (Ch == '"') OS << "\\"; OS << Ch; } OS << "\""; } raw_ostream &OS; int Indent = 0; }; // Output symbolized information for coverage points in JSON. // Format: // { // '<file_name>' : { // '<function_name>' : { // '<point_id'> : '<line_number>:'<column_number'. // .... // } // } // } static void operator<<(JSONWriter &W, const std::vector<CoveragePoint> &Points) { // Group points by file. auto ByFile(W.object()); std::map<std::string, std::vector<const CoveragePoint *>> PointsByFile; for (const auto &Point : Points) { for (const DILineInfo &Loc : Point.Locs) { PointsByFile[Loc.FileName].push_back(&Point); } } for (const auto &P : PointsByFile) { std::string FileName = P.first; ByFile->key(FileName); // Group points by function. auto ByFn(W.object()); std::map<std::string, std::vector<const CoveragePoint *>> PointsByFn; for (auto PointPtr : P.second) { for (const DILineInfo &Loc : PointPtr->Locs) { PointsByFn[Loc.FunctionName].push_back(PointPtr); } } for (const auto &P : PointsByFn) { std::string FunctionName = P.first; std::set<std::string> WrittenIds; ByFn->key(FunctionName); // Output <point_id> : "<line>:<col>". auto ById(W.object()); for (const CoveragePoint *Point : P.second) { for (const auto &Loc : Point->Locs) { if (Loc.FileName != FileName || Loc.FunctionName != FunctionName) continue; if (WrittenIds.find(Point->Id) != WrittenIds.end()) continue; WrittenIds.insert(Point->Id); ById->key(Point->Id); W << (utostr(Loc.Line) + ":" + utostr(Loc.Column)); } } } } } static void operator<<(JSONWriter &W, const SymbolizedCoverage &C) { auto O(W.object()); { O->key("covered-points"); auto PointsArray(W.array()); for (const auto &P : C.CoveredIds) { PointsArray->next(); W << P; } } { if (!C.BinaryHash.empty()) { O->key("binary-hash"); W << C.BinaryHash; } } { O->key("point-symbol-info"); W << C.Points; } } static std::string parseScalarString(yaml::Node *N) { SmallString<64> StringStorage; yaml::ScalarNode *S = dyn_cast<yaml::ScalarNode>(N); failIf(!S, "expected string"); return S->getValue(StringStorage); } std::unique_ptr<SymbolizedCoverage> SymbolizedCoverage::read(const std::string &InputFile) { auto Coverage(make_unique<SymbolizedCoverage>()); std::map<std::string, CoveragePoint> Points; ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(InputFile); failIfError(BufOrErr); SourceMgr SM; yaml::Stream S(**BufOrErr, SM); yaml::document_iterator DI = S.begin(); failIf(DI == S.end(), "empty document: " + InputFile); yaml::Node *Root = DI->getRoot(); failIf(!Root, "expecting root node: " + InputFile); yaml::MappingNode *Top = dyn_cast<yaml::MappingNode>(Root); failIf(!Top, "expecting mapping node: " + InputFile); for (auto &KVNode : *Top) { auto Key = parseScalarString(KVNode.getKey()); if (Key == "covered-points") { yaml::SequenceNode *Points = dyn_cast<yaml::SequenceNode>(KVNode.getValue()); failIf(!Points, "expected array: " + InputFile); for (auto I = Points->begin(), E = Points->end(); I != E; ++I) { Coverage->CoveredIds.insert(parseScalarString(&*I)); } } else if (Key == "binary-hash") { Coverage->BinaryHash = parseScalarString(KVNode.getValue()); } else if (Key == "point-symbol-info") { yaml::MappingNode *PointSymbolInfo = dyn_cast<yaml::MappingNode>(KVNode.getValue()); failIf(!PointSymbolInfo, "expected mapping node: " + InputFile); for (auto &FileKVNode : *PointSymbolInfo) { auto Filename = parseScalarString(FileKVNode.getKey()); yaml::MappingNode *FileInfo = dyn_cast<yaml::MappingNode>(FileKVNode.getValue()); failIf(!FileInfo, "expected mapping node: " + InputFile); for (auto &FunctionKVNode : *FileInfo) { auto FunctionName = parseScalarString(FunctionKVNode.getKey()); yaml::MappingNode *FunctionInfo = dyn_cast<yaml::MappingNode>(FunctionKVNode.getValue()); failIf(!FunctionInfo, "expected mapping node: " + InputFile); for (auto &PointKVNode : *FunctionInfo) { auto PointId = parseScalarString(PointKVNode.getKey()); auto Loc = parseScalarString(PointKVNode.getValue()); size_t ColonPos = Loc.find(':'); failIf(ColonPos == std::string::npos, "expected ':': " + InputFile); auto LineStr = Loc.substr(0, ColonPos); auto ColStr = Loc.substr(ColonPos + 1, Loc.size()); if (Points.find(PointId) == Points.end()) Points.insert(std::make_pair(PointId, CoveragePoint(PointId))); DILineInfo LineInfo; LineInfo.FileName = Filename; LineInfo.FunctionName = FunctionName; char *End; LineInfo.Line = std::strtoul(LineStr.c_str(), &End, 10); LineInfo.Column = std::strtoul(ColStr.c_str(), &End, 10); CoveragePoint *CoveragePoint = &Points.find(PointId)->second; CoveragePoint->Locs.push_back(LineInfo); } } } } else { errs() << "Ignoring unknown key: " << Key << "\n"; } } for (auto &KV : Points) { Coverage->Points.push_back(KV.second); } return Coverage; } // ---------- MAIN FUNCTIONALITY ---------- std::string stripPathPrefix(std::string Path) { if (ClStripPathPrefix.empty()) return Path; size_t Pos = Path.find(ClStripPathPrefix); if (Pos == std::string::npos) return Path; return Path.substr(Pos + ClStripPathPrefix.size()); } static std::unique_ptr<symbolize::LLVMSymbolizer> createSymbolizer() { symbolize::LLVMSymbolizer::Options SymbolizerOptions; SymbolizerOptions.Demangle = ClDemangle; SymbolizerOptions.UseSymbolTable = true; return std::unique_ptr<symbolize::LLVMSymbolizer>( new symbolize::LLVMSymbolizer(SymbolizerOptions)); } static std::string normalizeFilename(const std::string &FileName) { SmallString<256> S(FileName); sys::path::remove_dots(S, /* remove_dot_dot */ true); return stripPathPrefix(S.str().str()); } class Blacklists { public: Blacklists() : DefaultBlacklist(createDefaultBlacklist()), UserBlacklist(createUserBlacklist()) {} bool isBlacklisted(const DILineInfo &I) { if (DefaultBlacklist && DefaultBlacklist->inSection("fun", I.FunctionName)) return true; if (DefaultBlacklist && DefaultBlacklist->inSection("src", I.FileName)) return true; if (UserBlacklist && UserBlacklist->inSection("fun", I.FunctionName)) return true; if (UserBlacklist && UserBlacklist->inSection("src", I.FileName)) return true; return false; } private: static std::unique_ptr<SpecialCaseList> createDefaultBlacklist() { if (!ClUseDefaultBlacklist) return std::unique_ptr<SpecialCaseList>(); std::unique_ptr<MemoryBuffer> MB = MemoryBuffer::getMemBuffer(DefaultBlacklistStr); std::string Error; auto Blacklist = SpecialCaseList::create(MB.get(), Error); failIfNotEmpty(Error); return Blacklist; } static std::unique_ptr<SpecialCaseList> createUserBlacklist() { if (ClBlacklist.empty()) return std::unique_ptr<SpecialCaseList>(); return SpecialCaseList::createOrDie({{ClBlacklist}}); } std::unique_ptr<SpecialCaseList> DefaultBlacklist; std::unique_ptr<SpecialCaseList> UserBlacklist; }; static std::vector<CoveragePoint> getCoveragePoints(const std::string &ObjectFile, const std::set<uint64_t> &Addrs, const std::set<uint64_t> &CoveredAddrs) { std::vector<CoveragePoint> Result; auto Symbolizer(createSymbolizer()); Blacklists B; std::set<std::string> CoveredFiles; if (ClSkipDeadFiles) { for (auto Addr : CoveredAddrs) { auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, Addr); failIfError(LineInfo); CoveredFiles.insert(LineInfo->FileName); auto InliningInfo = Symbolizer->symbolizeInlinedCode(ObjectFile, Addr); failIfError(InliningInfo); for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { auto FrameInfo = InliningInfo->getFrame(I); CoveredFiles.insert(FrameInfo.FileName); } } } for (auto Addr : Addrs) { std::set<DILineInfo> Infos; // deduplicate debug info. auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, Addr); failIfError(LineInfo); if (ClSkipDeadFiles && CoveredFiles.find(LineInfo->FileName) == CoveredFiles.end()) continue; LineInfo->FileName = normalizeFilename(LineInfo->FileName); if (B.isBlacklisted(*LineInfo)) continue; auto Id = utohexstr(Addr, true); auto Point = CoveragePoint(Id); Infos.insert(*LineInfo); Point.Locs.push_back(*LineInfo); auto InliningInfo = Symbolizer->symbolizeInlinedCode(ObjectFile, Addr); failIfError(InliningInfo); for (uint32_t I = 0; I < InliningInfo->getNumberOfFrames(); ++I) { auto FrameInfo = InliningInfo->getFrame(I); if (ClSkipDeadFiles && CoveredFiles.find(FrameInfo.FileName) == CoveredFiles.end()) continue; FrameInfo.FileName = normalizeFilename(FrameInfo.FileName); if (B.isBlacklisted(FrameInfo)) continue; if (Infos.find(FrameInfo) == Infos.end()) { Infos.insert(FrameInfo); Point.Locs.push_back(FrameInfo); } } Result.push_back(Point); } return Result; } static bool isCoveragePointSymbol(StringRef Name) { return Name == "__sanitizer_cov" || Name == "__sanitizer_cov_with_check" || Name == "__sanitizer_cov_trace_func_enter" || Name == "__sanitizer_cov_trace_pc_guard" || // Mac has '___' prefix Name == "___sanitizer_cov" || Name == "___sanitizer_cov_with_check" || Name == "___sanitizer_cov_trace_func_enter" || Name == "___sanitizer_cov_trace_pc_guard"; } // Locate __sanitizer_cov* function addresses inside the stubs table on MachO. static void findMachOIndirectCovFunctions(const object::MachOObjectFile &O, std::set<uint64_t> *Result) { MachO::dysymtab_command Dysymtab = O.getDysymtabLoadCommand(); MachO::symtab_command Symtab = O.getSymtabLoadCommand(); for (const auto &Load : O.load_commands()) { if (Load.C.cmd == MachO::LC_SEGMENT_64) { MachO::segment_command_64 Seg = O.getSegment64LoadCommand(Load); for (unsigned J = 0; J < Seg.nsects; ++J) { MachO::section_64 Sec = O.getSection64(Load, J); uint32_t SectionType = Sec.flags & MachO::SECTION_TYPE; if (SectionType == MachO::S_SYMBOL_STUBS) { uint32_t Stride = Sec.reserved2; uint32_t Cnt = Sec.size / Stride; uint32_t N = Sec.reserved1; for (uint32_t J = 0; J < Cnt && N + J < Dysymtab.nindirectsyms; J++) { uint32_t IndirectSymbol = O.getIndirectSymbolTableEntry(Dysymtab, N + J); uint64_t Addr = Sec.addr + J * Stride; if (IndirectSymbol < Symtab.nsyms) { object::SymbolRef Symbol = *(O.getSymbolByIndex(IndirectSymbol)); Expected<StringRef> Name = Symbol.getName(); failIfError(Name); if (isCoveragePointSymbol(Name.get())) { Result->insert(Addr); } } } } } } if (Load.C.cmd == MachO::LC_SEGMENT) { errs() << "ERROR: 32 bit MachO binaries not supported\n"; } } } // Locate __sanitizer_cov* function addresses that are used for coverage // reporting. static std::set<uint64_t> findSanitizerCovFunctions(const object::ObjectFile &O) { std::set<uint64_t> Result; for (const object::SymbolRef &Symbol : O.symbols()) { Expected<uint64_t> AddressOrErr = Symbol.getAddress(); failIfError(AddressOrErr); uint64_t Address = AddressOrErr.get(); Expected<StringRef> NameOrErr = Symbol.getName(); failIfError(NameOrErr); StringRef Name = NameOrErr.get(); if (!(Symbol.getFlags() & object::BasicSymbolRef::SF_Undefined) && isCoveragePointSymbol(Name)) { Result.insert(Address); } } if (const auto *CO = dyn_cast<object::COFFObjectFile>(&O)) { for (const object::ExportDirectoryEntryRef &Export : CO->export_directories()) { uint32_t RVA; std::error_code EC = Export.getExportRVA(RVA); failIfError(EC); StringRef Name; EC = Export.getSymbolName(Name); failIfError(EC); if (isCoveragePointSymbol(Name)) Result.insert(CO->getImageBase() + RVA); } } if (const auto *MO = dyn_cast<object::MachOObjectFile>(&O)) { findMachOIndirectCovFunctions(*MO, &Result); } return Result; } // Locate addresses of all coverage points in a file. Coverage point // is defined as the 'address of instruction following __sanitizer_cov // call - 1'. static void getObjectCoveragePoints(const object::ObjectFile &O, std::set<uint64_t> *Addrs) { Triple TheTriple("unknown-unknown-unknown"); TheTriple.setArch(Triple::ArchType(O.getArch())); auto TripleName = TheTriple.getTriple(); std::string Error; const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); failIfNotEmpty(Error); std::unique_ptr<const MCSubtargetInfo> STI( TheTarget->createMCSubtargetInfo(TripleName, "", "")); failIfEmpty(STI, "no subtarget info for target " + TripleName); std::unique_ptr<const MCRegisterInfo> MRI( TheTarget->createMCRegInfo(TripleName)); failIfEmpty(MRI, "no register info for target " + TripleName); std::unique_ptr<const MCAsmInfo> AsmInfo( TheTarget->createMCAsmInfo(*MRI, TripleName)); failIfEmpty(AsmInfo, "no asm info for target " + TripleName); std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo); MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get()); std::unique_ptr<MCDisassembler> DisAsm( TheTarget->createMCDisassembler(*STI, Ctx)); failIfEmpty(DisAsm, "no disassembler info for target " + TripleName); std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); failIfEmpty(MII, "no instruction info for target " + TripleName); std::unique_ptr<const MCInstrAnalysis> MIA( TheTarget->createMCInstrAnalysis(MII.get())); failIfEmpty(MIA, "no instruction analysis info for target " + TripleName); auto SanCovAddrs = findSanitizerCovFunctions(O); if (SanCovAddrs.empty()) fail("__sanitizer_cov* functions not found"); for (object::SectionRef Section : O.sections()) { if (Section.isVirtual() || !Section.isText()) // llvm-objdump does the same. continue; uint64_t SectionAddr = Section.getAddress(); uint64_t SectSize = Section.getSize(); if (!SectSize) continue; StringRef BytesStr; failIfError(Section.getContents(BytesStr)); ArrayRef<uint8_t> Bytes(reinterpret_cast<const uint8_t *>(BytesStr.data()), BytesStr.size()); for (uint64_t Index = 0, Size = 0; Index < Section.getSize(); Index += Size) { MCInst Inst; if (!DisAsm->getInstruction(Inst, Size, Bytes.slice(Index), SectionAddr + Index, nulls(), nulls())) { if (Size == 0) Size = 1; continue; } uint64_t Addr = Index + SectionAddr; // Sanitizer coverage uses the address of the next instruction - 1. uint64_t CovPoint = Addr + Size - 1; uint64_t Target; if (MIA->isCall(Inst) && MIA->evaluateBranch(Inst, SectionAddr + Index, Size, Target) && SanCovAddrs.find(Target) != SanCovAddrs.end()) Addrs->insert(CovPoint); } } } static void visitObjectFiles(const object::Archive &A, function_ref<void(const object::ObjectFile &)> Fn) { Error Err = Error::success(); for (auto &C : A.children(Err)) { Expected<std::unique_ptr<object::Binary>> ChildOrErr = C.getAsBinary(); failIfError(ChildOrErr); if (auto *O = dyn_cast<object::ObjectFile>(&*ChildOrErr.get())) Fn(*O); else failIfError(object::object_error::invalid_file_type); } failIfError(std::move(Err)); } static void visitObjectFiles(const std::string &FileName, function_ref<void(const object::ObjectFile &)> Fn) { Expected<object::OwningBinary<object::Binary>> BinaryOrErr = object::createBinary(FileName); if (!BinaryOrErr) failIfError(BinaryOrErr); object::Binary &Binary = *BinaryOrErr.get().getBinary(); if (object::Archive *A = dyn_cast<object::Archive>(&Binary)) visitObjectFiles(*A, Fn); else if (object::ObjectFile *O = dyn_cast<object::ObjectFile>(&Binary)) Fn(*O); else failIfError(object::object_error::invalid_file_type); } static std::set<uint64_t> findSanitizerCovFunctions(const std::string &FileName) { std::set<uint64_t> Result; visitObjectFiles(FileName, [&](const object::ObjectFile &O) { auto Addrs = findSanitizerCovFunctions(O); Result.insert(Addrs.begin(), Addrs.end()); }); return Result; } // Locate addresses of all coverage points in a file. Coverage point // is defined as the 'address of instruction following __sanitizer_cov // call - 1'. static std::set<uint64_t> findCoveragePointAddrs(const std::string &FileName) { std::set<uint64_t> Result; visitObjectFiles(FileName, [&](const object::ObjectFile &O) { getObjectCoveragePoints(O, &Result); }); return Result; } static void printCovPoints(const std::string &ObjFile, raw_ostream &OS) { for (uint64_t Addr : findCoveragePointAddrs(ObjFile)) { OS << "0x"; OS.write_hex(Addr); OS << "\n"; } } static ErrorOr<bool> isCoverageFile(const std::string &FileName) { auto ShortFileName = llvm::sys::path::filename(FileName); if (!SancovFileRegex.match(ShortFileName)) return false; ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(FileName); if (!BufOrErr) { errs() << "Warning: " << BufOrErr.getError().message() << "(" << BufOrErr.getError().value() << "), filename: " << llvm::sys::path::filename(FileName) << "\n"; return BufOrErr.getError(); } std::unique_ptr<MemoryBuffer> Buf = std::move(BufOrErr.get()); if (Buf->getBufferSize() < 8) { return false; } const FileHeader *Header = reinterpret_cast<const FileHeader *>(Buf->getBufferStart()); return Header->Magic == BinCoverageMagic; } static bool isSymbolizedCoverageFile(const std::string &FileName) { auto ShortFileName = llvm::sys::path::filename(FileName); return SymcovFileRegex.match(ShortFileName); } static std::unique_ptr<SymbolizedCoverage> symbolize(const RawCoverage &Data, const std::string ObjectFile) { auto Coverage = make_unique<SymbolizedCoverage>(); ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr = MemoryBuffer::getFile(ObjectFile); failIfError(BufOrErr); SHA1 Hasher; Hasher.update((*BufOrErr)->getBuffer()); Coverage->BinaryHash = toHex(Hasher.final()); Blacklists B; auto Symbolizer(createSymbolizer()); for (uint64_t Addr : *Data.Addrs) { auto LineInfo = Symbolizer->symbolizeCode(ObjectFile, Addr); failIfError(LineInfo); if (B.isBlacklisted(*LineInfo)) continue; Coverage->CoveredIds.insert(utohexstr(Addr, true)); } std::set<uint64_t> AllAddrs = findCoveragePointAddrs(ObjectFile); if (!std::includes(AllAddrs.begin(), AllAddrs.end(), Data.Addrs->begin(), Data.Addrs->end())) { fail("Coverage points in binary and .sancov file do not match."); } Coverage->Points = getCoveragePoints(ObjectFile, AllAddrs, *Data.Addrs); return Coverage; } struct FileFn { bool operator<(const FileFn &RHS) const { return std::tie(FileName, FunctionName) < std::tie(RHS.FileName, RHS.FunctionName); } std::string FileName; std::string FunctionName; }; static std::set<FileFn> computeFunctions(const std::vector<CoveragePoint> &Points) { std::set<FileFn> Fns; for (const auto &Point : Points) { for (const auto &Loc : Point.Locs) { Fns.insert(FileFn{Loc.FileName, Loc.FunctionName}); } } return Fns; } static std::set<FileFn> computeNotCoveredFunctions(const SymbolizedCoverage &Coverage) { auto Fns = computeFunctions(Coverage.Points); for (const auto &Point : Coverage.Points) { if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) continue; for (const auto &Loc : Point.Locs) { Fns.erase(FileFn{Loc.FileName, Loc.FunctionName}); } } return Fns; } static std::set<FileFn> computeCoveredFunctions(const SymbolizedCoverage &Coverage) { auto AllFns = computeFunctions(Coverage.Points); std::set<FileFn> Result; for (const auto &Point : Coverage.Points) { if (Coverage.CoveredIds.find(Point.Id) == Coverage.CoveredIds.end()) continue; for (const auto &Loc : Point.Locs) { Result.insert(FileFn{Loc.FileName, Loc.FunctionName}); } } return Result; } typedef std::map<FileFn, std::pair<uint32_t, uint32_t>> FunctionLocs; // finds first location in a file for each function. static FunctionLocs resolveFunctions(const SymbolizedCoverage &Coverage, const std::set<FileFn> &Fns) { FunctionLocs Result; for (const auto &Point : Coverage.Points) { for (const auto &Loc : Point.Locs) { FileFn Fn = FileFn{Loc.FileName, Loc.FunctionName}; if (Fns.find(Fn) == Fns.end()) continue; auto P = std::make_pair(Loc.Line, Loc.Column); auto I = Result.find(Fn); if (I == Result.end() || I->second > P) { Result[Fn] = P; } } } return Result; } static void printFunctionLocs(const FunctionLocs &FnLocs, raw_ostream &OS) { for (const auto &P : FnLocs) { OS << stripPathPrefix(P.first.FileName) << ":" << P.second.first << " " << P.first.FunctionName << "\n"; } } CoverageStats computeStats(const SymbolizedCoverage &Coverage) { CoverageStats Stats = {Coverage.Points.size(), Coverage.CoveredIds.size(), computeFunctions(Coverage.Points).size(), computeCoveredFunctions(Coverage).size()}; return Stats; } // Print list of covered functions. // Line format: <file_name>:<line> <function_name> static void printCoveredFunctions(const SymbolizedCoverage &CovData, raw_ostream &OS) { auto CoveredFns = computeCoveredFunctions(CovData); printFunctionLocs(resolveFunctions(CovData, CoveredFns), OS); } // Print list of not covered functions. // Line format: <file_name>:<line> <function_name> static void printNotCoveredFunctions(const SymbolizedCoverage &CovData, raw_ostream &OS) { auto NotCoveredFns = computeNotCoveredFunctions(CovData); printFunctionLocs(resolveFunctions(CovData, NotCoveredFns), OS); } // Read list of files and merges their coverage info. static void readAndPrintRawCoverage(const std::vector<std::string> &FileNames, raw_ostream &OS) { std::vector<std::unique_ptr<RawCoverage>> Covs; for (const auto &FileName : FileNames) { auto Cov = RawCoverage::read(FileName); if (!Cov) continue; OS << *Cov.get(); } } static std::unique_ptr<SymbolizedCoverage> merge(const std::vector<std::unique_ptr<SymbolizedCoverage>> &Coverages) { if (Coverages.empty()) return nullptr; auto Result = make_unique<SymbolizedCoverage>(); for (size_t I = 0; I < Coverages.size(); ++I) { const SymbolizedCoverage &Coverage = *Coverages[I]; std::string Prefix; if (Coverages.size() > 1) { // prefix is not needed when there's only one file. Prefix = utostr(I); } for (const auto &Id : Coverage.CoveredIds) { Result->CoveredIds.insert(Prefix + Id); } for (const auto &CovPoint : Coverage.Points) { CoveragePoint NewPoint(CovPoint); NewPoint.Id = Prefix + CovPoint.Id; Result->Points.push_back(NewPoint); } } if (Coverages.size() == 1) { Result->BinaryHash = Coverages[0]->BinaryHash; } return Result; } static std::unique_ptr<SymbolizedCoverage> readSymbolizeAndMergeCmdArguments(std::vector<std::string> FileNames) { std::vector<std::unique_ptr<SymbolizedCoverage>> Coverages; { // Short name => file name. std::map<std::string, std::string> ObjFiles; std::string FirstObjFile; std::set<std::string> CovFiles; // Partition input values into coverage/object files. for (const auto &FileName : FileNames) { if (isSymbolizedCoverageFile(FileName)) { Coverages.push_back(SymbolizedCoverage::read(FileName)); } auto ErrorOrIsCoverage = isCoverageFile(FileName); if (!ErrorOrIsCoverage) continue; if (ErrorOrIsCoverage.get()) { CovFiles.insert(FileName); } else { auto ShortFileName = llvm::sys::path::filename(FileName); if (ObjFiles.find(ShortFileName) != ObjFiles.end()) { fail("Duplicate binary file with a short name: " + ShortFileName); } ObjFiles[ShortFileName] = FileName; if (FirstObjFile.empty()) FirstObjFile = FileName; } } SmallVector<StringRef, 2> Components; // Object file => list of corresponding coverage file names. std::map<std::string, std::vector<std::string>> CoverageByObjFile; for (const auto &FileName : CovFiles) { auto ShortFileName = llvm::sys::path::filename(FileName); auto Ok = SancovFileRegex.match(ShortFileName, &Components); if (!Ok) { fail("Can't match coverage file name against " "<module_name>.<pid>.sancov pattern: " + FileName); } auto Iter = ObjFiles.find(Components[1]); if (Iter == ObjFiles.end()) { fail("Object file for coverage not found: " + FileName); } CoverageByObjFile[Iter->second].push_back(FileName); }; for (const auto &Pair : ObjFiles) { auto FileName = Pair.second; if (CoverageByObjFile.find(FileName) == CoverageByObjFile.end()) errs() << "WARNING: No coverage file for " << FileName << "\n"; } // Read raw coverage and symbolize it. for (const auto &Pair : CoverageByObjFile) { if (findSanitizerCovFunctions(Pair.first).empty()) { errs() << "WARNING: Ignoring " << Pair.first << " and its coverage because __sanitizer_cov* functions were not " "found.\n"; continue; } for (const std::string &CoverageFile : Pair.second) { auto DataOrError = RawCoverage::read(CoverageFile); failIfError(DataOrError); Coverages.push_back(symbolize(*DataOrError.get(), Pair.first)); } } } return merge(Coverages); } } // namespace int main(int Argc, char **Argv) { // Print stack trace if we signal out. sys::PrintStackTraceOnErrorSignal(Argv[0]); PrettyStackTraceProgram X(Argc, Argv); llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllDisassemblers(); cl::ParseCommandLineOptions(Argc, Argv, "Sanitizer Coverage Processing Tool (sancov)\n\n" " This tool can extract various coverage-related information from: \n" " coverage-instrumented binary files, raw .sancov files and their " "symbolized .symcov version.\n" " Depending on chosen action the tool expects different input files:\n" " -print-coverage-pcs - coverage-instrumented binary files\n" " -print-coverage - .sancov files\n" " <other actions> - .sancov files & corresponding binary " "files, .symcov files\n" ); // -print doesn't need object files. if (Action == PrintAction) { readAndPrintRawCoverage(ClInputFiles, outs()); return 0; } else if (Action == PrintCovPointsAction) { // -print-coverage-points doesn't need coverage files. for (const std::string &ObjFile : ClInputFiles) { printCovPoints(ObjFile, outs()); } return 0; } auto Coverage = readSymbolizeAndMergeCmdArguments(ClInputFiles); failIf(!Coverage, "No valid coverage files given."); switch (Action) { case CoveredFunctionsAction: { printCoveredFunctions(*Coverage, outs()); return 0; } case NotCoveredFunctionsAction: { printNotCoveredFunctions(*Coverage, outs()); return 0; } case StatsAction: { outs() << computeStats(*Coverage); return 0; } case MergeAction: case SymbolizeAction: { // merge & symbolize are synonims. JSONWriter W(outs()); W << *Coverage; return 0; } case HtmlReportAction: errs() << "-html-report option is removed: " "use -symbolize & coverage-report-server.py instead\n"; return 1; case PrintAction: case PrintCovPointsAction: llvm_unreachable("unsupported action"); } }
{ "language": "C++" }
#include <algorithm> #include <vector> #include <sstream> using namespace std; char ispal[2501][2501]; struct PalindromesAnalyzer { long long summaryLength(vector<string> te) { string text = ""; for (int i = 0; i < te.size(); i++) text += te[i]; int n = text.size(); memset(ispal, 0, sizeof(ispal)); for (int i = 0; i < n; i++) ispal[0][i] = ispal[1][i] = 1; for (int len = 2; len <= n; len++) for (int offs = 0; offs+len <= n; offs++) ispal[len][offs] = ispal[len-2][offs+1] && text[offs] == text[offs+len-1]; long long ret = 0; for (int len = 1; len <= n; len++) for (int offs = 0; offs+len <= n; offs++) ret += ispal[len][offs] ? len : 0; return ret; } }; //----------------------------------------------------------------------------- void dotest(string a, string e="?", string id="") { char *P=strdup(a.c_str()), *p=P; int q;q=0; while (*p == '[') p++; vector<string> x0; while(*p && *p++!='{'); while(*p && *p!='}') { string t=""; if(*p!='\"'&&*p!='}'){p++;continue;} p++; while(*p && *p!='\"') {if(*p=='\\') {t+=p[1];p+=2;} else {t+=p[0];p++;}} p++; x0.push_back(t); } while(*p && *p++!='}'); long long z = PalindromesAnalyzer().summaryLength(x0); ostringstream os; os << z; if(os.str() == e) { if (id != "") printf("TEST %s: ", id.c_str()); printf("\033[01;32mOK\033[0m got %s\n", os.str().c_str()); } else { printf("\n"); if (id != "") printf("TEST %s:\n", id.c_str()); printf("Got: %s\n", os.str().c_str()); printf("\033[01;31mExp\033[0m: %s\n\n", e.c_str()); } free(P); } void doex(int t=-1) { if(t<0||t==0) dotest("{\"AAA\"}", "10", "0"); if(t<0||t==1) dotest("{\"AB\"}", "2", "1"); if(t<0||t==2) dotest("{\"AB\", \"BA\"}", "10", "2"); if(t<0||t==3) dotest("{\"AB\", \"AAA\"}", "15", "3"); if(t<0||t==4) dotest("{\"AZ\", \"ZZ\", \"A\"}", "17", "4"); } int main(int argc, char *argv[]) { if (argc == 1) { doex(-1); } else if (argc >= 2 && strcmp(argv[1], "-") == 0) { if (argc == 2) { string s=""; char buf[65536]; while(gets(buf))s+=string(buf); dotest(s,"?"); } else { string s=""; for(int i=2; i<argc; i++) s+=string(argv[i])+" "; printf("Args: %s\n", s.c_str()); dotest(s,"?"); } } else { for (int i=1; i<argc; i++) doex(atoi(argv[i])); } }
{ "language": "C++" }
module openconfig-packet-match-types { yang-version "1"; // namespace namespace "http://openconfig.net/yang/packet-match-types"; prefix "oc-pkt-match-types"; // import some basic types import openconfig-inet-types { prefix oc-inet; } import openconfig-extensions { prefix oc-ext; } // meta organization "OpenConfig working group"; contact "OpenConfig working group www.openconfig.net"; description "This module defines common types for use in models requiring data definitions related to packet matches."; oc-ext:openconfig-version "1.0.3"; revision "2020-06-30" { description "Add OpenConfig POSIX pattern extensions."; reference "1.0.3"; } revision "2018-11-21" { description "Add OpenConfig module metadata extensions."; reference "1.0.2"; } revision "2018-04-15" { description "Corrected description and range for ethertype typedef"; reference "1.0.1"; } revision "2017-05-26" { description "Separated IP matches into AFs"; reference "1.0.0"; } revision "2016-08-08" { description "OpenConfig public release"; reference "0.2.0"; } revision "2016-04-27" { description "Initial revision"; reference "TBD"; } // OpenConfig specific extensions for module metadata. oc-ext:regexp-posix; oc-ext:catalog-organization "openconfig"; oc-ext:origin "openconfig"; // extension statements // feature statements // identity statements //TODO: should replace this with an official IEEE module // when available. Only a select number of types are // defined in this identity. identity ETHERTYPE { description "Base identity for commonly used Ethertype values used in packet header matches on Ethernet frames. The Ethertype indicates which protocol is encapsulated in the Ethernet payload."; reference "IEEE 802.3"; } identity ETHERTYPE_IPV4 { base ETHERTYPE; description "IPv4 protocol (0x0800)"; } identity ETHERTYPE_ARP { base ETHERTYPE; description "Address resolution protocol (0x0806)"; } identity ETHERTYPE_VLAN { base ETHERTYPE; description "VLAN-tagged frame (as defined by IEEE 802.1q) (0x8100). Note that this value is also used to represent Shortest Path Bridging (IEEE 801.1aq) frames."; } identity ETHERTYPE_IPV6 { base ETHERTYPE; description "IPv6 protocol (0x86DD)"; } identity ETHERTYPE_MPLS { base ETHERTYPE; description "MPLS unicast (0x8847)"; } identity ETHERTYPE_LLDP { base ETHERTYPE; description "Link Layer Discovery Protocol (0x88CC)"; } identity ETHERTYPE_ROCE { base ETHERTYPE; description "RDMA over Converged Ethernet (0x8915)"; } //TODO: should replace this with an official IANA module when //available. Only a select set of protocols are defined with //this identity. identity IP_PROTOCOL { description "Base identity for commonly used IP protocols used in packet header matches"; reference "IANA Assigned Internet Protocol Numbers"; } identity IP_TCP { base IP_PROTOCOL; description "Transmission Control Protocol (6)"; } identity IP_UDP { base IP_PROTOCOL; description "User Datagram Protocol (17)"; } identity IP_ICMP { base IP_PROTOCOL; description "Internet Control Message Protocol (1)"; } identity IP_IGMP { base IP_PROTOCOL; description "Internet Group Membership Protocol (2)"; } identity IP_PIM { base IP_PROTOCOL; description "Protocol Independent Multicast (103)"; } identity IP_RSVP { base IP_PROTOCOL; description "Resource Reservation Protocol (46)"; } identity IP_GRE { base IP_PROTOCOL; description "Generic Routing Encapsulation (47)"; } identity IP_AUTH { base IP_PROTOCOL; description "Authentication header, e.g., for IPSEC (51)"; } identity IP_L2TP { base IP_PROTOCOL; description "Layer Two Tunneling Protocol v.3 (115)"; } identity TCP_FLAGS { description "Common TCP flags used in packet header matches"; reference "IETF RFC 793 - Transmission Control Protocol IETF RFC 3168 - The Addition of Explicit Congestion Notification (ECN) to IP"; } identity TCP_SYN { base TCP_FLAGS; description "TCP SYN flag"; } identity TCP_FIN { base TCP_FLAGS; description "TCP FIN flag"; } identity TCP_RST { base TCP_FLAGS; description "TCP RST flag"; } identity TCP_PSH { base TCP_FLAGS; description "TCP push flag"; } identity TCP_ACK { base TCP_FLAGS; description "TCP ACK flag"; } identity TCP_URG { base TCP_FLAGS; description "TCP urgent flag"; } identity TCP_ECE { base TCP_FLAGS; description "TCP ECN-Echo flag. If the SYN flag is set, indicates that the TCP peer is ECN-capable, otherwise indicates that a packet with Congestion Experienced flag in the IP header is set"; } identity TCP_CWR { base TCP_FLAGS; description "TCP Congestion Window Reduced flag"; } // typedef statements typedef port-num-range { type union { type string { pattern '^(6[0-5][0-5][0-3][0-5]|[0-5]?[0-9]?[0-9]?[0-9]?' + '[0-9]?)\.\.(6[0-5][0-5][0-3][0-5]|[0-5]?[0-9]?[0-9]?' + '[0-9]?[0-9]?)$'; oc-ext:posix-pattern '^(6[0-5][0-5][0-3][0-5]|[0-5]?[0-9]?[0-9]?[0-9]?' + '[0-9]?)\.\.(6[0-5][0-5][0-3][0-5]|[0-5]?[0-9]?[0-9]?' + '[0-9]?[0-9]?)$'; } type oc-inet:port-number; type enumeration { enum ANY { description "Indicates any valid port number (e.g., wildcard)"; } } } description "Port numbers may be represented as a single value, an inclusive range as <lower>..<higher>, or as ANY to indicate a wildcard."; } typedef ip-protocol-type { type union { type uint8 { range 0..254; } type identityref { base IP_PROTOCOL; } } description "The IP protocol number may be expressed as a valid protocol number (integer) or using a protocol type defined by the IP_PROTOCOL identity"; } typedef ethertype-type { type union { type uint16 { range 1536..65535; } type identityref { base ETHERTYPE; } } description "The Ethertype value may be expressed as a 16-bit number in decimal notation, or using a type defined by the ETHERTYPE identity"; } }
{ "language": "C++" }
/** * Copyright (C) 2008 Doug Judd (Zvents, Inc.) * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * * Hypertable 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 "Common/Compat.h" #include <cstdlib> #include <cstdio> #include <climits> #include <iostream> #include <fstream> #include <boost/progress.hpp> #include <boost/timer.hpp> #include <boost/thread/xtime.hpp> #include "Common/Init.h" #include "Common/Checksum.h" #include "Common/Error.h" #include "Common/FileUtils.h" #include "Common/Random.h" #include "Common/Stopwatch.h" #include "Common/String.h" #include "Common/Usage.h" #include "AsyncComm/Config.h" #include "Hypertable/Lib/Client.h" #include "Hypertable/Lib/KeySpec.h" using namespace Hypertable; using namespace Hypertable::Config; using namespace std; namespace { const char *usage = "Usage: random_read_test [options] <total-bytes>\n\n" "Description:\n" " This program is meant to be used in conjunction with random_write_test.\n" " It will generate and lookup the same sequence of keys as random_write_test\n" " as long as the <total-bytes> value is the same. It expects to find exactly\n" " one entry for each key. If it encounters a key that comes up empty or returns\n" " more than one entry, it prints an error message and exit with a return status\n" " of 1, otherwise it displays timing statistics and exits with status 0.\n\n" "Options"; struct AppPolicy : Config::Policy { static void init_options() { cmdline_desc(usage).add_options() ("blocksize", i32()->default_value(1000), "Size of value to write") ("checksum-file", str(), "File to contain, for each insert, " "key '\t' <value-checksum> pairs") ("seed", i32()->default_value(1234), "Random number generator seed") ("max-keys", i32()->default_value(0), "Maximum number of keys to lookup") ; cmdline_hidden_desc().add_options()("total-bytes", i64(), ""); cmdline_positional_desc().add("total-bytes", -1); } }; } typedef Meta::list<AppPolicy, DefaultCommPolicy> Policies; int main(int argc, char **argv) { ClientPtr hypertable_client_ptr; TablePtr table_ptr; ScanSpecBuilder scan_spec; TableScannerPtr scanner_ptr; Cell cell; size_t blocksize; uint64_t total = 0; unsigned long seed; String config_file; bool write_checksums = false; uint32_t checksum; ofstream checksum_out; uint32_t max_keys; size_t R; try { init_with_policies<Policies>(argc, argv); if (has("checksum-file")) { checksum_out.open(get_str("checksum-file").c_str()); write_checksums = true; } blocksize = get_i32("blocksize"); seed = get_i32("seed"); total = get_i64("total-bytes"); max_keys = get_i32("max-keys"); Random::seed(seed); R = total / blocksize; if (max_keys != 0 && max_keys < R) R = max_keys; if (config_file != "") hypertable_client_ptr = new Hypertable::Client( System::locate_install_dir(argv[0]), config_file); else hypertable_client_ptr = new Hypertable::Client( System::locate_install_dir(argv[0])); table_ptr = hypertable_client_ptr->open_table("RandomTest"); } catch (Hypertable::Exception &e) { cerr << "error: " << Error::get_text(e.code()) << " - " << e.what() << endl; _exit(1); } char key_data[32]; key_data[12] = '\0'; // Row key: a random 12-digit number. Stopwatch stopwatch; { boost::progress_display progress_meter(R); try { for (size_t i = 0; i < R; ++i) { Random::fill_buffer_with_random_ascii(key_data, 12); scan_spec.clear(); scan_spec.add_column("Field"); scan_spec.add_row(key_data); TableScanner *scanner_ptr=table_ptr->create_scanner(scan_spec.get()); int n = 0; while (scanner_ptr->next(cell)) { if (write_checksums) { checksum = fletcher32(cell.value, cell.value_len); checksum_out << key_data << "\t" << checksum << "\n"; } ++n; } if (n != 1) { printf("Wrong number of results: %d (key=%s, i=%d)\n", n, key_data, (int)i); HT_ERROR_OUT << "Wrong number of results: " << n << " (key=" << key_data << ", i=" << i << ")" << HT_END; _exit(1); } delete scanner_ptr; progress_meter += 1; } } catch (Hypertable::Exception &e) { HT_ERROR_OUT << e << HT_END; _exit(1); } } stopwatch.stop(); if (write_checksums) checksum_out.close(); double total_read = (double)total + (double)(R*12); printf(" Elapsed time: %.2f s\n", stopwatch.elapsed()); printf(" Total scanned: %llu\n", (Llu)R); printf(" Throughput: %.2f bytes/s\n", total_read / stopwatch.elapsed()); printf(" Throughput: %.2f scanned cells/s\n", (double)R / stopwatch.elapsed()); fflush(stdout); _exit(0); // don't bother with static objects. }
{ "language": "C++" }
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/medialive/MediaLive_EXPORTS.h> #include <aws/medialive/model/AutomaticInputFailoverSettings.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/medialive/model/InputSettings.h> #include <utility> namespace Aws { namespace Utils { namespace Json { class JsonValue; class JsonView; } // namespace Json } // namespace Utils namespace MediaLive { namespace Model { /** * Placeholder documentation for InputAttachment<p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/medialive-2017-10-14/InputAttachment">AWS * API Reference</a></p> */ class AWS_MEDIALIVE_API InputAttachment { public: InputAttachment(); InputAttachment(Aws::Utils::Json::JsonView jsonValue); InputAttachment& operator=(Aws::Utils::Json::JsonView jsonValue); Aws::Utils::Json::JsonValue Jsonize() const; /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline const AutomaticInputFailoverSettings& GetAutomaticInputFailoverSettings() const{ return m_automaticInputFailoverSettings; } /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline bool AutomaticInputFailoverSettingsHasBeenSet() const { return m_automaticInputFailoverSettingsHasBeenSet; } /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline void SetAutomaticInputFailoverSettings(const AutomaticInputFailoverSettings& value) { m_automaticInputFailoverSettingsHasBeenSet = true; m_automaticInputFailoverSettings = value; } /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline void SetAutomaticInputFailoverSettings(AutomaticInputFailoverSettings&& value) { m_automaticInputFailoverSettingsHasBeenSet = true; m_automaticInputFailoverSettings = std::move(value); } /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline InputAttachment& WithAutomaticInputFailoverSettings(const AutomaticInputFailoverSettings& value) { SetAutomaticInputFailoverSettings(value); return *this;} /** * User-specified settings for defining what the conditions are for declaring the * input unhealthy and failing over to a different input. */ inline InputAttachment& WithAutomaticInputFailoverSettings(AutomaticInputFailoverSettings&& value) { SetAutomaticInputFailoverSettings(std::move(value)); return *this;} /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline const Aws::String& GetInputAttachmentName() const{ return m_inputAttachmentName; } /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline bool InputAttachmentNameHasBeenSet() const { return m_inputAttachmentNameHasBeenSet; } /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline void SetInputAttachmentName(const Aws::String& value) { m_inputAttachmentNameHasBeenSet = true; m_inputAttachmentName = value; } /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline void SetInputAttachmentName(Aws::String&& value) { m_inputAttachmentNameHasBeenSet = true; m_inputAttachmentName = std::move(value); } /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline void SetInputAttachmentName(const char* value) { m_inputAttachmentNameHasBeenSet = true; m_inputAttachmentName.assign(value); } /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline InputAttachment& WithInputAttachmentName(const Aws::String& value) { SetInputAttachmentName(value); return *this;} /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline InputAttachment& WithInputAttachmentName(Aws::String&& value) { SetInputAttachmentName(std::move(value)); return *this;} /** * User-specified name for the attachment. This is required if the user wants to * use this input in an input switch action. */ inline InputAttachment& WithInputAttachmentName(const char* value) { SetInputAttachmentName(value); return *this;} /** * The ID of the input */ inline const Aws::String& GetInputId() const{ return m_inputId; } /** * The ID of the input */ inline bool InputIdHasBeenSet() const { return m_inputIdHasBeenSet; } /** * The ID of the input */ inline void SetInputId(const Aws::String& value) { m_inputIdHasBeenSet = true; m_inputId = value; } /** * The ID of the input */ inline void SetInputId(Aws::String&& value) { m_inputIdHasBeenSet = true; m_inputId = std::move(value); } /** * The ID of the input */ inline void SetInputId(const char* value) { m_inputIdHasBeenSet = true; m_inputId.assign(value); } /** * The ID of the input */ inline InputAttachment& WithInputId(const Aws::String& value) { SetInputId(value); return *this;} /** * The ID of the input */ inline InputAttachment& WithInputId(Aws::String&& value) { SetInputId(std::move(value)); return *this;} /** * The ID of the input */ inline InputAttachment& WithInputId(const char* value) { SetInputId(value); return *this;} /** * Settings of an input (caption selector, etc.) */ inline const InputSettings& GetInputSettings() const{ return m_inputSettings; } /** * Settings of an input (caption selector, etc.) */ inline bool InputSettingsHasBeenSet() const { return m_inputSettingsHasBeenSet; } /** * Settings of an input (caption selector, etc.) */ inline void SetInputSettings(const InputSettings& value) { m_inputSettingsHasBeenSet = true; m_inputSettings = value; } /** * Settings of an input (caption selector, etc.) */ inline void SetInputSettings(InputSettings&& value) { m_inputSettingsHasBeenSet = true; m_inputSettings = std::move(value); } /** * Settings of an input (caption selector, etc.) */ inline InputAttachment& WithInputSettings(const InputSettings& value) { SetInputSettings(value); return *this;} /** * Settings of an input (caption selector, etc.) */ inline InputAttachment& WithInputSettings(InputSettings&& value) { SetInputSettings(std::move(value)); return *this;} private: AutomaticInputFailoverSettings m_automaticInputFailoverSettings; bool m_automaticInputFailoverSettingsHasBeenSet; Aws::String m_inputAttachmentName; bool m_inputAttachmentNameHasBeenSet; Aws::String m_inputId; bool m_inputIdHasBeenSet; InputSettings m_inputSettings; bool m_inputSettingsHasBeenSet; }; } // namespace Model } // namespace MediaLive } // namespace Aws
{ "language": "C++" }
/* <!-- copyright */ /* * aria2 - The high speed download utility * * Copyright (C) 2009 Tatsuhiro Tsujikawa * * 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 * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ /* copyright --> */ #include "EpollEventPoll.h" #include <cerrno> #include <cstring> #include <algorithm> #include <numeric> #include "Command.h" #include "LogFactory.h" #include "Logger.h" #include "util.h" #include "a2functional.h" #include "fmt.h" namespace aria2 { EpollEventPoll::KSocketEntry::KSocketEntry(sock_t s) : SocketEntry<KCommandEvent, KADNSEvent>(s) { } int accumulateEvent(int events, const EpollEventPoll::KEvent& event) { return events | event.getEvents(); } struct epoll_event EpollEventPoll::KSocketEntry::getEvents() { struct epoll_event epEvent; memset(&epEvent, 0, sizeof(struct epoll_event)); epEvent.data.ptr = this; #ifdef ENABLE_ASYNC_DNS epEvent.events = std::accumulate(adnsEvents_.begin(), adnsEvents_.end(), std::accumulate(commandEvents_.begin(), commandEvents_.end(), 0, accumulateEvent), accumulateEvent); #else // !ENABLE_ASYNC_DNS epEvent.events = std::accumulate(commandEvents_.begin(), commandEvents_.end(), 0, accumulateEvent); #endif // !ENABLE_ASYNC_DNS return epEvent; } EpollEventPoll::EpollEventPoll() : epEventsSize_(EPOLL_EVENTS_MAX), epEvents_(make_unique<struct epoll_event[]>(epEventsSize_)) { epfd_ = epoll_create(EPOLL_EVENTS_MAX); } EpollEventPoll::~EpollEventPoll() { if (epfd_ != -1) { int r = close(epfd_); int errNum = errno; if (r == -1) { A2_LOG_ERROR(fmt("Error occurred while closing epoll file descriptor" " %d: %s", epfd_, util::safeStrerror(errNum).c_str())); } } } bool EpollEventPoll::good() const { return epfd_ != -1; } void EpollEventPoll::poll(const struct timeval& tv) { // timeout is millisec int timeout = tv.tv_sec * 1000 + tv.tv_usec / 1000; int res; while ((res = epoll_wait(epfd_, epEvents_.get(), EPOLL_EVENTS_MAX, timeout)) == -1 && errno == EINTR) ; if (res > 0) { for (int i = 0; i < res; ++i) { KSocketEntry* p = reinterpret_cast<KSocketEntry*>(epEvents_[i].data.ptr); p->processEvents(epEvents_[i].events); } } else if (res == -1) { int errNum = errno; A2_LOG_INFO( fmt("epoll_wait error: %s", util::safeStrerror(errNum).c_str())); } #ifdef ENABLE_ASYNC_DNS // It turns out that we have to call ares_process_fd before ares's // own timeout and ares may create new sockets or closes socket in // their API. So we call ares_process_fd for all ares_channel and // re-register their sockets. for (auto& i : nameResolverEntries_) { auto& ent = i.second; ent.processTimeout(); ent.removeSocketEvents(this); ent.addSocketEvents(this); } #endif // ENABLE_ASYNC_DNS // TODO timeout of name resolver is determined in Command(AbstractCommand, // DHTEntryPoint...Command) } namespace { int translateEvents(EventPoll::EventType events) { int newEvents = 0; if (EventPoll::EVENT_READ & events) { newEvents |= EPOLLIN; } if (EventPoll::EVENT_WRITE & events) { newEvents |= EPOLLOUT; } if (EventPoll::EVENT_ERROR & events) { newEvents |= EPOLLERR; } if (EventPoll::EVENT_HUP & events) { newEvents |= EPOLLHUP; } return newEvents; } } // namespace bool EpollEventPoll::addEvents(sock_t socket, const EpollEventPoll::KEvent& event) { auto i = socketEntries_.lower_bound(socket); int r = 0; int errNum = 0; if (i != std::end(socketEntries_) && (*i).first == socket) { auto& socketEntry = (*i).second; event.addSelf(&socketEntry); struct epoll_event epEvent = socketEntry.getEvents(); r = epoll_ctl(epfd_, EPOLL_CTL_MOD, socketEntry.getSocket(), &epEvent); if (r == -1) { // try EPOLL_CTL_ADD: There is a chance that previously socket X is // added to epoll, but it is closed and is not yet removed from // SocketEntries. In this case, EPOLL_CTL_MOD is failed with ENOENT. r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry.getSocket(), &epEvent); errNum = errno; } } else { i = socketEntries_.insert(i, std::make_pair(socket, KSocketEntry(socket))); auto& socketEntry = (*i).second; if (socketEntries_.size() > epEventsSize_) { epEventsSize_ *= 2; epEvents_ = make_unique<struct epoll_event[]>(epEventsSize_); } event.addSelf(&socketEntry); struct epoll_event epEvent = socketEntry.getEvents(); r = epoll_ctl(epfd_, EPOLL_CTL_ADD, socketEntry.getSocket(), &epEvent); errNum = errno; } if (r == -1) { A2_LOG_DEBUG(fmt("Failed to add socket event %d:%s", socket, util::safeStrerror(errNum).c_str())); return false; } else { return true; } } bool EpollEventPoll::addEvents(sock_t socket, Command* command, EventPoll::EventType events) { int epEvents = translateEvents(events); return addEvents(socket, KCommandEvent(command, epEvents)); } #ifdef ENABLE_ASYNC_DNS bool EpollEventPoll::addEvents(sock_t socket, Command* command, int events, const std::shared_ptr<AsyncNameResolver>& rs) { return addEvents(socket, KADNSEvent(rs, command, socket, events)); } #endif // ENABLE_ASYNC_DNS bool EpollEventPoll::deleteEvents(sock_t socket, const EpollEventPoll::KEvent& event) { auto i = socketEntries_.find(socket); if (i == std::end(socketEntries_)) { A2_LOG_DEBUG(fmt("Socket %d is not found in SocketEntries.", socket)); return false; } auto& socketEntry = (*i).second; event.removeSelf(&socketEntry); int r = 0; int errNum = 0; if (socketEntry.eventEmpty()) { // In kernel before 2.6.9, epoll_ctl with EPOLL_CTL_DEL requires non-null // pointer of epoll_event. struct epoll_event ev = {0, {0}}; r = epoll_ctl(epfd_, EPOLL_CTL_DEL, socketEntry.getSocket(), &ev); errNum = errno; socketEntries_.erase(i); } else { // If socket is closed, then it seems it is automatically removed from // epoll, so following EPOLL_CTL_MOD may fail. struct epoll_event epEvent = socketEntry.getEvents(); r = epoll_ctl(epfd_, EPOLL_CTL_MOD, socketEntry.getSocket(), &epEvent); errNum = errno; if (r == -1) { A2_LOG_DEBUG(fmt("Failed to delete socket event, but may be ignored:%s", util::safeStrerror(errNum).c_str())); } } if (r == -1) { A2_LOG_DEBUG(fmt("Failed to delete socket event:%s", util::safeStrerror(errNum).c_str())); return false; } else { return true; } } #ifdef ENABLE_ASYNC_DNS bool EpollEventPoll::deleteEvents(sock_t socket, Command* command, const std::shared_ptr<AsyncNameResolver>& rs) { return deleteEvents(socket, KADNSEvent(rs, command, socket, 0)); } #endif // ENABLE_ASYNC_DNS bool EpollEventPoll::deleteEvents(sock_t socket, Command* command, EventPoll::EventType events) { int epEvents = translateEvents(events); return deleteEvents(socket, KCommandEvent(command, epEvents)); } #ifdef ENABLE_ASYNC_DNS bool EpollEventPoll::addNameResolver( const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) { auto key = std::make_pair(resolver.get(), command); auto itr = nameResolverEntries_.lower_bound(key); if (itr != std::end(nameResolverEntries_) && (*itr).first == key) { return false; } itr = nameResolverEntries_.insert( itr, std::make_pair(key, KAsyncNameResolverEntry(resolver, command))); (*itr).second.addSocketEvents(this); return true; } bool EpollEventPoll::deleteNameResolver( const std::shared_ptr<AsyncNameResolver>& resolver, Command* command) { auto key = std::make_pair(resolver.get(), command); auto itr = nameResolverEntries_.find(key); if (itr == std::end(nameResolverEntries_)) { return false; } (*itr).second.removeSocketEvents(this); nameResolverEntries_.erase(itr); return true; } #endif // ENABLE_ASYNC_DNS } // namespace aria2
{ "language": "C++" }
// (C) Copyright 2009-2011 Frederic Bron. // // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_HAS_GREATER_EQUAL_HPP_INCLUDED #define BOOST_TT_HAS_GREATER_EQUAL_HPP_INCLUDED #define BOOST_TT_TRAIT_NAME has_greater_equal #define BOOST_TT_TRAIT_OP >= #define BOOST_TT_FORBIDDEN_IF\ (\ /* Lhs==pointer and Rhs==fundamental */\ (\ ::boost::is_pointer< Lhs_noref >::value && \ ::boost::is_fundamental< Rhs_nocv >::value\ ) || \ /* Rhs==pointer and Lhs==fundamental */\ (\ ::boost::is_pointer< Rhs_noref >::value && \ ::boost::is_fundamental< Lhs_nocv >::value\ ) || \ /* Lhs==pointer and Rhs==pointer and Lhs!=base(Rhs) and Rhs!=base(Lhs) and Lhs!=void* and Rhs!=void* */\ (\ ::boost::is_pointer< Lhs_noref >::value && \ ::boost::is_pointer< Rhs_noref >::value && \ (! \ ( \ ::boost::is_base_of< Lhs_noptr, Rhs_noptr >::value || \ ::boost::is_base_of< Rhs_noptr, Lhs_noptr >::value || \ ::boost::is_same< Lhs_noptr, Rhs_noptr >::value || \ ::boost::is_void< Lhs_noptr >::value || \ ::boost::is_void< Rhs_noptr >::value\ )\ )\ )\ ) #include <boost/type_traits/detail/has_binary_operator.hpp> #undef BOOST_TT_TRAIT_NAME #undef BOOST_TT_TRAIT_OP #undef BOOST_TT_FORBIDDEN_IF #endif
{ "language": "C++" }
/* -------------------------------------------------------------------------- * * OpenMM * * -------------------------------------------------------------------------- * * This is part of the OpenMM molecular simulation toolkit originating from * * Simbios, the NIH National Center for Physics-Based Simulation of * * Biological Structures at Stanford, funded under the NIH Roadmap for * * Medical Research, grant U54 GM072970. See https://simtk.org. * * * * Portions copyright (c) 2008 Stanford University and the Authors. * * Authors: Peter Eastman * * Contributors: * * * * 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, CONTRIBUTORS 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 "openmm/AndersenThermostat.h" #include "openmm/internal/AndersenThermostatImpl.h" #include "openmm/internal/OSRngSeed.h" using namespace OpenMM; AndersenThermostat::AndersenThermostat(double defaultTemperature, double defaultCollisionFrequency) : defaultTemp(defaultTemperature), defaultFreq(defaultCollisionFrequency) { setRandomNumberSeed(0); } ForceImpl* AndersenThermostat::createImpl() const { return new AndersenThermostatImpl(*this); }
{ "language": "C++" }
/* * Copyright (C) 2014 The Android Open Source Project * * 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 <androidfw/ResourceTypes.h> #include <ctype.h> #include "AaptConfig.h" #include "AaptAssets.h" #include "AaptUtil.h" #include "ResourceFilter.h" #include "SdkConstants.h" using android::String8; using android::Vector; using android::ResTable_config; namespace AaptConfig { static const char* kWildcardName = "any"; bool parse(const String8& str, ConfigDescription* out) { Vector<String8> parts = AaptUtil::splitAndLowerCase(str, '-'); ConfigDescription config; AaptLocaleValue locale; ssize_t index = 0; ssize_t localeIndex = 0; const ssize_t N = parts.size(); const char* part = parts[index].string(); if (str.length() == 0) { goto success; } if (parseMcc(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseMnc(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } // Locale spans a few '-' separators, so we let it // control the index. localeIndex = locale.initFromDirName(parts, index); if (localeIndex < 0) { return false; } else if (localeIndex > index) { locale.writeTo(&config); index = localeIndex; if (index >= N) { goto success; } part = parts[index].string(); } if (parseLayoutDirection(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseSmallestScreenWidthDp(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenWidthDp(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenHeightDp(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenLayoutSize(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenLayoutLong(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenRound(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseWideColorGamut(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseHdr(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseOrientation(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseUiModeType(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseUiModeNight(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseDensity(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseTouchscreen(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseKeysHidden(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseKeyboard(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseNavHidden(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseNavigation(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseScreenSize(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } if (parseVersion(part, &config)) { index++; if (index == N) { goto success; } part = parts[index].string(); } // Unrecognized. return false; success: if (out != NULL) { applyVersionForCompatibility(&config); *out = config; } return true; } bool parseCommaSeparatedList(const String8& str, std::set<ConfigDescription>* outSet) { Vector<String8> parts = AaptUtil::splitAndLowerCase(str, ','); const size_t N = parts.size(); for (size_t i = 0; i < N; i++) { ConfigDescription config; if (!parse(parts[i], &config)) { return false; } outSet->insert(config); } return true; } void applyVersionForCompatibility(ConfigDescription* config) { if (config == NULL) { return; } uint16_t minSdk = 0; if ((config->uiMode & ResTable_config::MASK_UI_MODE_TYPE) == ResTable_config::UI_MODE_TYPE_VR_HEADSET || config->colorMode & ResTable_config::MASK_WIDE_COLOR_GAMUT || config->colorMode & ResTable_config::MASK_HDR) { minSdk = SDK_O; } else if (config->screenLayout2 & ResTable_config::MASK_SCREENROUND) { minSdk = SDK_MNC; } else if (config->density == ResTable_config::DENSITY_ANY) { minSdk = SDK_LOLLIPOP; } else if (config->smallestScreenWidthDp != ResTable_config::SCREENWIDTH_ANY || config->screenWidthDp != ResTable_config::SCREENWIDTH_ANY || config->screenHeightDp != ResTable_config::SCREENHEIGHT_ANY) { minSdk = SDK_HONEYCOMB_MR2; } else if ((config->uiMode & ResTable_config::MASK_UI_MODE_TYPE) != ResTable_config::UI_MODE_TYPE_ANY || (config->uiMode & ResTable_config::MASK_UI_MODE_NIGHT) != ResTable_config::UI_MODE_NIGHT_ANY) { minSdk = SDK_FROYO; } else if ((config->screenLayout & ResTable_config::MASK_SCREENSIZE) != ResTable_config::SCREENSIZE_ANY || (config->screenLayout & ResTable_config::MASK_SCREENLONG) != ResTable_config::SCREENLONG_ANY || config->density != ResTable_config::DENSITY_DEFAULT) { minSdk = SDK_DONUT; } if (minSdk > config->sdkVersion) { config->sdkVersion = minSdk; } } bool parseMcc(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->mcc = 0; return true; } const char* c = name; if (tolower(*c) != 'm') return false; c++; if (tolower(*c) != 'c') return false; c++; if (tolower(*c) != 'c') return false; c++; const char* val = c; while (*c >= '0' && *c <= '9') { c++; } if (*c != 0) return false; if (c-val != 3) return false; int d = atoi(val); if (d != 0) { if (out) out->mcc = d; return true; } return false; } bool parseMnc(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->mcc = 0; return true; } const char* c = name; if (tolower(*c) != 'm') return false; c++; if (tolower(*c) != 'n') return false; c++; if (tolower(*c) != 'c') return false; c++; const char* val = c; while (*c >= '0' && *c <= '9') { c++; } if (*c != 0) return false; if (c-val == 0 || c-val > 3) return false; if (out) { out->mnc = atoi(val); if (out->mnc == 0) { out->mnc = ACONFIGURATION_MNC_ZERO; } } return true; } bool parseLayoutDirection(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_LAYOUTDIR) | ResTable_config::LAYOUTDIR_ANY; return true; } else if (strcmp(name, "ldltr") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_LAYOUTDIR) | ResTable_config::LAYOUTDIR_LTR; return true; } else if (strcmp(name, "ldrtl") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_LAYOUTDIR) | ResTable_config::LAYOUTDIR_RTL; return true; } return false; } bool parseScreenLayoutSize(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENSIZE) | ResTable_config::SCREENSIZE_ANY; return true; } else if (strcmp(name, "small") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENSIZE) | ResTable_config::SCREENSIZE_SMALL; return true; } else if (strcmp(name, "normal") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENSIZE) | ResTable_config::SCREENSIZE_NORMAL; return true; } else if (strcmp(name, "large") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENSIZE) | ResTable_config::SCREENSIZE_LARGE; return true; } else if (strcmp(name, "xlarge") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENSIZE) | ResTable_config::SCREENSIZE_XLARGE; return true; } return false; } bool parseScreenLayoutLong(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENLONG) | ResTable_config::SCREENLONG_ANY; return true; } else if (strcmp(name, "long") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENLONG) | ResTable_config::SCREENLONG_YES; return true; } else if (strcmp(name, "notlong") == 0) { if (out) out->screenLayout = (out->screenLayout&~ResTable_config::MASK_SCREENLONG) | ResTable_config::SCREENLONG_NO; return true; } return false; } bool parseScreenRound(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->screenLayout2 = (out->screenLayout2&~ResTable_config::MASK_SCREENROUND) | ResTable_config::SCREENROUND_ANY; return true; } else if (strcmp(name, "round") == 0) { if (out) out->screenLayout2 = (out->screenLayout2&~ResTable_config::MASK_SCREENROUND) | ResTable_config::SCREENROUND_YES; return true; } else if (strcmp(name, "notround") == 0) { if (out) out->screenLayout2 = (out->screenLayout2&~ResTable_config::MASK_SCREENROUND) | ResTable_config::SCREENROUND_NO; return true; } return false; } bool parseWideColorGamut(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_WIDE_COLOR_GAMUT) | ResTable_config::WIDE_COLOR_GAMUT_ANY; return true; } else if (strcmp(name, "widecg") == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_WIDE_COLOR_GAMUT) | ResTable_config::WIDE_COLOR_GAMUT_YES; return true; } else if (strcmp(name, "nowidecg") == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_WIDE_COLOR_GAMUT) | ResTable_config::WIDE_COLOR_GAMUT_NO; return true; } return false; } bool parseHdr(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_HDR) | ResTable_config::HDR_ANY; return true; } else if (strcmp(name, "highdr") == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_HDR) | ResTable_config::HDR_YES; return true; } else if (strcmp(name, "lowdr") == 0) { if (out) out->colorMode = (out->colorMode&~ResTable_config::MASK_HDR) | ResTable_config::HDR_NO; return true; } return false; } bool parseOrientation(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->orientation = out->ORIENTATION_ANY; return true; } else if (strcmp(name, "port") == 0) { if (out) out->orientation = out->ORIENTATION_PORT; return true; } else if (strcmp(name, "land") == 0) { if (out) out->orientation = out->ORIENTATION_LAND; return true; } else if (strcmp(name, "square") == 0) { if (out) out->orientation = out->ORIENTATION_SQUARE; return true; } return false; } bool parseUiModeType(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_ANY; return true; } else if (strcmp(name, "desk") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_DESK; return true; } else if (strcmp(name, "car") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_CAR; return true; } else if (strcmp(name, "television") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_TELEVISION; return true; } else if (strcmp(name, "appliance") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_APPLIANCE; return true; } else if (strcmp(name, "watch") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_WATCH; return true; } else if (strcmp(name, "vrheadset") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_TYPE) | ResTable_config::UI_MODE_TYPE_VR_HEADSET; return true; } return false; } bool parseUiModeNight(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_NIGHT) | ResTable_config::UI_MODE_NIGHT_ANY; return true; } else if (strcmp(name, "night") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_NIGHT) | ResTable_config::UI_MODE_NIGHT_YES; return true; } else if (strcmp(name, "notnight") == 0) { if (out) out->uiMode = (out->uiMode&~ResTable_config::MASK_UI_MODE_NIGHT) | ResTable_config::UI_MODE_NIGHT_NO; return true; } return false; } bool parseDensity(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->density = ResTable_config::DENSITY_DEFAULT; return true; } if (strcmp(name, "anydpi") == 0) { if (out) out->density = ResTable_config::DENSITY_ANY; return true; } if (strcmp(name, "nodpi") == 0) { if (out) out->density = ResTable_config::DENSITY_NONE; return true; } if (strcmp(name, "ldpi") == 0) { if (out) out->density = ResTable_config::DENSITY_LOW; return true; } if (strcmp(name, "mdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_MEDIUM; return true; } if (strcmp(name, "tvdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_TV; return true; } if (strcmp(name, "hdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_HIGH; return true; } if (strcmp(name, "xhdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_XHIGH; return true; } if (strcmp(name, "xxhdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_XXHIGH; return true; } if (strcmp(name, "xxxhdpi") == 0) { if (out) out->density = ResTable_config::DENSITY_XXXHIGH; return true; } char* c = (char*)name; while (*c >= '0' && *c <= '9') { c++; } // check that we have 'dpi' after the last digit. if (toupper(c[0]) != 'D' || toupper(c[1]) != 'P' || toupper(c[2]) != 'I' || c[3] != 0) { return false; } // temporarily replace the first letter with \0 to // use atoi. char tmp = c[0]; c[0] = '\0'; int d = atoi(name); c[0] = tmp; if (d != 0) { if (out) out->density = d; return true; } return false; } bool parseTouchscreen(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->touchscreen = out->TOUCHSCREEN_ANY; return true; } else if (strcmp(name, "notouch") == 0) { if (out) out->touchscreen = out->TOUCHSCREEN_NOTOUCH; return true; } else if (strcmp(name, "stylus") == 0) { if (out) out->touchscreen = out->TOUCHSCREEN_STYLUS; return true; } else if (strcmp(name, "finger") == 0) { if (out) out->touchscreen = out->TOUCHSCREEN_FINGER; return true; } return false; } bool parseKeysHidden(const char* name, ResTable_config* out) { uint8_t mask = 0; uint8_t value = 0; if (strcmp(name, kWildcardName) == 0) { mask = ResTable_config::MASK_KEYSHIDDEN; value = ResTable_config::KEYSHIDDEN_ANY; } else if (strcmp(name, "keysexposed") == 0) { mask = ResTable_config::MASK_KEYSHIDDEN; value = ResTable_config::KEYSHIDDEN_NO; } else if (strcmp(name, "keyshidden") == 0) { mask = ResTable_config::MASK_KEYSHIDDEN; value = ResTable_config::KEYSHIDDEN_YES; } else if (strcmp(name, "keyssoft") == 0) { mask = ResTable_config::MASK_KEYSHIDDEN; value = ResTable_config::KEYSHIDDEN_SOFT; } if (mask != 0) { if (out) out->inputFlags = (out->inputFlags&~mask) | value; return true; } return false; } bool parseKeyboard(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->keyboard = out->KEYBOARD_ANY; return true; } else if (strcmp(name, "nokeys") == 0) { if (out) out->keyboard = out->KEYBOARD_NOKEYS; return true; } else if (strcmp(name, "qwerty") == 0) { if (out) out->keyboard = out->KEYBOARD_QWERTY; return true; } else if (strcmp(name, "12key") == 0) { if (out) out->keyboard = out->KEYBOARD_12KEY; return true; } return false; } bool parseNavHidden(const char* name, ResTable_config* out) { uint8_t mask = 0; uint8_t value = 0; if (strcmp(name, kWildcardName) == 0) { mask = ResTable_config::MASK_NAVHIDDEN; value = ResTable_config::NAVHIDDEN_ANY; } else if (strcmp(name, "navexposed") == 0) { mask = ResTable_config::MASK_NAVHIDDEN; value = ResTable_config::NAVHIDDEN_NO; } else if (strcmp(name, "navhidden") == 0) { mask = ResTable_config::MASK_NAVHIDDEN; value = ResTable_config::NAVHIDDEN_YES; } if (mask != 0) { if (out) out->inputFlags = (out->inputFlags&~mask) | value; return true; } return false; } bool parseNavigation(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) out->navigation = out->NAVIGATION_ANY; return true; } else if (strcmp(name, "nonav") == 0) { if (out) out->navigation = out->NAVIGATION_NONAV; return true; } else if (strcmp(name, "dpad") == 0) { if (out) out->navigation = out->NAVIGATION_DPAD; return true; } else if (strcmp(name, "trackball") == 0) { if (out) out->navigation = out->NAVIGATION_TRACKBALL; return true; } else if (strcmp(name, "wheel") == 0) { if (out) out->navigation = out->NAVIGATION_WHEEL; return true; } return false; } bool parseScreenSize(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) { out->screenWidth = out->SCREENWIDTH_ANY; out->screenHeight = out->SCREENHEIGHT_ANY; } return true; } const char* x = name; while (*x >= '0' && *x <= '9') x++; if (x == name || *x != 'x') return false; String8 xName(name, x-name); x++; const char* y = x; while (*y >= '0' && *y <= '9') y++; if (y == name || *y != 0) return false; String8 yName(x, y-x); uint16_t w = (uint16_t)atoi(xName.string()); uint16_t h = (uint16_t)atoi(yName.string()); if (w < h) { return false; } if (out) { out->screenWidth = w; out->screenHeight = h; } return true; } bool parseSmallestScreenWidthDp(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) { out->smallestScreenWidthDp = out->SCREENWIDTH_ANY; } return true; } if (*name != 's') return false; name++; if (*name != 'w') return false; name++; const char* x = name; while (*x >= '0' && *x <= '9') x++; if (x == name || x[0] != 'd' || x[1] != 'p' || x[2] != 0) return false; String8 xName(name, x-name); if (out) { out->smallestScreenWidthDp = (uint16_t)atoi(xName.string()); } return true; } bool parseScreenWidthDp(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) { out->screenWidthDp = out->SCREENWIDTH_ANY; } return true; } if (*name != 'w') return false; name++; const char* x = name; while (*x >= '0' && *x <= '9') x++; if (x == name || x[0] != 'd' || x[1] != 'p' || x[2] != 0) return false; String8 xName(name, x-name); if (out) { out->screenWidthDp = (uint16_t)atoi(xName.string()); } return true; } bool parseScreenHeightDp(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) { out->screenHeightDp = out->SCREENWIDTH_ANY; } return true; } if (*name != 'h') return false; name++; const char* x = name; while (*x >= '0' && *x <= '9') x++; if (x == name || x[0] != 'd' || x[1] != 'p' || x[2] != 0) return false; String8 xName(name, x-name); if (out) { out->screenHeightDp = (uint16_t)atoi(xName.string()); } return true; } bool parseVersion(const char* name, ResTable_config* out) { if (strcmp(name, kWildcardName) == 0) { if (out) { out->sdkVersion = out->SDKVERSION_ANY; out->minorVersion = out->MINORVERSION_ANY; } return true; } if (*name != 'v') { return false; } name++; const char* s = name; while (*s >= '0' && *s <= '9') s++; if (s == name || *s != 0) return false; String8 sdkName(name, s-name); if (out) { out->sdkVersion = (uint16_t)atoi(sdkName.string()); out->minorVersion = 0; } return true; } String8 getVersion(const ResTable_config& config) { return String8::format("v%u", config.sdkVersion); } bool isSameExcept(const ResTable_config& a, const ResTable_config& b, int axisMask) { return a.diff(b) == axisMask; } bool isDensityOnly(const ResTable_config& config) { if (config.density == ResTable_config::DENSITY_DEFAULT) { return false; } if (config.density == ResTable_config::DENSITY_ANY) { if (config.sdkVersion != SDK_LOLLIPOP) { // Someone modified the sdkVersion from the default, this is not safe to assume. return false; } } else if (config.sdkVersion != SDK_DONUT) { return false; } const uint32_t mask = ResTable_config::CONFIG_DENSITY | ResTable_config::CONFIG_VERSION; const ConfigDescription nullConfig; return (nullConfig.diff(config) & ~mask) == 0; } } // namespace AaptConfig
{ "language": "C++" }
/**************************************************************************** This file is part of the GLC-lib library. Copyright (C) 2005-2008 Laurent Ribon (laumaya@users.sourceforge.net) http://glc-lib.sourceforge.net GLC-lib is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. GLC-lib 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 GLC-lib; if not, see <http://www.gnu.org/licenses/> *****************************************************************************/ //! \file glc_context.cpp implementation of the GLC_Context class. #include "glc_context.h" #include "glc_contextmanager.h" #include "shading/glc_shader.h" #include "glc_state.h" GLC_Context* GLC_Context::m_pCurrentContext= NULL; GLC_Context::GLC_Context(const QGLFormat& format) : QGLContext(format) , m_CurrentMatrixMode() , m_MatrixStackHash() , m_ContextSharedData() , m_UniformShaderData() , m_LightingIsEnable() { qDebug() << "GLC_Context::GLC_Context"; GLC_ContextManager::instance()->addContext(this); init(); } GLC_Context::~GLC_Context() { qDebug() << "GLC_Context::~GLC_Context()"; GLC_ContextManager::instance()->remove(this); QHash<GLenum, QStack<GLC_Matrix4x4>* >::iterator iStack= m_MatrixStackHash.begin(); while (iStack != m_MatrixStackHash.end()) { delete iStack.value(); ++iStack; } } ////////////////////////////////////////////////////////////////////// // Get Functions ////////////////////////////////////////////////////////////////////// GLC_Context* GLC_Context::current() { return m_pCurrentContext; } ////////////////////////////////////////////////////////////////////// // OpenGL Functions ////////////////////////////////////////////////////////////////////// void GLC_Context::glcMatrixMode(GLenum mode) { Q_ASSERT(QGLContext::isValid()); Q_ASSERT((mode == GL_MODELVIEW) || (mode == GL_PROJECTION)); m_CurrentMatrixMode= mode; #ifdef GLC_OPENGL_ES_2 #else glMatrixMode(m_CurrentMatrixMode); #endif } void GLC_Context::glcLoadIdentity() { Q_ASSERT(QGLContext::isValid()); m_MatrixStackHash.value(m_CurrentMatrixMode)->top().setToIdentity(); #ifdef GLC_OPENGL_ES_2 m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); #else if (GLC_Shader::hasActiveShader()) { m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); } glLoadIdentity(); #endif } void GLC_Context::glcPushMatrix() { Q_ASSERT(QGLContext::isValid()); m_MatrixStackHash.value(m_CurrentMatrixMode)->push(m_MatrixStackHash.value(m_CurrentMatrixMode)->top()); #ifndef GLC_OPENGL_ES_2 glPushMatrix(); #endif } void GLC_Context::glcPopMatrix() { Q_ASSERT(QGLContext::isValid()); m_MatrixStackHash.value(m_CurrentMatrixMode)->pop(); #ifdef GLC_OPENGL_ES_2 this->glcLoadMatrix(m_MatrixStackHash.value(m_CurrentMatrixMode)->top()); #else if (GLC_Shader::hasActiveShader()) { this->glcLoadMatrix(m_MatrixStackHash.value(m_CurrentMatrixMode)->top()); } glPopMatrix(); #endif } void GLC_Context::glcLoadMatrix(const GLC_Matrix4x4& matrix) { m_MatrixStackHash.value(m_CurrentMatrixMode)->top()= matrix; #ifdef GLC_OPENGL_ES_2 m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); #else if (GLC_Shader::hasActiveShader()) { m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); } ::glLoadMatrixd(matrix.getData()); #endif } void GLC_Context::glcMultMatrix(const GLC_Matrix4x4& matrix) { const GLC_Matrix4x4 current= m_MatrixStackHash.value(m_CurrentMatrixMode)->top(); m_MatrixStackHash.value(m_CurrentMatrixMode)->top()= m_MatrixStackHash.value(m_CurrentMatrixMode)->top() * matrix; #ifdef GLC_OPENGL_ES_2 m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); #else if (GLC_Shader::hasActiveShader()) { m_UniformShaderData.setModelViewProjectionMatrix(m_MatrixStackHash.value(GL_MODELVIEW)->top(), m_MatrixStackHash.value(GL_PROJECTION)->top()); } ::glMultMatrixd(matrix.getData()); #endif } void GLC_Context::glcScaled(double x, double y, double z) { GLC_Matrix4x4 scale; scale.setMatScaling(x, y, z); glcMultMatrix(scale); } void GLC_Context::glcOrtho(double left, double right, double bottom, double top, double nearVal, double farVal) { GLC_Matrix4x4 orthoMatrix; double* m= orthoMatrix.setData(); const double tx= - (right + left) / (right - left); const double ty= - (top + bottom) / (top - bottom); const double tz= - (farVal + nearVal) / (farVal - nearVal); m[0]= 2.0 / (right - left); m[5]= 2.0 / (top - bottom); m[10]= -2.0 / (farVal - nearVal); m[12]= tx; m[13]= ty; m[14]= tz; glcMultMatrix(orthoMatrix); } void GLC_Context::glcFrustum(double left, double right, double bottom, double top, double nearVal, double farVal) { GLC_Matrix4x4 perspMatrix; double* m= perspMatrix.setData(); const double a= (right + left) / (right - left); const double b= (top + bottom) / (top - bottom); const double c= - (farVal + nearVal) / (farVal - nearVal); const double d= - (2.0 * farVal * nearVal) / (farVal - nearVal); m[0]= (2.0 * nearVal) / (right - left); m[5]= (2.0 * nearVal) / (top - bottom); m[8]= a; m[9]= b; m[10]= c; m[11]= -1.0; m[14]= d; m[15]= 0.0; glcMultMatrix(perspMatrix); } void GLC_Context::glcEnableLighting(bool enable) { if (enable != m_LightingIsEnable.top()) { m_LightingIsEnable.top()= enable; #ifdef GLC_OPENGL_ES_2 m_UniformShaderData.setLightingState(m_LightingIsEnable); #else if (GLC_Shader::hasActiveShader()) { m_UniformShaderData.setLightingState(m_LightingIsEnable.top()); } if (m_LightingIsEnable.top()) ::glEnable(GL_LIGHTING); else ::glDisable(GL_LIGHTING); #endif } } ////////////////////////////////////////////////////////////////////// // Set Functions ////////////////////////////////////////////////////////////////////// void GLC_Context::makeCurrent() { QGLContext::makeCurrent(); if (!GLC_State::isValid()) { GLC_State::init(); } GLC_ContextManager::instance()->setCurrent(this); m_pCurrentContext= this; } void GLC_Context::doneCurrent() { QGLContext::doneCurrent(); GLC_ContextManager::instance()->setCurrent(NULL); m_pCurrentContext= NULL; } bool GLC_Context::chooseContext(const QGLContext* shareContext) { qDebug() << "GLC_Context::chooseContext"; const bool success= QGLContext::chooseContext(shareContext); if (!success) { qDebug() << "enable to create context " << this; } else if (NULL != shareContext) { GLC_Context* pContext= const_cast<GLC_Context*>(dynamic_cast<const GLC_Context*>(shareContext)); Q_ASSERT(NULL != pContext); m_ContextSharedData= pContext->m_ContextSharedData; } else { m_ContextSharedData= QSharedPointer<GLC_ContextSharedData>(new GLC_ContextSharedData()); } return success; } ////////////////////////////////////////////////////////////////////// // Private services Functions ////////////////////////////////////////////////////////////////////// void GLC_Context::init() { QStack<GLC_Matrix4x4>* pStack1= new QStack<GLC_Matrix4x4>(); pStack1->push(GLC_Matrix4x4()); m_MatrixStackHash.insert(GL_MODELVIEW, pStack1); QStack<GLC_Matrix4x4>* pStack2= new QStack<GLC_Matrix4x4>(); pStack2->push(GLC_Matrix4x4()); m_MatrixStackHash.insert(GL_PROJECTION, pStack2); m_LightingIsEnable.push(false); }
{ "language": "C++" }
/* * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include "webrtc/modules/audio_coding/codecs/isac/main/include/audio_decoder_isac.h" #include "webrtc/test/fuzzers/audio_decoder_fuzzer.h" namespace webrtc { void FuzzOneInput(const uint8_t* data, size_t size) { const int sample_rate_hz = size % 2 == 0 ? 16000 : 32000; // 16 or 32 kHz. static const size_t kAllocatedOuputSizeSamples = 32000 / 10; // 100 ms. int16_t output[kAllocatedOuputSizeSamples]; AudioDecoderIsacFloatImpl dec(sample_rate_hz); FuzzAudioDecoder(DecoderFunctionType::kNormalDecode, data, size, &dec, sample_rate_hz, sizeof(output), output); } } // namespace webrtc
{ "language": "C++" }
// Copyright Aleksey Gurtovoy 2000-2004 // // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // Preprocessed version of "boost/mpl/apply.hpp" header // -- DO NOT modify by hand! namespace boost { namespace mpl { template< typename F > struct apply0 : apply_wrap0< typename lambda<F>::type > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 1 , apply0 , (F ) ) }; template< typename F > struct apply< F,na,na,na,na,na > : apply0<F> { }; template< typename F, typename T1 > struct apply1 : apply_wrap1< typename lambda<F>::type , T1 > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 2 , apply1 , (F, T1) ) }; template< typename F, typename T1 > struct apply< F,T1,na,na,na,na > : apply1< F,T1 > { }; template< typename F, typename T1, typename T2 > struct apply2 : apply_wrap2< typename lambda<F>::type , T1, T2 > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 3 , apply2 , (F, T1, T2) ) }; template< typename F, typename T1, typename T2 > struct apply< F,T1,T2,na,na,na > : apply2< F,T1,T2 > { }; template< typename F, typename T1, typename T2, typename T3 > struct apply3 : apply_wrap3< typename lambda<F>::type , T1, T2, T3 > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 4 , apply3 , (F, T1, T2, T3) ) }; template< typename F, typename T1, typename T2, typename T3 > struct apply< F,T1,T2,T3,na,na > : apply3< F,T1,T2,T3 > { }; template< typename F, typename T1, typename T2, typename T3, typename T4 > struct apply4 : apply_wrap4< typename lambda<F>::type , T1, T2, T3, T4 > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 5 , apply4 , (F, T1, T2, T3, T4) ) }; template< typename F, typename T1, typename T2, typename T3, typename T4 > struct apply< F,T1,T2,T3,T4,na > : apply4< F,T1,T2,T3,T4 > { }; template< typename F, typename T1, typename T2, typename T3, typename T4 , typename T5 > struct apply5 : apply_wrap5< typename lambda<F>::type , T1, T2, T3, T4, T5 > { BOOST_MPL_AUX_LAMBDA_SUPPORT( 6 , apply5 , (F, T1, T2, T3, T4, T5) ) }; /// primary template (not a specialization!) template< typename F, typename T1, typename T2, typename T3, typename T4 , typename T5 > struct apply : apply5< F,T1,T2,T3,T4,T5 > { }; }}
{ "language": "C++" }
/* Copyright 2013 Google Inc. All Rights Reserved. Distributed under MIT license. See file LICENSE for detail or copy at https://opensource.org/licenses/MIT */ /* Functions to estimate the bit cost of Huffman trees. */ #include "./bit_cost.h" #include "../common/constants.h" #include "../common/platform.h" #include <brotli/types.h> #include "./fast_log.h" #include "./histogram.h" #if defined(__cplusplus) || defined(c_plusplus) extern "C" { #endif #define FN(X) X ## Literal #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Command #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #define FN(X) X ## Distance #include "./bit_cost_inc.h" /* NOLINT(build/include) */ #undef FN #if defined(__cplusplus) || defined(c_plusplus) } /* extern "C" */ #endif
{ "language": "C++" }
//===-- ABISysV_mips.h ----------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef liblldb_ABISysV_mips_h_ #define liblldb_ABISysV_mips_h_ #include "lldb/Target/ABI.h" #include "lldb/lldb-private.h" class ABISysV_mips : public lldb_private::ABI { public: ~ABISysV_mips() override = default; size_t GetRedZoneSize() const override; bool PrepareTrivialCall(lldb_private::Thread &thread, lldb::addr_t sp, lldb::addr_t functionAddress, lldb::addr_t returnAddress, llvm::ArrayRef<lldb::addr_t> args) const override; bool GetArgumentValues(lldb_private::Thread &thread, lldb_private::ValueList &values) const override; lldb_private::Status SetReturnValueObject(lldb::StackFrameSP &frame_sp, lldb::ValueObjectSP &new_value) override; lldb::ValueObjectSP GetReturnValueObjectImpl(lldb_private::Thread &thread, lldb_private::CompilerType &type) const override; bool CreateFunctionEntryUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override; bool CreateDefaultUnwindPlan(lldb_private::UnwindPlan &unwind_plan) override; bool RegisterIsVolatile(const lldb_private::RegisterInfo *reg_info) override; bool IsSoftFloat(uint32_t fp_flag) const; bool CallFrameAddressIsValid(lldb::addr_t cfa) override { // Make sure the stack call frame addresses are 8 byte aligned if (cfa & (8ull - 1ull)) return false; // Not 8 byte aligned if (cfa == 0) return false; // Zero is not a valid stack address return true; } bool CodeAddressIsValid(lldb::addr_t pc) override { // Just make sure the address is a valid 32 bit address. Bit zero // might be set due to MicroMIPS function calls, so don't enforce alignment. return (pc <= UINT32_MAX); } const lldb_private::RegisterInfo * GetRegisterInfoArray(uint32_t &count) override; // Static Functions static void Initialize(); static void Terminate(); static lldb::ABISP CreateInstance(lldb::ProcessSP process_sp, const lldb_private::ArchSpec &arch); static lldb_private::ConstString GetPluginNameStatic(); // PluginInterface protocol lldb_private::ConstString GetPluginName() override; uint32_t GetPluginVersion() override; protected: void CreateRegisterMapIfNeeded(); lldb::ValueObjectSP GetReturnValueObjectSimple(lldb_private::Thread &thread, lldb_private::CompilerType &ast_type) const; bool RegisterIsCalleeSaved(const lldb_private::RegisterInfo *reg_info); private: ABISysV_mips(lldb::ProcessSP process_sp, std::unique_ptr<llvm::MCRegisterInfo> info_up) : lldb_private::ABI(std::move(process_sp), std::move(info_up)) { // Call CreateInstance instead. } }; #endif // liblldb_ABISysV_mips_h_
{ "language": "C++" }
#include "axis_limits_dialog.h" #include "ui_axis_limits_dialog.h" #include <QLineEdit> #include <QDoubleValidator> using std::numeric_limits; AxisLimitsDialog::AxisLimitsDialog(QWidget* parent) : QDialog(parent), ui(new Ui::AxisLimitsDialog) { ui->setupUi(this); _limits.min = (-numeric_limits<double>::max() / 2); _limits.max = (numeric_limits<double>::max() / 2); ui->lineEditMinY->setValidator(new QDoubleValidator(this)); ui->lineEditMaxY->setValidator(new QDoubleValidator(this)); } AxisLimitsDialog::~AxisLimitsDialog() { delete ui; } void AxisLimitsDialog::setDefaultRange(PlotData::RangeValue range) { _parent_limits = range; if (!ui->checkBoxMinY->isChecked()) { ui->lineEditMinY->setText(QString::number(_parent_limits.min)); } if (!ui->checkBoxMaxY->isChecked()) { ui->lineEditMaxY->setText(QString::number(_parent_limits.max)); } } void AxisLimitsDialog::enableMin(bool enabled, double value) { _parent_limits.min = value; ui->lineEditMinY->setText(QString::number(_parent_limits.min)); ui->checkBoxMinY->setChecked(enabled); } void AxisLimitsDialog::enableMax(bool enabled, double value) { _parent_limits.max = value; ui->lineEditMaxY->setText(QString::number(_parent_limits.max)); ui->checkBoxMaxY->setChecked(enabled); } bool AxisLimitsDialog::limitsEnabled() const { return ui->checkBoxMinY->isChecked() || ui->checkBoxMaxY->isChecked(); } void AxisLimitsDialog::on_checkBoxMinY_toggled(bool checked) { ui->lineEditMinY->setEnabled(checked); ui->pushButtonMinY->setEnabled(checked); } void AxisLimitsDialog::on_checkBoxMaxY_toggled(bool checked) { ui->lineEditMaxY->setEnabled(checked); ui->pushButtonMaxY->setEnabled(checked); } void AxisLimitsDialog::on_pushButtonDone_pressed() { double ymin = -numeric_limits<double>::max(); double ymax = numeric_limits<double>::max(); if (!ui->lineEditMinY->text().isEmpty()) { ymin = ui->lineEditMinY->text().toDouble(); } if (!ui->lineEditMaxY->text().isEmpty()) { ymax = ui->lineEditMaxY->text().toDouble(); } if (ymin > ymax) { // swap ui->lineEditMinY->setText(QString::number(ymax)); ui->lineEditMaxY->setText(QString::number(ymin)); } else { _limits.min = (ui->checkBoxMinY->isChecked() ? ymin : -numeric_limits<double>::max() / 2); _limits.max = (ui->checkBoxMaxY->isChecked() ? ymax : numeric_limits<double>::max() / 2); this->accept(); } } void AxisLimitsDialog::on_pushButtonMinY_pressed() { ui->lineEditMinY->setText(QString::number(_parent_limits.min)); } void AxisLimitsDialog::on_pushButtonMaxY_pressed() { ui->lineEditMaxY->setText(QString::number(_parent_limits.max)); } void AxisLimitsDialog::closeEvent(QCloseEvent* event) { on_pushButtonDone_pressed(); }
{ "language": "C++" }
//------------------------------------------------------------------------------ // Copyright (c) 2003, Ingo Weinhold // // 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. // // File Name: ElfImage.cpp // Author: Ingo Weinhold (bonefish@users.sf.net) // Description: Implementation of ElfImage, a class encapsulating // a loaded ELF image, providing support for accessing the // image's symbols and their relocation entries. //------------------------------------------------------------------------------ #include <new> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <List.h> #include <debug/debug_support.h> #include "ElfImage.h" static status_t get_static_image_symbol(image_id image, const char* name, int32 symbolType, void** _address) { // try standard lookup first status_t error = get_image_symbol(image, name, symbolType, _address); if (error == B_OK) return B_OK; // get an image info image_info imageInfo; error = get_image_info(image, &imageInfo); if (error != B_OK) return error; // get a symbol iterator debug_symbol_iterator* iterator; error = debug_create_file_symbol_iterator(imageInfo.name, &iterator); if (error != B_OK) return error; // get the unrelocated image info image_info unrelocatedImageInfo; error = debug_get_symbol_iterator_image_info(iterator, &unrelocatedImageInfo); if (error != B_OK) { debug_delete_symbol_iterator(iterator); return error; } // iterate through the symbols int32 nameLength = strlen(name); while (true) { char foundName[nameLength + 1]; int32 foundType; void* foundAddress; size_t foundSize; if (debug_next_image_symbol(iterator, foundName, nameLength + 1, &foundType, &foundAddress, &foundSize) != B_OK) { debug_delete_symbol_iterator(iterator); return B_ENTRY_NOT_FOUND; } if (strcmp(foundName, name) == 0 && (symbolType == B_SYMBOL_TYPE_ANY || foundType == symbolType)) { *_address = (void*)((addr_t)foundAddress + (addr_t)imageInfo.text - (addr_t)unrelocatedImageInfo.text); debug_delete_symbol_iterator(iterator); return B_OK; } } } // ElfImage // constructor ElfImage::ElfImage() : fImage(-1), fFile(), fTextAddress(NULL), fDataAddress(NULL), fGotAddress(NULL) { } // destructor ElfImage::~ElfImage() { Unset(); } // SetTo status_t ElfImage::SetTo(image_id image) { Unset(); status_t error = _SetTo(image); if (error) Unset(); return error; } // Unset void ElfImage::Unset() { fFile.Unset(); fImage = -1; fTextAddress = NULL; fDataAddress = NULL; fGotAddress = NULL; } // Unload void ElfImage::Unload() { fFile.Unload(); } // FindSymbol status_t ElfImage::FindSymbol(const char* symbolName, void** address) { return get_image_symbol(fImage, symbolName, B_SYMBOL_TYPE_ANY, address); } // GetSymbolRelocations status_t ElfImage::GetSymbolRelocations(const char* symbolName, BList* relocations) { status_t error = B_OK; ElfRelocation relocation; for (ElfRelocationIterator it(&fFile); it.GetNext(&relocation); ) { uint32 type = relocation.GetType(); // get the symbol ElfSymbol symbol; if ((type == R_GLOB_DAT || type == R_JUMP_SLOT) && relocation.GetSymbol(&symbol) == B_OK && symbol.GetName()) { // only undefined symbols with global binding if ((symbol.GetBinding() == STB_GLOBAL || symbol.GetBinding() == STB_WEAK) && (symbol.GetTargetSectionIndex() == SHN_UNDEF || symbol.GetTargetSectionIndex() >= (uint32)fFile.CountSections()) && !strcmp(symbol.GetName(), symbolName)) { // get the address of the GOT entry for the symbol void** gotEntry = (void**)(fTextAddress + relocation.GetOffset()); if (!relocations->AddItem(gotEntry)) { error = B_NO_MEMORY; break; } } } } return error; } // _SetTo status_t ElfImage::_SetTo(image_id image) { // get an image info image_info imageInfo; status_t error = get_image_info(image, &imageInfo); if (error != B_OK) return error; fImage = imageInfo.id; // get the address of global offset table error = get_static_image_symbol(image, "_GLOBAL_OFFSET_TABLE_", B_SYMBOL_TYPE_ANY, (void**)&fGotAddress); if (error != B_OK) return error; fTextAddress = (uint8*)imageInfo.text; fDataAddress = (uint8*)imageInfo.data; // init the file error = fFile.SetTo(imageInfo.name); if (error != B_OK) return error; return B_OK; }
{ "language": "C++" }
From 6c36f0ff8c1f5852c33d2b23714f9f187cc6ff26 Mon Sep 17 00:00:00 2001 From: Khem Raj <raj.khem@gmail.com> Date: Fri, 5 Jun 2015 19:55:05 -0700 Subject: [PATCH] Exclude backtrace() API for non-glibc libraries It was excluding musl with current checks, so lets make it such that it considers only glibc when using backtrace API Signed-off-by: Khem Raj <raj.khem@gmail.com> Downloaded from: https://github.com/meta-qt5/meta-qt5/blob/krogoth/recipes-qt/qt5/qtwebkit/ 0003-Exclude-backtrace-API-for-non-glibc-libraries.patch Signed-off-by: Gary Bisson <gary.bisson@boundarydevices.com> --- Source/WTF/wtf/Assertions.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Source/WTF/wtf/Assertions.cpp b/Source/WTF/wtf/Assertions.cpp index 1b2091f..ba03a28 100644 --- a/Source/WTF/wtf/Assertions.cpp +++ b/Source/WTF/wtf/Assertions.cpp @@ -61,7 +61,7 @@ #include <windows.h> #endif -#if (OS(DARWIN) || (OS(LINUX) && !defined(__UCLIBC__))) && !OS(ANDROID) +#if (OS(DARWIN) || (OS(LINUX) && defined (__GLIBC__) && !defined(__UCLIBC__))) && !OS(ANDROID) #include <cxxabi.h> #include <dlfcn.h> #include <execinfo.h> @@ -245,7 +245,7 @@ void WTFReportArgumentAssertionFailure(const char* file, int line, const char* f void WTFGetBacktrace(void** stack, int* size) { -#if (OS(DARWIN) || (OS(LINUX) && !defined(__UCLIBC__))) && !OS(ANDROID) +#if (OS(DARWIN) || (OS(LINUX) && defined(__GLIBC__) && !defined(__UCLIBC__))) && !OS(ANDROID) *size = backtrace(stack, *size); #elif OS(WINDOWS) && !OS(WINCE) // The CaptureStackBackTrace function is available in XP, but it is not defined -- 2.7.0
{ "language": "C++" }
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. /*============================================================================= OpenGLDrv.cpp: Unreal OpenGL RHI library implementation. =============================================================================*/ #include "OpenGLDrv.h" #include "Modules/ModuleManager.h" #include "EngineGlobals.h" #include "StaticBoundShaderState.h" #include "RHIStaticStates.h" #include "Engine/Engine.h" #include "OpenGLDrvPrivate.h" #include "PipelineStateCache.h" #include "Engine/GameViewportClient.h" IMPLEMENT_MODULE(FOpenGLDynamicRHIModule, OpenGLDrv); #include "Shader.h" #include "OneColorShader.h" /** OpenGL Logging. */ DEFINE_LOG_CATEGORY(LogOpenGL); ERHIFeatureLevel::Type GRequestedFeatureLevel = ERHIFeatureLevel::Num; void FOpenGLDynamicRHI::RHIPushEvent(const TCHAR* Name, FColor Color) { #if ENABLE_OPENGL_DEBUG_GROUPS // @todo-mobile: Fix string conversion ASAP! FOpenGL::PushGroupMarker(TCHAR_TO_ANSI(Name)); #endif GPUProfilingData.PushEvent(Name, Color); } void FOpenGLGPUProfiler::PushEvent(const TCHAR* Name, FColor Color) { FGPUProfiler::PushEvent(Name, Color); } void FOpenGLDynamicRHI::RHIPopEvent() { #if ENABLE_OPENGL_DEBUG_GROUPS FOpenGL::PopGroupMarker(); #endif GPUProfilingData.PopEvent(); } void FOpenGLGPUProfiler::PopEvent() { FGPUProfiler::PopEvent(); } void FOpenGLGPUProfiler::BeginFrame(FOpenGLDynamicRHI* InRHI) { if (NestedFrameCount++>0) { // guard against nested Begin/EndFrame calls. return; } CurrentEventNode = NULL; check(!bTrackingEvents); check(!CurrentEventNodeFrame); // this should have already been cleaned up and the end of the previous frame // latch the bools from the game thread into our private copy bLatchedGProfilingGPU = GTriggerGPUProfile; bLatchedGProfilingGPUHitches = GTriggerGPUHitchProfile; if (bLatchedGProfilingGPUHitches) { bLatchedGProfilingGPU = false; // we do NOT permit an ordinary GPU profile during hitch profiles } // if we are starting a hitch profile or this frame is a gpu profile, then save off the state of the draw events if (bLatchedGProfilingGPU || (!bPreviousLatchedGProfilingGPUHitches && bLatchedGProfilingGPUHitches)) { bOriginalGEmitDrawEvents = GEmitDrawEvents; } if (bLatchedGProfilingGPU || bLatchedGProfilingGPUHitches) { if (bLatchedGProfilingGPUHitches && GPUHitchDebounce) { // if we are doing hitches and we had a recent hitch, wait to recover // the reasoning is that collecting the hitch report may itself hitch the GPU GPUHitchDebounce--; } else { GEmitDrawEvents = true; // thwart an attempt to turn this off on the game side bTrackingEvents = true; CurrentEventNodeFrame = new FOpenGLEventNodeFrame(InRHI); CurrentEventNodeFrame->StartFrame(); } } else if (bPreviousLatchedGProfilingGPUHitches) { // hitch profiler is turning off, clear history and restore draw events GPUHitchEventNodeFrames.Empty(); GEmitDrawEvents = bOriginalGEmitDrawEvents; } bPreviousLatchedGProfilingGPUHitches = bLatchedGProfilingGPUHitches; // Skip timing events when using SLI, they will not be accurate anyway if (GNumActiveGPUsForRendering == 1) { if (FrameTiming.IsSupported()) { FrameTiming.StartTiming(); } if (FOpenGLDisjointTimeStampQuery::IsSupported()) { CurrentGPUFrameQueryIndex = (CurrentGPUFrameQueryIndex + 1) % MAX_GPUFRAMEQUERIES; DisjointGPUFrameTimeQuery[CurrentGPUFrameQueryIndex].StartTracking(); } } if (GEmitDrawEvents) { PushEvent(TEXT("FRAME"), FColor(0, 255, 0, 255)); } } void FOpenGLGPUProfiler::EndFrame() { if (--NestedFrameCount != 0) { // ignore endframes calls from nested beginframe calls. return; } if (GEmitDrawEvents) { PopEvent(); } // Skip timing events when using SLI, they will not be accurate anyway if (GNumActiveGPUsForRendering == 1) { if (FrameTiming.IsSupported()) { FrameTiming.EndTiming(); } if (FOpenGLDisjointTimeStampQuery::IsSupported()) { DisjointGPUFrameTimeQuery[CurrentGPUFrameQueryIndex].EndTracking(); } } // Skip timing events when using SLI, as they will block the GPU and we want maximum throughput // Stat unit GPU time is not accurate anyway with SLI if (FrameTiming.IsSupported() && GNumActiveGPUsForRendering == 1) { uint64 GPUTiming = FrameTiming.GetTiming(); uint64 GPUFreq = FrameTiming.GetTimingFrequency(); GGPUFrameTime = FMath::TruncToInt( double(GPUTiming) / double(GPUFreq) / FPlatformTime::GetSecondsPerCycle() ); } else if (FOpenGLDisjointTimeStampQuery::IsSupported() && GNumActiveGPUsForRendering == 1) { static uint32 GLastGPUFrameTime = 0; uint64 GPUTiming = 0; uint64 GPUFreq = FOpenGLDisjointTimeStampQuery::GetTimingFrequency(); int OldestQueryIndex = (CurrentGPUFrameQueryIndex + 1) % MAX_GPUFRAMEQUERIES; if ( DisjointGPUFrameTimeQuery[OldestQueryIndex].IsResultValid() && DisjointGPUFrameTimeQuery[OldestQueryIndex].GetResult(&GPUTiming) ) { GGPUFrameTime = FMath::TruncToInt( double(GPUTiming) / double(GPUFreq) / FPlatformTime::GetSecondsPerCycle() ); GLastGPUFrameTime = GGPUFrameTime; } else { // Keep the timing of the last frame if the query was disjoint (e.g. GPU frequency changed and the result is undefined) GGPUFrameTime = GLastGPUFrameTime; } } else { GGPUFrameTime = 0; } // if we have a frame open, close it now. if (CurrentEventNodeFrame) { CurrentEventNodeFrame->EndFrame(); } check(!bTrackingEvents || bLatchedGProfilingGPU || bLatchedGProfilingGPUHitches); check(!bTrackingEvents || CurrentEventNodeFrame); if (bLatchedGProfilingGPU) { if (bTrackingEvents) { GEmitDrawEvents = bOriginalGEmitDrawEvents; UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("")); CurrentEventNodeFrame->DumpEventTree(); // OPENGL_PERFORMANCE_DATA_INVALID is a compile time constant bool DebugEnabled = false; #ifdef GL_ARB_debug_output DebugEnabled = GL_TRUE == glIsEnabled( GL_DEBUG_OUTPUT ); #endif #if !OPENGL_PERFORMANCE_DATA_INVALID if( DebugEnabled ) #endif { UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("*********************************************************************************************")); UE_LOG(LogRHI, Warning, TEXT("OpenGL perfomance data is potentially invalid because of the following build/runtime options:")); #define LOG_GL_DEBUG_FLAG(a) UE_LOG(LogRHI, Warning, TEXT(" built with %s = %d"), TEXT(#a), a); LOG_GL_DEBUG_FLAG(ENABLE_OPENGL_FRAMEDUMP); LOG_GL_DEBUG_FLAG(ENABLE_VERIFY_GL); LOG_GL_DEBUG_FLAG(ENABLE_UNIFORM_BUFFER_LAYOUT_VERIFICATION); LOG_GL_DEBUG_FLAG(ENABLE_UNIFORM_BUFFER_LAYOUT_DUMP); LOG_GL_DEBUG_FLAG(DEBUG_GL_SHADERS); LOG_GL_DEBUG_FLAG(ENABLE_OPENGL_DEBUG_GROUPS); LOG_GL_DEBUG_FLAG(OPENGL_PERFORMANCE_DATA_INVALID); #undef LOG_GL_DEBUG_FLAG UE_LOG(LogRHI, Warning, TEXT("*********************************************************************************************")); UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("")); } GTriggerGPUProfile = false; bLatchedGProfilingGPU = false; if (RHIConfig::ShouldSaveScreenshotAfterProfilingGPU() && GEngine->GameViewport) { GEngine->GameViewport->Exec( NULL, TEXT("SCREENSHOT"), *GLog); } } } else if (bLatchedGProfilingGPUHitches) { //@todo this really detects any hitch, even one on the game thread. // it would be nice to restrict the test to stalls on D3D, but for now... // this needs to be out here because bTrackingEvents is false during the hitch debounce static double LastTime = -1.0; double Now = FPlatformTime::Seconds(); if (bTrackingEvents) { /** How long, in seconds a frame much be to be considered a hitch **/ static const float HitchThreshold = .1f; //100ms float ThisTime = Now - LastTime; bool bHitched = (ThisTime > HitchThreshold) && LastTime > 0.0 && CurrentEventNodeFrame; if (bHitched) { UE_LOG(LogRHI, Warning, TEXT("*******************************************************************************")); UE_LOG(LogRHI, Warning, TEXT("********** Hitch detected on CPU, frametime = %6.1fms"),ThisTime * 1000.0f); UE_LOG(LogRHI, Warning, TEXT("*******************************************************************************")); for (int32 Frame = 0; Frame < GPUHitchEventNodeFrames.Num(); Frame++) { UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("********** GPU Frame: Current - %d"),GPUHitchEventNodeFrames.Num() - Frame); GPUHitchEventNodeFrames[Frame].DumpEventTree(); } UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("")); UE_LOG(LogRHI, Warning, TEXT("********** GPU Frame: Current")); CurrentEventNodeFrame->DumpEventTree(); UE_LOG(LogRHI, Warning, TEXT("*******************************************************************************")); UE_LOG(LogRHI, Warning, TEXT("********** End Hitch GPU Profile")); UE_LOG(LogRHI, Warning, TEXT("*******************************************************************************")); if (GEngine->GameViewport) { GEngine->GameViewport->Exec( NULL, TEXT("SCREENSHOT"), *GLog); } GPUHitchDebounce = 5; // don't trigger this again for a while GPUHitchEventNodeFrames.Empty(); // clear history } else if (CurrentEventNodeFrame) // this will be null for discarded frames while recovering from a recent hitch { /** How many old frames to buffer for hitch reports **/ static const int32 HitchHistorySize = 4; if (GPUHitchEventNodeFrames.Num() >= HitchHistorySize) { GPUHitchEventNodeFrames.RemoveAt(0); } GPUHitchEventNodeFrames.Add((FOpenGLEventNodeFrame*)CurrentEventNodeFrame); CurrentEventNodeFrame = NULL; // prevent deletion of this below; ke kept it in the history } } LastTime = Now; } bTrackingEvents = false; delete CurrentEventNodeFrame; CurrentEventNodeFrame = NULL; } void FOpenGLGPUProfiler::Cleanup() { for (int32 Index = 0; Index < MAX_GPUFRAMEQUERIES; ++Index) { DisjointGPUFrameTimeQuery[Index].ReleaseResource(); } FrameTiming.ReleaseResource(); NestedFrameCount = 0; } /** Start this frame of per tracking */ void FOpenGLEventNodeFrame::StartFrame() { EventTree.Reset(); DisjointQuery.StartTracking(); RootEventTiming.StartTiming(); } /** End this frame of per tracking, but do not block yet */ void FOpenGLEventNodeFrame::EndFrame() { RootEventTiming.EndTiming(); DisjointQuery.EndTracking(); } float FOpenGLEventNodeFrame::GetRootTimingResults() { double RootResult = 0.0f; if (RootEventTiming.IsSupported()) { const uint64 GPUTiming = RootEventTiming.GetTiming(true); const uint64 GPUFreq = RootEventTiming.GetTimingFrequency(); RootResult = double(GPUTiming) / double(GPUFreq); } return (float)RootResult; } void FOpenGLEventNodeFrame::LogDisjointQuery() { if (DisjointQuery.IsSupported()) { UE_LOG(LogRHI, Warning, TEXT("%s"), DisjointQuery.IsResultValid() ? TEXT("Profiled range was continuous.") : TEXT("Profiled range was disjoint! GPU switched to doing something else while profiling.") ); } else { UE_LOG(LogRHI, Warning, TEXT("Profiled range \"disjoinness\" could not be determined due to lack of disjoint timer query functionality on this platform.")); } } float FOpenGLEventNode::GetTiming() { float Result = 0; if (Timing.IsSupported()) { // Get the timing result and block the CPU until it is ready const uint64 GPUTiming = Timing.GetTiming(true); const uint64 GPUFreq = Timing.GetTimingFrequency(); Result = double(GPUTiming) / double(GPUFreq); } return Result; } void FOpenGLDynamicRHI::InitializeStateResources() { SharedContextState.InitializeResources(FOpenGL::GetMaxCombinedTextureImageUnits(), OGL_MAX_COMPUTE_STAGE_UAV_UNITS); RenderingContextState.InitializeResources(FOpenGL::GetMaxCombinedTextureImageUnits(), OGL_MAX_COMPUTE_STAGE_UAV_UNITS); PendingState.InitializeResources(FOpenGL::GetMaxCombinedTextureImageUnits(), OGL_MAX_COMPUTE_STAGE_UAV_UNITS); } GLint FOpenGLBase::MaxTextureImageUnits = -1; GLint FOpenGLBase::MaxCombinedTextureImageUnits = -1; GLint FOpenGLBase::MaxVertexTextureImageUnits = -1; GLint FOpenGLBase::MaxGeometryTextureImageUnits = -1; GLint FOpenGLBase::MaxHullTextureImageUnits = -1; GLint FOpenGLBase::MaxDomainTextureImageUnits = -1; GLint FOpenGLBase::MaxVaryingVectors = -1; GLint FOpenGLBase::MaxVertexUniformComponents = -1; GLint FOpenGLBase::MaxPixelUniformComponents = -1; GLint FOpenGLBase::MaxGeometryUniformComponents = -1; GLint FOpenGLBase::MaxHullUniformComponents = -1; GLint FOpenGLBase::MaxDomainUniformComponents = -1; bool FOpenGLBase::bSupportsClipControl = false; bool FOpenGLBase::bSupportsASTC = false; bool FOpenGLBase::bSupportsCopyImage = false; bool FOpenGLBase::bSupportsSeamlessCubemap = false; bool FOpenGLBase::bSupportsVolumeTextureRendering = false; bool FOpenGLBase::bSupportsTextureFilterAnisotropic = false; bool FOpenGLBase::bSupportsDrawBuffersBlend = false; bool FOpenGLBase::bAmdWorkaround = false; void FOpenGLBase::ProcessQueryGLInt() { GET_GL_INT(GL_MAX_TEXTURE_IMAGE_UNITS, 0, MaxTextureImageUnits); GET_GL_INT(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS, 0, MaxVertexTextureImageUnits); GET_GL_INT(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, 0, MaxCombinedTextureImageUnits); } void FOpenGLBase::ProcessExtensions( const FString& ExtensionsString ) { ProcessQueryGLInt(); // For now, just allocate additional units if available and advertise no tessellation units for HW that can't handle more if ( MaxCombinedTextureImageUnits < 48 ) { // To work around AMD driver limitation of 32 GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS, // Going to hard code this for now (16 units in PS, 8 units in VS, 8 units in GS). // This is going to be a problem for tessellation. MaxTextureImageUnits = MaxTextureImageUnits > 16 ? 16 : MaxTextureImageUnits; MaxVertexTextureImageUnits = MaxVertexTextureImageUnits > 8 ? 8 : MaxVertexTextureImageUnits; MaxGeometryTextureImageUnits = MaxGeometryTextureImageUnits > 8 ? 8 : MaxGeometryTextureImageUnits; MaxHullTextureImageUnits = 0; MaxDomainTextureImageUnits = 0; MaxCombinedTextureImageUnits = MaxCombinedTextureImageUnits > 32 ? 32 : MaxCombinedTextureImageUnits; } else { // clamp things to the levels that the other path is going, but allow additional units for tessellation MaxTextureImageUnits = MaxTextureImageUnits > 16 ? 16 : MaxTextureImageUnits; MaxVertexTextureImageUnits = MaxVertexTextureImageUnits > 8 ? 8 : MaxVertexTextureImageUnits; MaxGeometryTextureImageUnits = MaxGeometryTextureImageUnits > 8 ? 8 : MaxGeometryTextureImageUnits; MaxHullTextureImageUnits = MaxHullTextureImageUnits > 8 ? 8 : MaxHullTextureImageUnits; MaxDomainTextureImageUnits = MaxDomainTextureImageUnits > 8 ? 8 : MaxDomainTextureImageUnits; MaxCombinedTextureImageUnits = MaxCombinedTextureImageUnits > 48 ? 48 : MaxCombinedTextureImageUnits; } // Check for support for advanced texture compression (desktop and mobile) bSupportsASTC = ExtensionsString.Contains(TEXT("GL_KHR_texture_compression_astc_ldr")); // check for copy image support bSupportsCopyImage = ExtensionsString.Contains(TEXT("GL_ARB_copy_image")); bSupportsSeamlessCubemap = ExtensionsString.Contains(TEXT("GL_ARB_seamless_cube_map")); bSupportsTextureFilterAnisotropic = ExtensionsString.Contains(TEXT("GL_EXT_texture_filter_anisotropic")); bSupportsDrawBuffersBlend = ExtensionsString.Contains(TEXT("GL_ARB_draw_buffers_blend")); #if PLATFORM_IOS GRHIVendorId = 0x1010; #else FString VendorName( ANSI_TO_TCHAR((const ANSICHAR*)glGetString(GL_VENDOR) ) ); if (VendorName.Contains(TEXT("ATI "))) { GRHIVendorId = 0x1002; #if PLATFORM_WINDOWS || PLATFORM_LINUX bAmdWorkaround = true; #endif } #if PLATFORM_LINUX else if (VendorName.Contains(TEXT("X.Org"))) { GRHIVendorId = 0x1002; bAmdWorkaround = true; } #endif else if (VendorName.Contains(TEXT("Intel ")) || VendorName == TEXT("Intel")) { GRHIVendorId = 0x8086; #if PLATFORM_WINDOWS || PLATFORM_LINUX bAmdWorkaround = true; #endif } else if (VendorName.Contains(TEXT("NVIDIA "))) { GRHIVendorId = 0x10DE; } else if (VendorName.Contains(TEXT("ImgTec"))) { GRHIVendorId = 0x1010; } else if (VendorName.Contains(TEXT("ARM"))) { GRHIVendorId = 0x13B5; } else if (VendorName.Contains(TEXT("Qualcomm"))) { GRHIVendorId = 0x5143; } if (GRHIVendorId == 0x0) { // Fix for Mesa Radeon const ANSICHAR* AnsiVersion = (const ANSICHAR*)glGetString(GL_VERSION); const ANSICHAR* AnsiRenderer = (const ANSICHAR*)glGetString(GL_RENDERER); if (AnsiVersion && AnsiRenderer) { if (FCStringAnsi::Strstr(AnsiVersion, "Mesa") && (FCStringAnsi::Strstr(AnsiRenderer, "AMD") || FCStringAnsi::Strstr(AnsiRenderer, "ATI"))) { // Radeon GRHIVendorId = 0x1002; } } } #if PLATFORM_WINDOWS auto* CVar = IConsoleManager::Get().FindConsoleVariable(TEXT("OpenGL.UseStagingBuffer")); if (CVar) { CVar->Set(false); } #endif #endif // Setup CVars that require the RHI initialized //@todo-rco: Workaround Nvidia driver crash #if PLATFORM_DESKTOP && !PLATFORM_LINUX if (IsRHIDeviceNVIDIA()) { OpenGLConsoleVariables::bUseVAB = 0; } #endif } void GetExtensionsString( FString& ExtensionsString) { GLint ExtensionCount = 0; ExtensionsString = TEXT(""); if ( FOpenGL::SupportsIndexedExtensions() ) { glGetIntegerv(GL_NUM_EXTENSIONS, &ExtensionCount); for (int32 ExtensionIndex = 0; ExtensionIndex < ExtensionCount; ++ExtensionIndex) { const ANSICHAR* ExtensionString = FOpenGL::GetStringIndexed(GL_EXTENSIONS, ExtensionIndex); ExtensionsString += TEXT(" "); ExtensionsString += ANSI_TO_TCHAR(ExtensionString); } } else { const ANSICHAR* GlGetStringOutput = (const ANSICHAR*) glGetString( GL_EXTENSIONS ); if (GlGetStringOutput) { ExtensionsString += GlGetStringOutput; ExtensionsString += TEXT(" "); } } } namespace OpenGLConsoleVariables { #if PLATFORM_WINDOWS || PLATFORM_LINUX int32 bUseGlClipControlIfAvailable = 1; #else int32 bUseGlClipControlIfAvailable = 0; #endif static FAutoConsoleVariableRef CVarUseGlClipControlIfAvailable( TEXT("OpenGL.UseGlClipControlIfAvailable"), bUseGlClipControlIfAvailable, TEXT("If true, the engine trys to use glClipControl if the driver supports it."), ECVF_RenderThreadSafe | ECVF_ReadOnly ); } void InitDefaultGLContextState(void) { // NOTE: This function can be called before capabilities setup, so extensions need to be checked directly FString ExtensionsString; GetExtensionsString(ExtensionsString); // Intel HD4000 under <= 10.8.4 requires GL_DITHER disabled or dithering will occur on any channel < 8bits. // No other driver does this but we don't need GL_DITHER on anyway. glDisable(GL_DITHER); if (FOpenGL::SupportsFramebufferSRGBEnable()) { // Render targets with TexCreate_SRGB should do sRGB conversion like in D3D11 glEnable(GL_FRAMEBUFFER_SRGB); } // Engine always expects seamless cubemap, so enable it if available if (ExtensionsString.Contains(TEXT("GL_ARB_seamless_cube_map"))) { glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); } #if PLATFORM_WINDOWS || PLATFORM_LINUX if (OpenGLConsoleVariables::bUseGlClipControlIfAvailable && ExtensionsString.Contains(TEXT("GL_ARB_clip_control"))) { FOpenGL::EnableSupportsClipControl(); glClipControl(GL_UPPER_LEFT, GL_ZERO_TO_ONE); } #endif }
{ "language": "C++" }
// Copyright 2001-2019 Crytek GmbH / Crytek Group. All rights reserved. #include "StdAfx.h" #include "ItemDescriptionDlg.h" #include "SmartObjectsEditorDialog.h" #include "SmartObjectClassDialog.h" #include "AI/AIManager.h" #include "IResourceSelectorHost.h" #include "Controls/QuestionDialog.h" IMPLEMENT_DYNAMIC(CSmartObjectClassDialog, CDialog) CSmartObjectClassDialog::CSmartObjectClassDialog(CWnd* pParent /*=NULL*/, bool multi /*=false*/) : CDialog(multi ? CSmartObjectClassDialog::IDD_MULTIPLE : CSmartObjectClassDialog::IDD, pParent) { m_bMultiple = multi; m_bEnableOK = false; } CSmartObjectClassDialog::~CSmartObjectClassDialog() { } void CSmartObjectClassDialog::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Control(pDX, IDC_TREE, m_TreeCtrl); } BEGIN_MESSAGE_MAP(CSmartObjectClassDialog, CDialog) ON_BN_CLICKED(IDC_NEW, OnNewBtn) ON_BN_CLICKED(IDEDIT, OnEditBtn) ON_BN_CLICKED(IDREFRESH, OnRefreshBtn) //ON_LBN_DBLCLK(IDC_TREE, OnDblClk) //ON_LBN_SELCHANGE(IDC_TREE, OnSelchangeClass) ON_NOTIFY(TVN_KEYDOWN, IDC_TREE, OnTVKeyDown) ON_NOTIFY(NM_CLICK, IDC_TREE, OnTVClick) ON_NOTIFY(NM_DBLCLK, IDC_TREE, OnTVDblClk) ON_NOTIFY(TVN_SELCHANGED, IDC_TREE, OnTVSelChanged) ON_WM_SHOWWINDOW() END_MESSAGE_MAP() HTREEITEM CSmartObjectClassDialog::FindOrInsertItem(const CString& name, HTREEITEM parent) { HTREEITEM item = m_TreeCtrl.GetChildItem(parent); while (item && name.CompareNoCase(m_TreeCtrl.GetItemText(item)) > 0) item = m_TreeCtrl.GetNextSiblingItem(item); if (!item) return m_TreeCtrl.InsertItem(name, parent, TVI_LAST); if (name.CompareNoCase(m_TreeCtrl.GetItemText(item)) == 0) return item; item = m_TreeCtrl.InsertItem(name, parent, TVI_SORT); return item; } HTREEITEM CSmartObjectClassDialog::ForcePath(const CString& location) { HTREEITEM item = 0; CString token; int i = 0; while (!(token = location.Tokenize("/", i)).IsEmpty()) item = FindOrInsertItem('/' + token, item); return item; } void CSmartObjectClassDialog::RemoveItemAndDummyParents(HTREEITEM item) { CRY_ASSERT(item && !m_TreeCtrl.ItemHasChildren(item)); CRY_VERIFY(m_mapStringToItem.erase(m_TreeCtrl.GetItemText(item)) == 1); while (item && !m_TreeCtrl.ItemHasChildren(item)) { HTREEITEM parent = m_TreeCtrl.GetParentItem(item); m_TreeCtrl.DeleteItem(item); item = parent; } } HTREEITEM CSmartObjectClassDialog::AddItemInTreeCtrl(const char* name, const CString& location) { HTREEITEM parent = ForcePath(location); HTREEITEM item = m_TreeCtrl.InsertItem(name, parent, TVI_SORT); m_mapStringToItem[name] = item; return item; } HTREEITEM CSmartObjectClassDialog::FindItemInTreeCtrl(const CString& name) { MapStringToItem::iterator it = m_mapStringToItem.find(name); if (it == m_mapStringToItem.end()) return 0; else return it->second; } // CSmartObjectClassDialog message handlers void CSmartObjectClassDialog::OnTVKeyDown(NMHDR* pNMHdr, LRESULT* pResult) { if (!m_bMultiple) return; NMTVKEYDOWN* nmkd = (NMTVKEYDOWN*) pNMHdr; if (nmkd->wVKey != ' ') return; if (HTREEITEM item = m_TreeCtrl.GetSelectedItem()) { if (m_TreeCtrl.ItemHasChildren(item)) { m_TreeCtrl.SetCheck(item, !m_TreeCtrl.GetCheck(item)); } else { UINT state = m_TreeCtrl.GetItemState(item, TVIS_BOLD); m_TreeCtrl.SetItemState(item, state ^ TVIS_BOLD, TVIS_BOLD); if (state & TVIS_BOLD) { // It was bold, i.e. it was selected, so deselect it now. m_setClasses.erase(m_TreeCtrl.GetItemText(item)); } else { // It wasn't bold, i.e. it wasn't selected, so select it now. m_setClasses.insert(m_TreeCtrl.GetItemText(item)); } UpdateListCurrentClasses(); } } } void CSmartObjectClassDialog::OnTVClick(NMHDR* pNMHdr, LRESULT* pResult) { if (!m_bMultiple) return; TVHITTESTINFO hti; GetCursorPos(&hti.pt); m_TreeCtrl.ScreenToClient(&hti.pt); m_TreeCtrl.HitTest(&hti); if (hti.hItem && hti.flags == TVHT_ONITEMSTATEICON) { if (m_TreeCtrl.ItemHasChildren(hti.hItem)) m_TreeCtrl.SetCheck(hti.hItem, !m_TreeCtrl.GetCheck(hti.hItem)); else { BOOL check = !m_TreeCtrl.GetCheck(hti.hItem); m_TreeCtrl.SetItemState(hti.hItem, check ? TVIS_BOLD : 0, TVIS_BOLD); if (check) m_setClasses.insert(m_TreeCtrl.GetItemText(hti.hItem)); else m_setClasses.erase(m_TreeCtrl.GetItemText(hti.hItem)); UpdateListCurrentClasses(); } } } void CSmartObjectClassDialog::OnTVDblClk(NMHDR*, LRESULT*) { if (HTREEITEM item = m_TreeCtrl.GetSelectedItem()) { if (!m_TreeCtrl.ItemHasChildren(item)) { if (!m_bMultiple) EndDialog(IDOK); else { BOOL check = !m_TreeCtrl.GetCheck(item); m_TreeCtrl.SetCheck(item, check); m_TreeCtrl.SetItemState(item, check ? TVIS_BOLD : 0, TVIS_BOLD); if (check) m_setClasses.insert(m_TreeCtrl.GetItemText(item)); else m_setClasses.erase(m_TreeCtrl.GetItemText(item)); UpdateListCurrentClasses(); } } } } void CSmartObjectClassDialog::OnTVSelChanged(NMHDR*, LRESULT*) { HTREEITEM item = m_TreeCtrl.GetSelectedItem(); if (!item || m_TreeCtrl.ItemHasChildren(item)) { SetDlgItemText(IDC_DESCRIPTION, ""); } else { CSOLibrary::VectorClassData::iterator it = CSOLibrary::FindClass(m_TreeCtrl.GetItemText(item)); SetDlgItemText(IDC_DESCRIPTION, it->description); } if (m_bMultiple || !item) return; if (!m_TreeCtrl.ItemHasChildren(item)) { SetDlgItemText(IDCANCEL, "Cancel"); GetDlgItem(IDOK)->EnableWindow(TRUE); if (HTREEITEM old = FindItemInTreeCtrl(m_sSOClass)) m_TreeCtrl.SetItemState(old, 0, TVIS_BOLD); m_sSOClass = m_TreeCtrl.GetItemText(item); m_TreeCtrl.SetItemState(item, TVIS_BOLD, TVIS_BOLD); SetWindowText("Smart Object Class: " + m_sSOClass); } } BOOL CSmartObjectClassDialog::OnInitDialog() { CDialog::OnInitDialog(); if (m_bMultiple) { SetWindowText("Smart Object Classes"); SetDlgItemText(IDC_LISTCAPTION, "&Choose Smart Object Classes:"); //. m_wndClassList.ModifyStyle( 0, LBS_MULTIPLESEL ); } else { SetWindowText("Smart Object Class"); SetDlgItemText(IDC_LISTCAPTION, "&Choose Smart Object Class:"); //. m_wndClassList.ModifyStyle( LBS_MULTIPLESEL, 0 ); } //GetDlgItem( IDC_NEW )->EnableWindow( FALSE ); //GetDlgItem( IDEDIT )->EnableWindow( FALSE ); GetDlgItem(IDDELETE)->EnableWindow(FALSE); GetDlgItem(IDREFRESH)->EnableWindow(FALSE); //OnRefreshBtn(); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE } void CSmartObjectClassDialog::OnShowWindow(BOOL bShow, UINT nStatus) { if (bShow) PostMessage(WM_COMMAND, (BN_CLICKED << 16) | IDREFRESH, (LPARAM) GetDlgItem(IDREFRESH)->m_hWnd); } void CSmartObjectClassDialog::OnRefreshBtn() { m_TreeCtrl.UpdateWindow(); m_setClasses.clear(); if (m_bMultiple) { CString token; int i = 0; while (!(token = m_sSOClass.Tokenize(" !\"#$%&'()*+,-./:;<=>?@[\\]^`{|}~", i)).IsEmpty()) { if (CItemDescriptionDlg::ValidateItem(token)) { if (CSOLibrary::FindClass(token) == CSOLibrary::GetClasses().end()) CSOLibrary::AddClass(token, "", "", ""); m_setClasses.insert(token); } } } m_mapStringToItem.clear(); m_TreeCtrl.DeleteAllItems(); CSOLibrary::VectorClassData::iterator it, itEnd = CSOLibrary::GetClasses().end(); for (it = CSOLibrary::GetClasses().begin(); it != itEnd; ++it) AddItemInTreeCtrl(it->name, it->location); if (m_bMultiple) { m_sSOClass.Empty(); TSOClassesSet::iterator it, itEnd = m_setClasses.end(); for (it = m_setClasses.begin(); it != itEnd; ++it) { HTREEITEM item = FindItemInTreeCtrl(*it); m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); m_TreeCtrl.SetCheck(item, TRUE); assert(m_TreeCtrl.GetCheck(item)); m_TreeCtrl.SetItemState(item, TVIS_BOLD, TVIS_BOLD); if (!m_sSOClass.IsEmpty()) m_sSOClass += ", "; m_sSOClass += *it; } SetDlgItemText(IDC_SELECTIONLIST, m_sSOClass); } else { HTREEITEM item = FindItemInTreeCtrl(m_sSOClass); m_TreeCtrl.SetItemState(item, TVIS_BOLD, TVIS_BOLD); m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); } if (!m_bEnableOK) { SetDlgItemText(IDCANCEL, "Close"); GetDlgItem(IDOK)->EnableWindow(FALSE); } } void CSmartObjectClassDialog::UpdateListCurrentClasses() { m_sSOClass.Empty(); TSOClassesSet::iterator it, itEnd = m_setClasses.end(); for (it = m_setClasses.begin(); it != itEnd; ++it) { if (!m_sSOClass.IsEmpty()) m_sSOClass += ", "; m_sSOClass += *it; } SetDlgItemText(IDC_SELECTIONLIST, m_sSOClass); SetDlgItemText(IDCANCEL, "Cancel"); GetDlgItem(IDOK)->EnableWindow(TRUE); } void CSmartObjectClassDialog::OnEditBtn() { HTREEITEM item = m_TreeCtrl.GetSelectedItem(); if (!item || m_TreeCtrl.ItemHasChildren(item)) return; CString name = m_TreeCtrl.GetItemText(item); CSOLibrary::VectorClassData::iterator it = CSOLibrary::FindClass(name); assert(it != CSOLibrary::GetClasses().end()); CItemDescriptionDlg dlg(this, false, false, true, true); dlg.m_sCaption = "Edit Smart Object Class"; dlg.m_sItemCaption = "Class &name:"; dlg.m_sItemEdit = name; dlg.m_sDescription = it->description; dlg.m_sLocation = it->location; dlg.m_sTemplate = it->templateName; if (dlg.DoModal() == IDOK) { if (CSOLibrary::StartEditing()) { it->description = dlg.m_sDescription; if (it->location != dlg.m_sLocation) { it->location = dlg.m_sLocation; RemoveItemAndDummyParents(item); item = AddItemInTreeCtrl(name, dlg.m_sLocation); m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); } it->templateName = dlg.m_sTemplate; it->pClassTemplateData = dlg.m_sTemplate.IsEmpty() ? NULL : CSOLibrary::FindClassTemplate(dlg.m_sTemplate); SetDlgItemText(IDC_DESCRIPTION, dlg.m_sDescription); CSOLibrary::InvalidateSOEntities(); } } } void CSmartObjectClassDialog::OnNewBtn() { CItemDescriptionDlg dlg(this, true, false, true, true); dlg.m_sCaption = "New Class"; dlg.m_sItemCaption = "Class &name:"; dlg.m_sDescription = ""; dlg.m_sLocation = ""; dlg.m_sTemplate = ""; HTREEITEM current = m_TreeCtrl.GetSelectedItem(); while (current) { if (m_TreeCtrl.ItemHasChildren(current)) { if (!dlg.m_sLocation.IsEmpty()) dlg.m_sLocation = m_TreeCtrl.GetItemText(current) + '/' + dlg.m_sLocation; else dlg.m_sLocation = m_TreeCtrl.GetItemText(current); } current = m_TreeCtrl.GetParentItem(current); } if (dlg.DoModal() == IDOK && CSOLibrary::StartEditing()) { HTREEITEM item = FindItemInTreeCtrl(dlg.m_sItemEdit); if (item) { if (m_bMultiple) { m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); } else { //. m_sSOClass = dlg.m_sItemEdit; m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); } CQuestionDialog::SWarning(QObject::tr(""), QObject::tr("Entered class name already exists...\n\nA new class with the same name can not be created!")); } else { CSOLibrary::AddClass(dlg.m_sItemEdit, dlg.m_sDescription, dlg.m_sLocation, dlg.m_sTemplate); item = AddItemInTreeCtrl(dlg.m_sItemEdit, dlg.m_sLocation); if (m_bMultiple) { m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); //OnSelChanged(0,0); } else { //. m_sSOClass = dlg.m_sItemEdit; m_TreeCtrl.EnsureVisible(item); m_TreeCtrl.SelectItem(item); } } SetDlgItemText(IDCANCEL, "Cancel"); GetDlgItem(IDOK)->EnableWindow(TRUE); } } namespace { SResourceSelectionResult ShowDialog(const SResourceSelectorContext& context, const char* szPreviousValue) { CSmartObjectClassDialog soDlg(nullptr, true); soDlg.SetSOClass(szPreviousValue); bool accepted = soDlg.DoModal() == IDOK; SResourceSelectionResult result{ accepted, szPreviousValue }; if (accepted) { CString dialogResult = soDlg.GetSOClass(); result.selectedResource = (LPCSTR)dialogResult; } return result; } REGISTER_RESOURCE_SELECTOR("SmartObjectClasses", ShowDialog, "") }
{ "language": "C++" }
/////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2004, Industrial Light & Magic, a division of Lucas // Digital Ltd. LLC // // 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 Industrial Light & Magic 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. // /////////////////////////////////////////////////////////////////////////// //----------------------------------------------------------------------------- // // class TiledRgbaOutputFile // class TiledRgbaInputFile // //----------------------------------------------------------------------------- #include <ImfTiledRgbaFile.h> #include <ImfRgbaFile.h> #include <ImfTiledOutputFile.h> #include <ImfTiledInputFile.h> #include <ImfChannelList.h> #include <ImfTileDescriptionAttribute.h> #include <ImfStandardAttributes.h> #include <ImfRgbaYca.h> #include <ImfArray.h> #include "IlmThreadMutex.h" #include "Iex.h" namespace Imf { using namespace std; using namespace Imath; using namespace RgbaYca; using namespace IlmThread; namespace { void insertChannels (Header &header, RgbaChannels rgbaChannels, const char fileName[]) { ChannelList ch; if (rgbaChannels & (WRITE_Y | WRITE_C)) { if (rgbaChannels & WRITE_Y) { ch.insert ("Y", Channel (HALF, 1, 1)); } if (rgbaChannels & WRITE_C) { THROW (Iex::ArgExc, "Cannot open file \"" << fileName << "\" " "for writing. Tiled image files do not " "support subsampled chroma channels."); } } else { if (rgbaChannels & WRITE_R) ch.insert ("R", Channel (HALF, 1, 1)); if (rgbaChannels & WRITE_G) ch.insert ("G", Channel (HALF, 1, 1)); if (rgbaChannels & WRITE_B) ch.insert ("B", Channel (HALF, 1, 1)); } if (rgbaChannels & WRITE_A) ch.insert ("A", Channel (HALF, 1, 1)); header.channels() = ch; } RgbaChannels rgbaChannels (const ChannelList &ch, const string &channelNamePrefix = "") { int i = 0; if (ch.findChannel (channelNamePrefix + "R")) i |= WRITE_R; if (ch.findChannel (channelNamePrefix + "G")) i |= WRITE_G; if (ch.findChannel (channelNamePrefix + "B")) i |= WRITE_B; if (ch.findChannel (channelNamePrefix + "A")) i |= WRITE_A; if (ch.findChannel (channelNamePrefix + "Y")) i |= WRITE_Y; return RgbaChannels (i); } string prefixFromLayerName (const string &layerName, const Header &header) { if (layerName.empty()) return ""; if (hasMultiView (header) && multiView(header)[0] == layerName) return ""; return layerName + "."; } V3f ywFromHeader (const Header &header) { Chromaticities cr; if (hasChromaticities (header)) cr = chromaticities (header); return computeYw (cr); } } // namespace class TiledRgbaOutputFile::ToYa: public Mutex { public: ToYa (TiledOutputFile &outputFile, RgbaChannels rgbaChannels); void setFrameBuffer (const Rgba *base, size_t xStride, size_t yStride); void writeTile (int dx, int dy, int lx, int ly); private: TiledOutputFile & _outputFile; bool _writeA; unsigned int _tileXSize; unsigned int _tileYSize; V3f _yw; Array2D <Rgba> _buf; const Rgba * _fbBase; size_t _fbXStride; size_t _fbYStride; }; TiledRgbaOutputFile::ToYa::ToYa (TiledOutputFile &outputFile, RgbaChannels rgbaChannels) : _outputFile (outputFile) { _writeA = (rgbaChannels & WRITE_A)? true: false; const TileDescription &td = outputFile.header().tileDescription(); _tileXSize = td.xSize; _tileYSize = td.ySize; _yw = ywFromHeader (_outputFile.header()); _buf.resizeErase (_tileYSize, _tileXSize); _fbBase = 0; _fbXStride = 0; _fbYStride = 0; } void TiledRgbaOutputFile::ToYa::setFrameBuffer (const Rgba *base, size_t xStride, size_t yStride) { _fbBase = base; _fbXStride = xStride; _fbYStride = yStride; } void TiledRgbaOutputFile::ToYa::writeTile (int dx, int dy, int lx, int ly) { if (_fbBase == 0) { THROW (Iex::ArgExc, "No frame buffer was specified as the " "pixel data source for image file " "\"" << _outputFile.fileName() << "\"."); } // // Copy the tile's RGBA pixels into _buf and convert // them to luminance/alpha format // Box2i dw = _outputFile.dataWindowForTile (dx, dy, lx, ly); int width = dw.max.x - dw.min.x + 1; for (int y = dw.min.y, y1 = 0; y <= dw.max.y; ++y, ++y1) { for (int x = dw.min.x, x1 = 0; x <= dw.max.x; ++x, ++x1) _buf[y1][x1] = _fbBase[x * _fbXStride + y * _fbYStride]; RGBAtoYCA (_yw, width, _writeA, _buf[y1], _buf[y1]); } // // Store the contents of _buf in the output file // FrameBuffer fb; fb.insert ("Y", Slice (HALF, // type (char *) &_buf[-dw.min.y][-dw.min.x].g, // base sizeof (Rgba), // xStride sizeof (Rgba) * _tileXSize)); // yStride fb.insert ("A", Slice (HALF, // type (char *) &_buf[-dw.min.y][-dw.min.x].a, // base sizeof (Rgba), // xStride sizeof (Rgba) * _tileXSize)); // yStride _outputFile.setFrameBuffer (fb); _outputFile.writeTile (dx, dy, lx, ly); } TiledRgbaOutputFile::TiledRgbaOutputFile (const char name[], const Header &header, RgbaChannels rgbaChannels, int tileXSize, int tileYSize, LevelMode mode, LevelRoundingMode rmode, int numThreads) : _outputFile (0), _toYa (0) { Header hd (header); insertChannels (hd, rgbaChannels, name); hd.setTileDescription (TileDescription (tileXSize, tileYSize, mode, rmode)); _outputFile = new TiledOutputFile (name, hd, numThreads); if (rgbaChannels & WRITE_Y) _toYa = new ToYa (*_outputFile, rgbaChannels); } TiledRgbaOutputFile::TiledRgbaOutputFile (OStream &os, const Header &header, RgbaChannels rgbaChannels, int tileXSize, int tileYSize, LevelMode mode, LevelRoundingMode rmode, int numThreads) : _outputFile (0), _toYa (0) { Header hd (header); insertChannels (hd, rgbaChannels, os.fileName()); hd.setTileDescription (TileDescription (tileXSize, tileYSize, mode, rmode)); _outputFile = new TiledOutputFile (os, hd, numThreads); if (rgbaChannels & WRITE_Y) _toYa = new ToYa (*_outputFile, rgbaChannels); } TiledRgbaOutputFile::TiledRgbaOutputFile (const char name[], int tileXSize, int tileYSize, LevelMode mode, LevelRoundingMode rmode, const Imath::Box2i &displayWindow, const Imath::Box2i &dataWindow, RgbaChannels rgbaChannels, float pixelAspectRatio, const Imath::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _outputFile (0), _toYa (0) { Header hd (displayWindow, dataWindow.isEmpty()? displayWindow: dataWindow, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); insertChannels (hd, rgbaChannels, name); hd.setTileDescription (TileDescription (tileXSize, tileYSize, mode, rmode)); _outputFile = new TiledOutputFile (name, hd, numThreads); if (rgbaChannels & WRITE_Y) _toYa = new ToYa (*_outputFile, rgbaChannels); } TiledRgbaOutputFile::TiledRgbaOutputFile (const char name[], int width, int height, int tileXSize, int tileYSize, LevelMode mode, LevelRoundingMode rmode, RgbaChannels rgbaChannels, float pixelAspectRatio, const Imath::V2f screenWindowCenter, float screenWindowWidth, LineOrder lineOrder, Compression compression, int numThreads) : _outputFile (0), _toYa (0) { Header hd (width, height, pixelAspectRatio, screenWindowCenter, screenWindowWidth, lineOrder, compression); insertChannels (hd, rgbaChannels, name); hd.setTileDescription (TileDescription (tileXSize, tileYSize, mode, rmode)); _outputFile = new TiledOutputFile (name, hd, numThreads); if (rgbaChannels & WRITE_Y) _toYa = new ToYa (*_outputFile, rgbaChannels); } TiledRgbaOutputFile::~TiledRgbaOutputFile () { delete _outputFile; delete _toYa; } void TiledRgbaOutputFile::setFrameBuffer (const Rgba *base, size_t xStride, size_t yStride) { if (_toYa) { Lock lock (*_toYa); _toYa->setFrameBuffer (base, xStride, yStride); } else { size_t xs = xStride * sizeof (Rgba); size_t ys = yStride * sizeof (Rgba); FrameBuffer fb; fb.insert ("R", Slice (HALF, (char *) &base[0].r, xs, ys)); fb.insert ("G", Slice (HALF, (char *) &base[0].g, xs, ys)); fb.insert ("B", Slice (HALF, (char *) &base[0].b, xs, ys)); fb.insert ("A", Slice (HALF, (char *) &base[0].a, xs, ys)); _outputFile->setFrameBuffer (fb); } } const Header & TiledRgbaOutputFile::header () const { return _outputFile->header(); } const FrameBuffer & TiledRgbaOutputFile::frameBuffer () const { return _outputFile->frameBuffer(); } const Imath::Box2i & TiledRgbaOutputFile::displayWindow () const { return _outputFile->header().displayWindow(); } const Imath::Box2i & TiledRgbaOutputFile::dataWindow () const { return _outputFile->header().dataWindow(); } float TiledRgbaOutputFile::pixelAspectRatio () const { return _outputFile->header().pixelAspectRatio(); } const Imath::V2f TiledRgbaOutputFile::screenWindowCenter () const { return _outputFile->header().screenWindowCenter(); } float TiledRgbaOutputFile::screenWindowWidth () const { return _outputFile->header().screenWindowWidth(); } LineOrder TiledRgbaOutputFile::lineOrder () const { return _outputFile->header().lineOrder(); } Compression TiledRgbaOutputFile::compression () const { return _outputFile->header().compression(); } RgbaChannels TiledRgbaOutputFile::channels () const { return rgbaChannels (_outputFile->header().channels()); } unsigned int TiledRgbaOutputFile::tileXSize () const { return _outputFile->tileXSize(); } unsigned int TiledRgbaOutputFile::tileYSize () const { return _outputFile->tileYSize(); } LevelMode TiledRgbaOutputFile::levelMode () const { return _outputFile->levelMode(); } LevelRoundingMode TiledRgbaOutputFile::levelRoundingMode () const { return _outputFile->levelRoundingMode(); } int TiledRgbaOutputFile::numLevels () const { return _outputFile->numLevels(); } int TiledRgbaOutputFile::numXLevels () const { return _outputFile->numXLevels(); } int TiledRgbaOutputFile::numYLevels () const { return _outputFile->numYLevels(); } bool TiledRgbaOutputFile::isValidLevel (int lx, int ly) const { return _outputFile->isValidLevel (lx, ly); } int TiledRgbaOutputFile::levelWidth (int lx) const { return _outputFile->levelWidth (lx); } int TiledRgbaOutputFile::levelHeight (int ly) const { return _outputFile->levelHeight (ly); } int TiledRgbaOutputFile::numXTiles (int lx) const { return _outputFile->numXTiles (lx); } int TiledRgbaOutputFile::numYTiles (int ly) const { return _outputFile->numYTiles (ly); } Imath::Box2i TiledRgbaOutputFile::dataWindowForLevel (int l) const { return _outputFile->dataWindowForLevel (l); } Imath::Box2i TiledRgbaOutputFile::dataWindowForLevel (int lx, int ly) const { return _outputFile->dataWindowForLevel (lx, ly); } Imath::Box2i TiledRgbaOutputFile::dataWindowForTile (int dx, int dy, int l) const { return _outputFile->dataWindowForTile (dx, dy, l); } Imath::Box2i TiledRgbaOutputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { return _outputFile->dataWindowForTile (dx, dy, lx, ly); } void TiledRgbaOutputFile::writeTile (int dx, int dy, int l) { if (_toYa) { Lock lock (*_toYa); _toYa->writeTile (dx, dy, l, l); } else { _outputFile->writeTile (dx, dy, l); } } void TiledRgbaOutputFile::writeTile (int dx, int dy, int lx, int ly) { if (_toYa) { Lock lock (*_toYa); _toYa->writeTile (dx, dy, lx, ly); } else { _outputFile->writeTile (dx, dy, lx, ly); } } void TiledRgbaOutputFile::writeTiles (int dxMin, int dxMax, int dyMin, int dyMax, int lx, int ly) { if (_toYa) { Lock lock (*_toYa); for (int dy = dyMin; dy <= dyMax; dy++) for (int dx = dxMin; dx <= dxMax; dx++) _toYa->writeTile (dx, dy, lx, ly); } else { _outputFile->writeTiles (dxMin, dxMax, dyMin, dyMax, lx, ly); } } void TiledRgbaOutputFile::writeTiles (int dxMin, int dxMax, int dyMin, int dyMax, int l) { writeTiles (dxMin, dxMax, dyMin, dyMax, l, l); } class TiledRgbaInputFile::FromYa: public Mutex { public: FromYa (TiledInputFile &inputFile); void setFrameBuffer (Rgba *base, size_t xStride, size_t yStride, const string &channelNamePrefix); void readTile (int dx, int dy, int lx, int ly); private: TiledInputFile & _inputFile; unsigned int _tileXSize; unsigned int _tileYSize; V3f _yw; Array2D <Rgba> _buf; Rgba * _fbBase; size_t _fbXStride; size_t _fbYStride; }; TiledRgbaInputFile::FromYa::FromYa (TiledInputFile &inputFile) : _inputFile (inputFile) { const TileDescription &td = inputFile.header().tileDescription(); _tileXSize = td.xSize; _tileYSize = td.ySize; _yw = ywFromHeader (_inputFile.header()); _buf.resizeErase (_tileYSize, _tileXSize); _fbBase = 0; _fbXStride = 0; _fbYStride = 0; } void TiledRgbaInputFile::FromYa::setFrameBuffer (Rgba *base, size_t xStride, size_t yStride, const string &channelNamePrefix) { if (_fbBase == 0) { FrameBuffer fb; fb.insert (channelNamePrefix + "Y", Slice (HALF, // type (char *) &_buf[0][0].g, // base sizeof (Rgba), // xStride sizeof (Rgba) * _tileXSize, // yStride 1, 1, // sampling 0.0, // fillValue true, true)); // tileCoordinates fb.insert (channelNamePrefix + "A", Slice (HALF, // type (char *) &_buf[0][0].a, // base sizeof (Rgba), // xStride sizeof (Rgba) * _tileXSize, // yStride 1, 1, // sampling 1.0, // fillValue true, true)); // tileCoordinates _inputFile.setFrameBuffer (fb); } _fbBase = base; _fbXStride = xStride; _fbYStride = yStride; } void TiledRgbaInputFile::FromYa::readTile (int dx, int dy, int lx, int ly) { if (_fbBase == 0) { THROW (Iex::ArgExc, "No frame buffer was specified as the " "pixel data destination for image file " "\"" << _inputFile.fileName() << "\"."); } // // Read the tile requested by the caller into _buf. // _inputFile.readTile (dx, dy, lx, ly); // // Convert the luminance/alpha pixels to RGBA // and copy them into the caller's frame buffer. // Box2i dw = _inputFile.dataWindowForTile (dx, dy, lx, ly); int width = dw.max.x - dw.min.x + 1; for (int y = dw.min.y, y1 = 0; y <= dw.max.y; ++y, ++y1) { for (int x1 = 0; x1 < width; ++x1) { _buf[y1][x1].r = 0; _buf[y1][x1].b = 0; } YCAtoRGBA (_yw, width, _buf[y1], _buf[y1]); for (int x = dw.min.x, x1 = 0; x <= dw.max.x; ++x, ++x1) { _fbBase[x * _fbXStride + y * _fbYStride] = _buf[y1][x1]; } } } TiledRgbaInputFile::TiledRgbaInputFile (const char name[], int numThreads): _inputFile (new TiledInputFile (name, numThreads)), _fromYa (0), _channelNamePrefix ("") { if (channels() & WRITE_Y) _fromYa = new FromYa (*_inputFile); } TiledRgbaInputFile::TiledRgbaInputFile (IStream &is, int numThreads): _inputFile (new TiledInputFile (is, numThreads)), _fromYa (0), _channelNamePrefix ("") { if (channels() & WRITE_Y) _fromYa = new FromYa (*_inputFile); } TiledRgbaInputFile::TiledRgbaInputFile (const char name[], const string &layerName, int numThreads) : _inputFile (new TiledInputFile (name, numThreads)), _fromYa (0), _channelNamePrefix (prefixFromLayerName (layerName, _inputFile->header())) { if (channels() & WRITE_Y) _fromYa = new FromYa (*_inputFile); } TiledRgbaInputFile::TiledRgbaInputFile (IStream &is, const string &layerName, int numThreads) : _inputFile (new TiledInputFile (is, numThreads)), _fromYa (0), _channelNamePrefix (prefixFromLayerName (layerName, _inputFile->header())) { if (channels() & WRITE_Y) _fromYa = new FromYa (*_inputFile); } TiledRgbaInputFile::~TiledRgbaInputFile () { delete _inputFile; delete _fromYa; } void TiledRgbaInputFile::setFrameBuffer (Rgba *base, size_t xStride, size_t yStride) { if (_fromYa) { Lock lock (*_fromYa); _fromYa->setFrameBuffer (base, xStride, yStride, _channelNamePrefix); } else { size_t xs = xStride * sizeof (Rgba); size_t ys = yStride * sizeof (Rgba); FrameBuffer fb; fb.insert (_channelNamePrefix + "R", Slice (HALF, (char *) &base[0].r, xs, ys, 1, 1, // xSampling, ySampling 0.0)); // fillValue fb.insert (_channelNamePrefix + "G", Slice (HALF, (char *) &base[0].g, xs, ys, 1, 1, // xSampling, ySampling 0.0)); // fillValue fb.insert (_channelNamePrefix + "B", Slice (HALF, (char *) &base[0].b, xs, ys, 1, 1, // xSampling, ySampling 0.0)); // fillValue fb.insert (_channelNamePrefix + "A", Slice (HALF, (char *) &base[0].a, xs, ys, 1, 1, // xSampling, ySampling 1.0)); // fillValue _inputFile->setFrameBuffer (fb); } } void TiledRgbaInputFile::setLayerName (const std::string &layerName) { delete _fromYa; _fromYa = 0; _channelNamePrefix = prefixFromLayerName (layerName, _inputFile->header()); if (channels() & WRITE_Y) _fromYa = new FromYa (*_inputFile); FrameBuffer fb; _inputFile->setFrameBuffer (fb); } const Header & TiledRgbaInputFile::header () const { return _inputFile->header(); } const char * TiledRgbaInputFile::fileName () const { return _inputFile->fileName(); } const FrameBuffer & TiledRgbaInputFile::frameBuffer () const { return _inputFile->frameBuffer(); } const Imath::Box2i & TiledRgbaInputFile::displayWindow () const { return _inputFile->header().displayWindow(); } const Imath::Box2i & TiledRgbaInputFile::dataWindow () const { return _inputFile->header().dataWindow(); } float TiledRgbaInputFile::pixelAspectRatio () const { return _inputFile->header().pixelAspectRatio(); } const Imath::V2f TiledRgbaInputFile::screenWindowCenter () const { return _inputFile->header().screenWindowCenter(); } float TiledRgbaInputFile::screenWindowWidth () const { return _inputFile->header().screenWindowWidth(); } LineOrder TiledRgbaInputFile::lineOrder () const { return _inputFile->header().lineOrder(); } Compression TiledRgbaInputFile::compression () const { return _inputFile->header().compression(); } RgbaChannels TiledRgbaInputFile::channels () const { return rgbaChannels (_inputFile->header().channels(), _channelNamePrefix); } int TiledRgbaInputFile::version () const { return _inputFile->version(); } bool TiledRgbaInputFile::isComplete () const { return _inputFile->isComplete(); } unsigned int TiledRgbaInputFile::tileXSize () const { return _inputFile->tileXSize(); } unsigned int TiledRgbaInputFile::tileYSize () const { return _inputFile->tileYSize(); } LevelMode TiledRgbaInputFile::levelMode () const { return _inputFile->levelMode(); } LevelRoundingMode TiledRgbaInputFile::levelRoundingMode () const { return _inputFile->levelRoundingMode(); } int TiledRgbaInputFile::numLevels () const { return _inputFile->numLevels(); } int TiledRgbaInputFile::numXLevels () const { return _inputFile->numXLevels(); } int TiledRgbaInputFile::numYLevels () const { return _inputFile->numYLevels(); } bool TiledRgbaInputFile::isValidLevel (int lx, int ly) const { return _inputFile->isValidLevel (lx, ly); } int TiledRgbaInputFile::levelWidth (int lx) const { return _inputFile->levelWidth (lx); } int TiledRgbaInputFile::levelHeight (int ly) const { return _inputFile->levelHeight (ly); } int TiledRgbaInputFile::numXTiles (int lx) const { return _inputFile->numXTiles(lx); } int TiledRgbaInputFile::numYTiles (int ly) const { return _inputFile->numYTiles(ly); } Imath::Box2i TiledRgbaInputFile::dataWindowForLevel (int l) const { return _inputFile->dataWindowForLevel (l); } Imath::Box2i TiledRgbaInputFile::dataWindowForLevel (int lx, int ly) const { return _inputFile->dataWindowForLevel (lx, ly); } Imath::Box2i TiledRgbaInputFile::dataWindowForTile (int dx, int dy, int l) const { return _inputFile->dataWindowForTile (dx, dy, l); } Imath::Box2i TiledRgbaInputFile::dataWindowForTile (int dx, int dy, int lx, int ly) const { return _inputFile->dataWindowForTile (dx, dy, lx, ly); } void TiledRgbaInputFile::readTile (int dx, int dy, int l) { if (_fromYa) { Lock lock (*_fromYa); _fromYa->readTile (dx, dy, l, l); } else { _inputFile->readTile (dx, dy, l); } } void TiledRgbaInputFile::readTile (int dx, int dy, int lx, int ly) { if (_fromYa) { Lock lock (*_fromYa); _fromYa->readTile (dx, dy, lx, ly); } else { _inputFile->readTile (dx, dy, lx, ly); } } void TiledRgbaInputFile::readTiles (int dxMin, int dxMax, int dyMin, int dyMax, int lx, int ly) { if (_fromYa) { Lock lock (*_fromYa); for (int dy = dyMin; dy <= dyMax; dy++) for (int dx = dxMin; dx <= dxMax; dx++) _fromYa->readTile (dx, dy, lx, ly); } else { _inputFile->readTiles (dxMin, dxMax, dyMin, dyMax, lx, ly); } } void TiledRgbaInputFile::readTiles (int dxMin, int dxMax, int dyMin, int dyMax, int l) { readTiles (dxMin, dxMax, dyMin, dyMax, l, l); } void TiledRgbaOutputFile::updatePreviewImage (const PreviewRgba newPixels[]) { _outputFile->updatePreviewImage (newPixels); } void TiledRgbaOutputFile::breakTile (int dx, int dy, int lx, int ly, int offset, int length, char c) { _outputFile->breakTile (dx, dy, lx, ly, offset, length, c); } } // namespace Imf
{ "language": "C++" }
// 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. #ifndef NET_HTTP_HTTP_AUTH_HANDLER_DIGEST_H_ #define NET_HTTP_HTTP_AUTH_HANDLER_DIGEST_H_ #include <string> #include "base/basictypes.h" #include "base/gtest_prod_util.h" #include "base/memory/scoped_ptr.h" #include "net/base/net_export.h" #include "net/http/http_auth_handler.h" #include "net/http/http_auth_handler_factory.h" namespace net { // Code for handling http digest authentication. class NET_EXPORT_PRIVATE HttpAuthHandlerDigest : public HttpAuthHandler { public: // A NonceGenerator is a simple interface for generating client nonces. // Unit tests can override the default client nonce behavior with fixed // nonce generation to get reproducible results. class NET_EXPORT_PRIVATE NonceGenerator { public: NonceGenerator(); virtual ~NonceGenerator(); // Generates a client nonce. virtual std::string GenerateNonce() const = 0; private: DISALLOW_COPY_AND_ASSIGN(NonceGenerator); }; // DynamicNonceGenerator does a random shuffle of 16 // characters to generate a client nonce. class DynamicNonceGenerator : public NonceGenerator { public: DynamicNonceGenerator(); virtual std::string GenerateNonce() const OVERRIDE; private: DISALLOW_COPY_AND_ASSIGN(DynamicNonceGenerator); }; // FixedNonceGenerator always uses the same string specified at // construction time as the client nonce. class NET_EXPORT_PRIVATE FixedNonceGenerator : public NonceGenerator { public: explicit FixedNonceGenerator(const std::string& nonce); virtual std::string GenerateNonce() const OVERRIDE; private: const std::string nonce_; DISALLOW_COPY_AND_ASSIGN(FixedNonceGenerator); }; class NET_EXPORT_PRIVATE Factory : public HttpAuthHandlerFactory { public: Factory(); virtual ~Factory(); // This factory owns the passed in |nonce_generator|. void set_nonce_generator(const NonceGenerator* nonce_generator); virtual int CreateAuthHandler( HttpAuth::ChallengeTokenizer* challenge, HttpAuth::Target target, const GURL& origin, CreateReason reason, int digest_nonce_count, const BoundNetLog& net_log, scoped_ptr<HttpAuthHandler>* handler) OVERRIDE; private: scoped_ptr<const NonceGenerator> nonce_generator_; }; virtual HttpAuth::AuthorizationResult HandleAnotherChallenge( HttpAuth::ChallengeTokenizer* challenge) OVERRIDE; protected: virtual bool Init(HttpAuth::ChallengeTokenizer* challenge) OVERRIDE; virtual int GenerateAuthTokenImpl(const AuthCredentials* credentials, const HttpRequestInfo* request, const CompletionCallback& callback, std::string* auth_token) OVERRIDE; private: FRIEND_TEST_ALL_PREFIXES(HttpAuthHandlerDigestTest, ParseChallenge); FRIEND_TEST_ALL_PREFIXES(HttpAuthHandlerDigestTest, AssembleCredentials); FRIEND_TEST_ALL_PREFIXES(HttpNetworkTransactionTest, DigestPreAuthNonceCount); // Possible values for the "algorithm" property. enum DigestAlgorithm { // No algorithm was specified. According to RFC 2617 this means // we should default to ALGORITHM_MD5. ALGORITHM_UNSPECIFIED, // Hashes are run for every request. ALGORITHM_MD5, // Hash is run only once during the first WWW-Authenticate handshake. // (SESS means session). ALGORITHM_MD5_SESS, }; // Possible values for QualityOfProtection. // auth-int is not supported, see http://crbug.com/62890 for justification. enum QualityOfProtection { QOP_UNSPECIFIED, QOP_AUTH, }; // |nonce_count| indicates how many times the server-specified nonce has // been used so far. // |nonce_generator| is used to create a client nonce, and is not owned by // the handler. The lifetime of the |nonce_generator| must exceed that of this // handler. HttpAuthHandlerDigest(int nonce_count, const NonceGenerator* nonce_generator); virtual ~HttpAuthHandlerDigest(); // Parse the challenge, saving the results into this instance. // Returns true on success. bool ParseChallenge(HttpAuth::ChallengeTokenizer* challenge); // Parse an individual property. Returns true on success. bool ParseChallengeProperty(const std::string& name, const std::string& value); // Generates a random string, to be used for client-nonce. static std::string GenerateNonce(); // Convert enum value back to string. static std::string QopToString(QualityOfProtection qop); static std::string AlgorithmToString(DigestAlgorithm algorithm); // Extract the method and path of the request, as needed by // the 'A2' production. (path may be a hostname for proxy). void GetRequestMethodAndPath(const HttpRequestInfo* request, std::string* method, std::string* path) const; // Build up the 'response' production. std::string AssembleResponseDigest(const std::string& method, const std::string& path, const AuthCredentials& credentials, const std::string& cnonce, const std::string& nc) const; // Build up the value for (Authorization/Proxy-Authorization). std::string AssembleCredentials(const std::string& method, const std::string& path, const AuthCredentials& credentials, const std::string& cnonce, int nonce_count) const; // Information parsed from the challenge. std::string nonce_; std::string domain_; std::string opaque_; bool stale_; DigestAlgorithm algorithm_; QualityOfProtection qop_; // The realm as initially encoded over-the-wire. This is used in the // challenge text, rather than |realm_| which has been converted to // UTF-8. std::string original_realm_; int nonce_count_; const NonceGenerator* nonce_generator_; }; } // namespace net #endif // NET_HTTP_HTTP_AUTH_HANDLER_DIGEST_H_
{ "language": "C++" }
/**CFile**************************************************************** FileName [sim.h] SystemName [ABC: Logic synthesis and verification system.] PackageName [Simulation package.] Synopsis [External declarations.] Author [Alan Mishchenko] Affiliation [UC Berkeley] Date [Ver. 1.0. Started - June 20, 2005.] Revision [$Id: sim.h,v 1.00 2005/06/20 00:00:00 alanmi Exp $] ***********************************************************************/ #ifndef ABC__opt__sim__sim_h #define ABC__opt__sim__sim_h /* The ideas realized in this package are described in the paper: "Detecting Symmetries in Boolean Functions using Circuit Representation, Simulation, and Satisfiability". */ //////////////////////////////////////////////////////////////////////// /// INCLUDES /// //////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////// /// PARAMETERS /// //////////////////////////////////////////////////////////////////////// ABC_NAMESPACE_HEADER_START //////////////////////////////////////////////////////////////////////// /// BASIC TYPES /// //////////////////////////////////////////////////////////////////////// typedef struct Sym_Man_t_ Sym_Man_t; struct Sym_Man_t_ { // info about the network Abc_Ntk_t * pNtk; // the network Vec_Ptr_t * vNodes; // internal nodes in topological order int nInputs; int nOutputs; // internal simulation information int nSimWords; // the number of bits in simulation info Vec_Ptr_t * vSim; // simulation info // support information Vec_Ptr_t * vSuppFun; // bit representation Vec_Vec_t * vSupports; // integer representation // symmetry info for each output Vec_Ptr_t * vMatrSymms; // symmetric pairs Vec_Ptr_t * vMatrNonSymms; // non-symmetric pairs Vec_Int_t * vPairsTotal; // total pairs Vec_Int_t * vPairsSym; // symmetric pairs Vec_Int_t * vPairsNonSym; // non-symmetric pairs // temporary simulation info unsigned * uPatRand; unsigned * uPatCol; unsigned * uPatRow; // temporary Vec_Int_t * vVarsU; Vec_Int_t * vVarsV; int iOutput; int iVar1; int iVar2; int iVar1Old; int iVar2Old; // internal data structures int nSatRuns; int nSatRunsSat; int nSatRunsUnsat; // pairs int nPairsSymm; int nPairsSymmStr; int nPairsNonSymm; int nPairsRem; int nPairsTotal; // runtime statistics abctime timeStruct; abctime timeCount; abctime timeMatr; abctime timeSim; abctime timeFraig; abctime timeSat; abctime timeTotal; }; typedef struct Sim_Man_t_ Sim_Man_t; struct Sim_Man_t_ { // info about the network Abc_Ntk_t * pNtk; int nInputs; int nOutputs; int fLightweight; // internal simulation information int nSimBits; // the number of bits in simulation info int nSimWords; // the number of words in simulation info Vec_Ptr_t * vSim0; // simulation info 1 Vec_Ptr_t * vSim1; // simulation info 2 // support information int nSuppBits; // the number of bits in support info int nSuppWords; // the number of words in support info Vec_Ptr_t * vSuppStr; // structural supports Vec_Ptr_t * vSuppFun; // functional supports // simulation targets Vec_Vec_t * vSuppTargs; // support targets int iInput; // the input current processed // internal data structures Extra_MmFixed_t * pMmPat; Vec_Ptr_t * vFifo; Vec_Int_t * vDiffs; int nSatRuns; int nSatRunsSat; int nSatRunsUnsat; // runtime statistics abctime timeSim; abctime timeTrav; abctime timeFraig; abctime timeSat; abctime timeTotal; }; typedef struct Sim_Pat_t_ Sim_Pat_t; struct Sim_Pat_t_ { int Input; // the input which it has detected int Output; // the output for which it was collected unsigned * pData; // the simulation data }; //////////////////////////////////////////////////////////////////////// /// MACRO DEFINITIONS /// //////////////////////////////////////////////////////////////////////// #define SIM_NUM_WORDS(n) (((n)>>5) + (((n)&31) > 0)) #define SIM_LAST_BITS(n) ((((n)&31) > 0)? (n)&31 : 32) #define SIM_MASK_FULL (0xFFFFFFFF) #define SIM_MASK_BEG(n) (SIM_MASK_FULL >> (32-n)) #define SIM_MASK_END(n) (SIM_MASK_FULL << (n)) #define SIM_SET_0_FROM(m,n) ((m) & ~SIM_MASK_BEG(n)) #define SIM_SET_1_FROM(m,n) ((m) | SIM_MASK_END(n)) // generating random unsigned (#define RAND_MAX 0x7fff) #define SIM_RANDOM_UNSIGNED ((((unsigned)rand()) << 24) ^ (((unsigned)rand()) << 12) ^ ((unsigned)rand())) // macros to get hold of bits in a bit string #define Sim_SetBit(p,i) ((p)[(i)>>5] |= (1<<((i) & 31))) #define Sim_XorBit(p,i) ((p)[(i)>>5] ^= (1<<((i) & 31))) #define Sim_HasBit(p,i) (((p)[(i)>>5] & (1<<((i) & 31))) > 0) // macros to get hold of the support info #define Sim_SuppStrSetVar(vSupps,pNode,v) Sim_SetBit((unsigned*)(vSupps)->pArray[(pNode)->Id],(v)) #define Sim_SuppStrHasVar(vSupps,pNode,v) Sim_HasBit((unsigned*)(vSupps)->pArray[(pNode)->Id],(v)) #define Sim_SuppFunSetVar(vSupps,Output,v) Sim_SetBit((unsigned*)(vSupps)->pArray[Output],(v)) #define Sim_SuppFunHasVar(vSupps,Output,v) Sim_HasBit((unsigned*)(vSupps)->pArray[Output],(v)) #define Sim_SimInfoSetVar(vSupps,pNode,v) Sim_SetBit((unsigned*)(vSupps)->pArray[(pNode)->Id],(v)) #define Sim_SimInfoHasVar(vSupps,pNode,v) Sim_HasBit((unsigned*)(vSupps)->pArray[(pNode)->Id],(v)) #define Sim_SimInfoGet(vInfo,pNode) ((unsigned *)((vInfo)->pArray[(pNode)->Id])) //////////////////////////////////////////////////////////////////////// /// FUNCTION DECLARATIONS /// //////////////////////////////////////////////////////////////////////// /*=== simMan.c ==========================================================*/ extern Sym_Man_t * Sym_ManStart( Abc_Ntk_t * pNtk, int fVerbose ); extern void Sym_ManStop( Sym_Man_t * p ); extern void Sym_ManPrintStats( Sym_Man_t * p ); extern Sim_Man_t * Sim_ManStart( Abc_Ntk_t * pNtk, int fLightweight ); extern void Sim_ManStop( Sim_Man_t * p ); extern void Sim_ManPrintStats( Sim_Man_t * p ); extern Sim_Pat_t * Sim_ManPatAlloc( Sim_Man_t * p ); extern void Sim_ManPatFree( Sim_Man_t * p, Sim_Pat_t * pPat ); /*=== simSeq.c ==========================================================*/ extern Vec_Ptr_t * Sim_SimulateSeqRandom( Abc_Ntk_t * pNtk, int nFrames, int nWords ); extern Vec_Ptr_t * Sim_SimulateSeqModel( Abc_Ntk_t * pNtk, int nFrames, int * pModel ); /*=== simSupp.c ==========================================================*/ extern Vec_Ptr_t * Sim_ComputeStrSupp( Abc_Ntk_t * pNtk ); extern Vec_Ptr_t * Sim_ComputeFunSupp( Abc_Ntk_t * pNtk, int fVerbose ); /*=== simSym.c ==========================================================*/ extern int Sim_ComputeTwoVarSymms( Abc_Ntk_t * pNtk, int fVerbose ); /*=== simSymSat.c ==========================================================*/ extern int Sim_SymmsGetPatternUsingSat( Sym_Man_t * p, unsigned * pPattern ); /*=== simSymStr.c ==========================================================*/ extern void Sim_SymmsStructCompute( Abc_Ntk_t * pNtk, Vec_Ptr_t * vMatrs, Vec_Ptr_t * vSuppFun ); /*=== simSymSim.c ==========================================================*/ extern void Sim_SymmsSimulate( Sym_Man_t * p, unsigned * pPatRand, Vec_Ptr_t * vMatrsNonSym ); /*=== simUtil.c ==========================================================*/ extern Vec_Ptr_t * Sim_UtilInfoAlloc( int nSize, int nWords, int fClean ); extern void Sim_UtilInfoFree( Vec_Ptr_t * p ); extern void Sim_UtilInfoAdd( unsigned * pInfo1, unsigned * pInfo2, int nWords ); extern void Sim_UtilInfoDetectDiffs( unsigned * pInfo1, unsigned * pInfo2, int nWords, Vec_Int_t * vDiffs ); extern void Sim_UtilInfoDetectNews( unsigned * pInfo1, unsigned * pInfo2, int nWords, Vec_Int_t * vDiffs ); extern void Sim_UtilInfoFlip( Sim_Man_t * p, Abc_Obj_t * pNode ); extern int Sim_UtilInfoCompare( Sim_Man_t * p, Abc_Obj_t * pNode ); extern void Sim_UtilSimulate( Sim_Man_t * p, int fFirst ); extern void Sim_UtilSimulateNode( Sim_Man_t * p, Abc_Obj_t * pNode, int fType, int fType1, int fType2 ); extern void Sim_UtilSimulateNodeOne( Abc_Obj_t * pNode, Vec_Ptr_t * vSimInfo, int nSimWords, int nOffset ); extern void Sim_UtilTransferNodeOne( Abc_Obj_t * pNode, Vec_Ptr_t * vSimInfo, int nSimWords, int nOffset, int fShift ); extern int Sim_UtilCountSuppSizes( Sim_Man_t * p, int fStruct ); extern int Sim_UtilCountOnes( unsigned * pSimInfo, int nSimWords ); extern Vec_Int_t * Sim_UtilCountOnesArray( Vec_Ptr_t * vInfo, int nSimWords ); extern void Sim_UtilSetRandom( unsigned * pPatRand, int nSimWords ); extern void Sim_UtilSetCompl( unsigned * pPatRand, int nSimWords ); extern void Sim_UtilSetConst( unsigned * pPatRand, int nSimWords, int fConst1 ); extern int Sim_UtilInfoIsEqual( unsigned * pPats1, unsigned * pPats2, int nSimWords ); extern int Sim_UtilInfoIsImp( unsigned * pPats1, unsigned * pPats2, int nSimWords ); extern int Sim_UtilInfoIsClause( unsigned * pPats1, unsigned * pPats2, int nSimWords ); extern int Sim_UtilCountAllPairs( Vec_Ptr_t * vSuppFun, int nSimWords, Vec_Int_t * vCounters ); extern void Sim_UtilCountPairsAll( Sym_Man_t * p ); extern int Sim_UtilMatrsAreDisjoint( Sym_Man_t * p ); ABC_NAMESPACE_HEADER_END #endif //////////////////////////////////////////////////////////////////////// /// END OF FILE /// ////////////////////////////////////////////////////////////////////////
{ "language": "C++" }
#include <robin_hood.h> #include <app/CtorDtorVerifier.h> #include <app/doctest.h> #include <app/randomseed.h> #include <app/sfc64.h> #include <unordered_map> #include <utility> TYPE_TO_STRING(robin_hood::unordered_flat_map<CtorDtorVerifier, CtorDtorVerifier>); TYPE_TO_STRING(robin_hood::unordered_node_map<CtorDtorVerifier, CtorDtorVerifier>); TEST_CASE_TEMPLATE("multiple_different_APIs" * doctest::test_suite("stochastic"), Map, robin_hood::unordered_flat_map<CtorDtorVerifier, CtorDtorVerifier>, robin_hood::unordered_node_map<CtorDtorVerifier, CtorDtorVerifier>) { Map rhhs; REQUIRE(rhhs.size() == static_cast<size_t>(0)); std::pair<typename Map::iterator, bool> it_outer = rhhs.insert(typename Map::value_type{UINT64_C(32145), UINT64_C(123)}); REQUIRE(it_outer.second); REQUIRE(it_outer.first->first.val() == 32145); REQUIRE(it_outer.first->second.val() == 123); REQUIRE(rhhs.size() == 1); const uint64_t times = 10000; for (uint64_t i = 0; i < times; ++i) { INFO(i); std::pair<typename Map::iterator, bool> it_inner = rhhs.insert(typename Map::value_type(i * 4, i)); REQUIRE(it_inner.second); REQUIRE(it_inner.first->first.val() == i * 4); REQUIRE(it_inner.first->second.val() == i); typename Map::iterator found = rhhs.find(i * 4); REQUIRE(rhhs.end() != found); REQUIRE(found->second.val() == i); REQUIRE(rhhs.size() == 2 + i); } // check if everything can be found for (uint64_t i = 0; i < times; ++i) { typename Map::iterator found = rhhs.find(i * 4); REQUIRE(rhhs.end() != found); REQUIRE(found->second.val() == i); REQUIRE(found->first.val() == i * 4); } // check non-elements for (uint64_t i = 0; i < times; ++i) { typename Map::iterator found = rhhs.find((i + times) * 4); REQUIRE(rhhs.end() == found); } // random test against std::unordered_map rhhs.clear(); std::unordered_map<uint64_t, uint64_t> uo; auto seed = randomseed(); INFO("seed=" << seed); sfc64 gen(seed); for (uint64_t i = 0; i < times; ++i) { auto r = gen(times / 4); auto rhh_it = rhhs.insert(typename Map::value_type(r, r * 2)); auto uo_it = uo.insert(std::make_pair(r, r * 2)); REQUIRE(rhh_it.second == uo_it.second); REQUIRE(rhh_it.first->first.val() == uo_it.first->first); REQUIRE(rhh_it.first->second.val() == uo_it.first->second); REQUIRE(rhhs.size() == uo.size()); r = gen(times / 4); typename Map::iterator rhhsIt = rhhs.find(r); auto uoIt = uo.find(r); REQUIRE((rhhs.end() == rhhsIt) == (uo.end() == uoIt)); if (rhhs.end() != rhhsIt) { REQUIRE(rhhsIt->first.val() == uoIt->first); REQUIRE(rhhsIt->second.val() == uoIt->second); } } uo.clear(); rhhs.clear(); for (uint64_t i = 0; i < times; ++i) { const auto r = gen(times / 4); rhhs[r] = r * 2; uo[r] = r * 2; REQUIRE(rhhs.find(r)->second.val() == uo.find(r)->second); REQUIRE(rhhs.size() == uo.size()); } std::size_t numChecks = 0; for (typename Map::const_iterator it = rhhs.begin(); it != rhhs.end(); ++it) { REQUIRE(uo.end() != uo.find(it->first.val())); ++numChecks; } REQUIRE(rhhs.size() == numChecks); numChecks = 0; const Map& constRhhs = rhhs; for (const typename Map::value_type& vt : constRhhs) { REQUIRE(uo.end() != uo.find(vt.first.val())); ++numChecks; } REQUIRE(rhhs.size() == numChecks); }
{ "language": "C++" }
/* * Copyright (C) 2010 Google Inc. All rights reserved. * Copyright (C) 2016 Apple 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: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. 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. */ #pragma once #include "ActiveDOMObject.h" #include "AsyncAudioDecoder.h" #include "AudioBus.h" #include "AudioDestinationNode.h" #include "EventTarget.h" #include "JSDOMPromiseDeferred.h" #include "MediaCanStartListener.h" #include "MediaProducer.h" #include "PlatformMediaSession.h" #include "VisibilityChangeClient.h" #include <JavaScriptCore/Float32Array.h> #include <atomic> #include <wtf/HashSet.h> #include <wtf/MainThread.h> #include <wtf/RefPtr.h> #include <wtf/ThreadSafeRefCounted.h> #include <wtf/Threading.h> #include <wtf/Vector.h> #include <wtf/text/AtomicStringHash.h> namespace WebCore { class AnalyserNode; class AudioBuffer; class AudioBufferCallback; class AudioBufferSourceNode; class AudioListener; class AudioSummingJunction; class BiquadFilterNode; class ChannelMergerNode; class ChannelSplitterNode; class ConvolverNode; class DelayNode; class Document; class DynamicsCompressorNode; class GainNode; class GenericEventQueue; class HTMLMediaElement; class MediaElementAudioSourceNode; class MediaStream; class MediaStreamAudioDestinationNode; class MediaStreamAudioSourceNode; class OscillatorNode; class PannerNode; class PeriodicWave; class ScriptProcessorNode; class WaveShaperNode; // AudioContext is the cornerstone of the web audio API and all AudioNodes are created from it. // For thread safety between the audio thread and the main thread, it has a rendering graph locking mechanism. class AudioContext : public ActiveDOMObject, public ThreadSafeRefCounted<AudioContext>, public EventTargetWithInlineData, public MediaCanStartListener, public MediaProducer, private PlatformMediaSessionClient, private VisibilityChangeClient { public: // Create an AudioContext for rendering to the audio hardware. static RefPtr<AudioContext> create(Document&); virtual ~AudioContext(); bool isInitialized() const; bool isOfflineContext() const { return m_isOfflineContext; } Document* document() const; // ASSERTs if document no longer exists. Document* hostingDocument() const final; AudioDestinationNode* destination() { return m_destinationNode.get(); } size_t currentSampleFrame() const { return m_destinationNode->currentSampleFrame(); } double currentTime() const { return m_destinationNode->currentTime(); } float sampleRate() const { return m_destinationNode->sampleRate(); } unsigned long activeSourceCount() const { return static_cast<unsigned long>(m_activeSourceCount); } void incrementActiveSourceCount(); void decrementActiveSourceCount(); ExceptionOr<Ref<AudioBuffer>> createBuffer(unsigned numberOfChannels, size_t numberOfFrames, float sampleRate); ExceptionOr<Ref<AudioBuffer>> createBuffer(ArrayBuffer&, bool mixToMono); // Asynchronous audio file data decoding. void decodeAudioData(Ref<ArrayBuffer>&&, RefPtr<AudioBufferCallback>&&, RefPtr<AudioBufferCallback>&&); AudioListener* listener() { return m_listener.get(); } using ActiveDOMObject::suspend; using ActiveDOMObject::resume; void suspend(DOMPromiseDeferred<void>&&); void resume(DOMPromiseDeferred<void>&&); void close(DOMPromiseDeferred<void>&&); enum class State { Suspended, Running, Interrupted, Closed }; State state() const; bool wouldTaintOrigin(const URL&) const; // The AudioNode create methods are called on the main thread (from JavaScript). Ref<AudioBufferSourceNode> createBufferSource(); #if ENABLE(VIDEO) ExceptionOr<Ref<MediaElementAudioSourceNode>> createMediaElementSource(HTMLMediaElement&); #endif #if ENABLE(MEDIA_STREAM) ExceptionOr<Ref<MediaStreamAudioSourceNode>> createMediaStreamSource(MediaStream&); Ref<MediaStreamAudioDestinationNode> createMediaStreamDestination(); #endif Ref<GainNode> createGain(); Ref<BiquadFilterNode> createBiquadFilter(); Ref<WaveShaperNode> createWaveShaper(); ExceptionOr<Ref<DelayNode>> createDelay(double maxDelayTime); Ref<PannerNode> createPanner(); Ref<ConvolverNode> createConvolver(); Ref<DynamicsCompressorNode> createDynamicsCompressor(); Ref<AnalyserNode> createAnalyser(); ExceptionOr<Ref<ScriptProcessorNode>> createScriptProcessor(size_t bufferSize, size_t numberOfInputChannels, size_t numberOfOutputChannels); ExceptionOr<Ref<ChannelSplitterNode>> createChannelSplitter(size_t numberOfOutputs); ExceptionOr<Ref<ChannelMergerNode>> createChannelMerger(size_t numberOfInputs); Ref<OscillatorNode> createOscillator(); ExceptionOr<Ref<PeriodicWave>> createPeriodicWave(Float32Array& real, Float32Array& imaginary); // When a source node has no more processing to do (has finished playing), then it tells the context to dereference it. void notifyNodeFinishedProcessing(AudioNode*); // Called at the start of each render quantum. void handlePreRenderTasks(); // Called at the end of each render quantum. void handlePostRenderTasks(); // Called periodically at the end of each render quantum to dereference finished source nodes. void derefFinishedSourceNodes(); // We schedule deletion of all marked nodes at the end of each realtime render quantum. void markForDeletion(AudioNode&); void deleteMarkedNodes(); // AudioContext can pull node(s) at the end of each render quantum even when they are not connected to any downstream nodes. // These two methods are called by the nodes who want to add/remove themselves into/from the automatic pull lists. void addAutomaticPullNode(AudioNode&); void removeAutomaticPullNode(AudioNode&); // Called right before handlePostRenderTasks() to handle nodes which need to be pulled even when they are not connected to anything. void processAutomaticPullNodes(size_t framesToProcess); // Keeps track of the number of connections made. void incrementConnectionCount() { ASSERT(isMainThread()); m_connectionCount++; } unsigned connectionCount() const { return m_connectionCount; } // // Thread Safety and Graph Locking: // void setAudioThread(Thread& thread) { m_audioThread = &thread; } // FIXME: check either not initialized or the same Thread* audioThread() const { return m_audioThread; } bool isAudioThread() const; // Returns true only after the audio thread has been started and then shutdown. bool isAudioThreadFinished() { return m_isAudioThreadFinished; } // mustReleaseLock is set to true if we acquired the lock in this method call and caller must unlock(), false if it was previously acquired. void lock(bool& mustReleaseLock); // Returns true if we own the lock. // mustReleaseLock is set to true if we acquired the lock in this method call and caller must unlock(), false if it was previously acquired. bool tryLock(bool& mustReleaseLock); void unlock(); // Returns true if this thread owns the context's lock. bool isGraphOwner() const; // Returns the maximum number of channels we can support. static unsigned maxNumberOfChannels() { return MaxNumberOfChannels; } class AutoLocker { public: explicit AutoLocker(AudioContext& context) : m_context(context) { m_context.lock(m_mustReleaseLock); } ~AutoLocker() { if (m_mustReleaseLock) m_context.unlock(); } private: AudioContext& m_context; bool m_mustReleaseLock; }; // In AudioNode::deref() a tryLock() is used for calling finishDeref(), but if it fails keep track here. void addDeferredFinishDeref(AudioNode*); // In the audio thread at the start of each render cycle, we'll call handleDeferredFinishDerefs(). void handleDeferredFinishDerefs(); // Only accessed when the graph lock is held. void markSummingJunctionDirty(AudioSummingJunction*); void markAudioNodeOutputDirty(AudioNodeOutput*); // Must be called on main thread. void removeMarkedSummingJunction(AudioSummingJunction*); // EventTarget EventTargetInterface eventTargetInterface() const final { return AudioContextEventTargetInterfaceType; } ScriptExecutionContext* scriptExecutionContext() const final; // Reconcile ref/deref which are defined both in ThreadSafeRefCounted and EventTarget. using ThreadSafeRefCounted::ref; using ThreadSafeRefCounted::deref; void startRendering(); void fireCompletionEvent(); static unsigned s_hardwareContextCount; // Restrictions to change default behaviors. enum BehaviorRestrictionFlags { NoRestrictions = 0, RequireUserGestureForAudioStartRestriction = 1 << 0, RequirePageConsentForAudioStartRestriction = 1 << 1, }; typedef unsigned BehaviorRestrictions; BehaviorRestrictions behaviorRestrictions() const { return m_restrictions; } void addBehaviorRestriction(BehaviorRestrictions restriction) { m_restrictions |= restriction; } void removeBehaviorRestriction(BehaviorRestrictions restriction) { m_restrictions &= ~restriction; } void isPlayingAudioDidChange(); void nodeWillBeginPlayback(); protected: explicit AudioContext(Document&); AudioContext(Document&, unsigned numberOfChannels, size_t numberOfFrames, float sampleRate); static bool isSampleRateRangeGood(float sampleRate); private: void constructCommon(); void lazyInitialize(); void uninitialize(); bool willBeginPlayback(); bool willPausePlayback(); bool userGestureRequiredForAudioStart() const { return !isOfflineContext() && m_restrictions & RequireUserGestureForAudioStartRestriction; } bool pageConsentRequiredForAudioStart() const { return !isOfflineContext() && m_restrictions & RequirePageConsentForAudioStartRestriction; } void setState(State); void clear(); void scheduleNodeDeletion(); void mediaCanStart(Document&) override; // MediaProducer MediaProducer::MediaStateFlags mediaState() const override; void pageMutedStateDidChange() override; // The context itself keeps a reference to all source nodes. The source nodes, then reference all nodes they're connected to. // In turn, these nodes reference all nodes they're connected to. All nodes are ultimately connected to the AudioDestinationNode. // When the context dereferences a source node, it will be deactivated from the rendering graph along with all other nodes it is // uniquely connected to. See the AudioNode::ref() and AudioNode::deref() methods for more details. void refNode(AudioNode&); void derefNode(AudioNode&); // ActiveDOMObject API. void stop() override; bool canSuspendForDocumentSuspension() const override; const char* activeDOMObjectName() const override; // When the context goes away, there might still be some sources which haven't finished playing. // Make sure to dereference them here. void derefUnfinishedSourceNodes(); // PlatformMediaSessionClient PlatformMediaSession::MediaType mediaType() const override { return PlatformMediaSession::WebAudio; } PlatformMediaSession::MediaType presentationType() const override { return PlatformMediaSession::WebAudio; } PlatformMediaSession::CharacteristicsFlags characteristics() const override { return m_state == State::Running ? PlatformMediaSession::HasAudio : PlatformMediaSession::HasNothing; } void mayResumePlayback(bool shouldResume) override; void suspendPlayback() override; bool canReceiveRemoteControlCommands() const override { return false; } void didReceiveRemoteControlCommand(PlatformMediaSession::RemoteControlCommandType, const PlatformMediaSession::RemoteCommandArgument*) override { } bool supportsSeeking() const override { return false; } bool shouldOverrideBackgroundPlaybackRestriction(PlatformMediaSession::InterruptionType) const override { return false; } String sourceApplicationIdentifier() const override; bool canProduceAudio() const final { return true; } bool isSuspended() const final; bool processingUserGestureForMedia() const final; void visibilityStateChanged() final; // EventTarget void refEventTarget() override { ref(); } void derefEventTarget() override { deref(); } void handleDirtyAudioSummingJunctions(); void handleDirtyAudioNodeOutputs(); void addReaction(State, DOMPromiseDeferred<void>&&); void updateAutomaticPullNodes(); // Only accessed in the audio thread. Vector<AudioNode*> m_finishedNodes; // We don't use RefPtr<AudioNode> here because AudioNode has a more complex ref() / deref() implementation // with an optional argument for refType. We need to use the special refType: RefTypeConnection // Either accessed when the graph lock is held, or on the main thread when the audio thread has finished. Vector<AudioNode*> m_referencedNodes; // Accumulate nodes which need to be deleted here. // This is copied to m_nodesToDelete at the end of a render cycle in handlePostRenderTasks(), where we're assured of a stable graph // state which will have no references to any of the nodes in m_nodesToDelete once the context lock is released // (when handlePostRenderTasks() has completed). Vector<AudioNode*> m_nodesMarkedForDeletion; // They will be scheduled for deletion (on the main thread) at the end of a render cycle (in realtime thread). Vector<AudioNode*> m_nodesToDelete; bool m_isDeletionScheduled { false }; bool m_isStopScheduled { false }; bool m_isInitialized { false }; bool m_isAudioThreadFinished { false }; bool m_automaticPullNodesNeedUpdating { false }; bool m_isOfflineContext { false }; // Only accessed when the graph lock is held. HashSet<AudioSummingJunction*> m_dirtySummingJunctions; HashSet<AudioNodeOutput*> m_dirtyAudioNodeOutputs; // For the sake of thread safety, we maintain a seperate Vector of automatic pull nodes for rendering in m_renderingAutomaticPullNodes. // It will be copied from m_automaticPullNodes by updateAutomaticPullNodes() at the very start or end of the rendering quantum. HashSet<AudioNode*> m_automaticPullNodes; Vector<AudioNode*> m_renderingAutomaticPullNodes; // Only accessed in the audio thread. Vector<AudioNode*> m_deferredFinishDerefList; Vector<Vector<DOMPromiseDeferred<void>>> m_stateReactions; std::unique_ptr<PlatformMediaSession> m_mediaSession; std::unique_ptr<GenericEventQueue> m_eventQueue; RefPtr<AudioBuffer> m_renderTarget; RefPtr<AudioDestinationNode> m_destinationNode; RefPtr<AudioListener> m_listener; unsigned m_connectionCount { 0 }; // Graph locking. Lock m_contextGraphMutex; // FIXME: Using volatile seems incorrect. // https://bugs.webkit.org/show_bug.cgi?id=180332 Thread* volatile m_audioThread { nullptr }; Thread* volatile m_graphOwnerThread { nullptr }; // if the lock is held then this is the thread which owns it, otherwise == nullptr. AsyncAudioDecoder m_audioDecoder; // This is considering 32 is large enough for multiple channels audio. // It is somewhat arbitrary and could be increased if necessary. enum { MaxNumberOfChannels = 32 }; // Number of AudioBufferSourceNodes that are active (playing). std::atomic<int> m_activeSourceCount { 0 }; BehaviorRestrictions m_restrictions { NoRestrictions }; State m_state { State::Suspended }; }; // FIXME: Find out why these ==/!= functions are needed and remove them if possible. inline bool operator==(const AudioContext& lhs, const AudioContext& rhs) { return &lhs == &rhs; } inline bool operator!=(const AudioContext& lhs, const AudioContext& rhs) { return &lhs != &rhs; } inline AudioContext::State AudioContext::state() const { return m_state; } } // WebCore
{ "language": "C++" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <forward_list> // void sort(); #include <forward_list> #include <iterator> #include <algorithm> #include <vector> #include <random> #include <cassert> #include "test_macros.h" #include "min_allocator.h" std::mt19937 randomness; template <class C> void test(int N) { typedef typename C::value_type T; typedef std::vector<T> V; V v; for (int i = 0; i < N; ++i) v.push_back(i); std::shuffle(v.begin(), v.end(), randomness); C c(v.begin(), v.end()); c.sort(); assert(distance(c.begin(), c.end()) == N); typename C::const_iterator j = c.begin(); for (int i = 0; i < N; ++i, ++j) assert(*j == i); } struct Payload { int val; int side; Payload(int v) : val(v), side(0) {} Payload(int v, int s) : val(v), side(s) {} bool operator< (const Payload &rhs) const { return val < rhs.val;} // bool operator==(const Payload &rhs) const { return val == rhs.val;} }; void test_stable(int N) { typedef Payload T; typedef std::forward_list<T> C; typedef std::vector<T> V; V v; for (int i = 0; i < N; ++i) v.push_back(Payload(i/2)); std::shuffle(v.begin(), v.end(), randomness); for (int i = 0; i < N; ++i) v[i].side = i; C c(v.begin(), v.end()); c.sort(); assert(distance(c.begin(), c.end()) == N); // Are we sorted? typename C::const_iterator j = c.begin(); for (int i = 0; i < N; ++i, ++j) assert(j->val == i/2); // Are we stable? for (C::const_iterator it = c.begin(); it != c.end(); ++it) { C::const_iterator next = std::next(it); if (next != c.end() && it->val == next->val) assert(it->side < next->side); } } int main(int, char**) { for (int i = 0; i < 40; ++i) test<std::forward_list<int> >(i); #if TEST_STD_VER >= 11 for (int i = 0; i < 40; ++i) test<std::forward_list<int, min_allocator<int>> >(i); #endif for (int i = 0; i < 40; ++i) test_stable(i); return 0; }
{ "language": "C++" }
// (C) Copyright Steve Cleary, Beman Dawes, Howard Hinnant & John Maddock 2000. // Use, modification and distribution are subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt). // // See http://www.boost.org/libs/type_traits for most recent version including documentation. #ifndef BOOST_TT_REMOVE_REFERENCE_HPP_INCLUDED #define BOOST_TT_REMOVE_REFERENCE_HPP_INCLUDED #include <boost/config.hpp> #include <boost/detail/workaround.hpp> namespace boost { namespace detail{ // // We can't filter out rvalue_references at the same level as // references or we get ambiguities from msvc: // template <class T> struct remove_rvalue_ref { typedef T type; }; #ifndef BOOST_NO_CXX11_RVALUE_REFERENCES template <class T> struct remove_rvalue_ref<T&&> { typedef T type; }; #endif } // namespace detail template <class T> struct remove_reference{ typedef typename boost::detail::remove_rvalue_ref<T>::type type; }; template <class T> struct remove_reference<T&>{ typedef T type; }; #if defined(BOOST_ILLEGAL_CV_REFERENCES) // these are illegal specialisations; cv-qualifies applied to // references have no effect according to [8.3.2p1], // C++ Builder requires them though as it treats cv-qualified // references as distinct types... template <class T> struct remove_reference<T&const>{ typedef T type; }; template <class T> struct remove_reference<T&volatile>{ typedef T type; }; template <class T> struct remove_reference<T&const volatile>{ typedef T type; }; #endif } // namespace boost #endif // BOOST_TT_REMOVE_REFERENCE_HPP_INCLUDED
{ "language": "C++" }
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation 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_copyright_notice ==================================*/ #ifndef _BUILDIR_H_ #define _BUILDIR_H_ #include <cstdarg> #include <list> #include <map> #include <set> #include <string> #include "Gen4_IR.hpp" #include "FlowGraph.h" #include "visa_igc_common_header.h" #include "Common_ISA.h" #include "Common_ISA_util.h" #include "RT_Jitter_Interface.h" #include "visa_wa.h" #include "PreDefinedVars.h" #include "CompilerStats.h" #include "BinaryEncodingIGA.h" #include "inc/common/sku_wa.h" #define MAX_DWORD_VALUE 0x7fffffff #define MIN_DWORD_VALUE 0x80000000 #define MAX_UDWORD_VALUE 0xffffffff #define MIN_UDWORD_VALUE 0 #define MAX_WORD_VALUE 32767 #define MIN_WORD_VALUE -32768 #define MAX_UWORD_VALUE 65535 #define MIN_UWORD_VALUE 0 #define MAX_CHAR_VALUE 127 #define MIN_CHAR_VALUE -128 #define MAX_UCHAR_VALUE 255 #define MIN_UCHAR_VALUE 0 typedef struct FCCalls { // callOffset is in inst number units unsigned int callOffset; const char* calleeLabelString; } FCCalls; enum DeclareType { Regular = 0, Fill = 1, Spill = 2, Tmp = 3, AddrSpill = 4, CoalescedFill = 5, CoalescedSpill = 6 }; // forward declaration // FIXME: our #include is a mess, need to clean it up class CISA_IR_Builder; namespace vISA { // IR_Builder class has a member of type FCPatchingInfo // as a member. This class is expected to hold all FC // related information. class FCPatchingInfo { private: // Flag to tell if this instance has any fast-composite // type calls. Callees for such call instructions are not available // in same compilation unit. bool hasFCCalls; // Set to true if kernel has "Callable" attribute set in VISA // stream. bool isFCCallableKernel; // Set to true if kernel was compiled with /mCM_composable_kernel // FE flag. bool isFCComposableKernel; // Set to true if kernel has "Entry" attribute set in VISA // stream. bool isFCEntryKernel; std::vector<FCCalls*> FCCallsToPatch; std::vector<unsigned int> FCReturnOffsetsToPatch; public: FCPatchingInfo() { hasFCCalls = false; isFCCallableKernel = false; isFCComposableKernel = false; isFCEntryKernel = false; } void setHasFCCalls(bool hasFC) { hasFCCalls = hasFC; } bool getHasFCCalls() { return hasFCCalls; } void setIsCallableKernel(bool value) { isFCCallableKernel = value; } bool getIsCallableKernel() { return isFCCallableKernel; } void setFCComposableKernel(bool value) { isFCComposableKernel = value; } bool getFCComposableKernel() { return isFCComposableKernel; } void setIsEntryKernel(bool value) { isFCEntryKernel = value; } bool getIsEntryKernel() { return isFCEntryKernel; } std::vector<FCCalls*>& getFCCallsToPatch() { return FCCallsToPatch; } std::vector<unsigned int>& getFCReturnsToPatch() { return FCReturnOffsetsToPatch; } enum RegAccessType : unsigned char { Fully_Use = 0, Partial_Use = 1, Fully_Def = 2, Partial_Def = 3 }; enum RegAccessPipe : unsigned char { Pipe_ALU = 0, Pipe_Math = 1, Pipe_Send = 2 }; struct RegAccess { RegAccess *Next; // The next access on the same GRF. RegAccessType Type; // 'def' or 'use' of that GRF. unsigned RegNo; // GRF. unsigned Pipe; // Pipe. // where that access is issued. G4_INST *Inst; // Where that GRF is accessed. unsigned Offset; // Instruction offset populated finally. // Token associated with that access. unsigned Token; // Optional token allocation associated to 'def'. RegAccess() : Next(nullptr), Type(Fully_Use), RegNo(0), Pipe(0), Inst(nullptr), Offset(0), Token(0) {} }; // FIXME: Need to consider the pipeline ID together with GRF since // different pipe will use/def out-of-order. Need to synchronize all of // them to resolve the dependency. std::list<RegAccess> RegFirstAccessList; std::list<RegAccess> RegLastAccessList; // Per GRF, the first access. std::map<unsigned, RegAccess *> RegFirstAccessMap; // Per GRF, the last access. std::map<unsigned, RegAccess *> RegLastAccessMap; // Note that tokens recorded are tokens allocated but not used in last // access list. std::set<unsigned> AllocatedToken; // Allocated token. }; } namespace vISA { // // hash table for holding reg vars and reg region // class OperandHashTable { Mem_Manager& mem; struct ImmKey { int64_t val; G4_Type valType; ImmKey(int64_t imm, G4_Type type) : val(imm), valType(type) {} bool operator==(const ImmKey& imm) const { return val == imm.val && valType == imm.valType; } }; struct ImmKeyHash { std::size_t operator()(const ImmKey& imm) const { return (std::size_t) (imm.val ^ imm.valType); } }; struct stringCompare { bool operator() (const char* s1, const char* s2) const { return strcmp(s1, s2) == 0; } }; std::unordered_map<ImmKey, G4_Imm*, ImmKeyHash> immTable; std::unordered_map<const char *, G4_Label*, std::hash<const char*>, stringCompare> labelTable; public: OperandHashTable(Mem_Manager& m) : mem(m) { } // Generic methods that work on both integer and floating-point types. // For floating-point types, 'imm' needs to be G4_Imm(<float-value>.getImm(). G4_Imm* lookupImm(int64_t imm, G4_Type ty); G4_Imm* createImm(int64_t imm, G4_Type ty); G4_Label* lookupLabel(const char* lab); G4_Label* createLabel(const char* lab); }; // // place for holding all region descriptions // class RegionPool { Mem_Manager& mem; std::vector<RegionDesc*> rgnlist; public: RegionPool(Mem_Manager& m) : mem(m) {} const RegionDesc* createRegion( uint16_t vstride, uint16_t width, uint16_t hstride); }; // // place for hbolding all .declare // class DeclarePool { Mem_Manager& mem; std::vector<G4_Declare*> dcllist; int addrSpillLocCount; //incremented in G4_RegVarAddrSpillLoc() public: DeclarePool(Mem_Manager& m) : mem(m), addrSpillLocCount(0) { dcllist.reserve(2048); } ~DeclarePool(); G4_Declare* createDeclare( const char* name, G4_RegFileKind regFile, unsigned short nElems, unsigned short nRows, G4_Type ty, DeclareType kind = Regular, G4_RegVar * base = nullptr, G4_Operand * repRegion = nullptr, G4_ExecSize execSize = G4_ExecSize(0)); G4_Declare* createPreVarDeclare( PreDefinedVarsInternal index, unsigned short n_elems, unsigned short n_rows, G4_Type ty) { G4_Declare* dcl = new (mem)G4_Declare(getPredefinedVarString(index), G4_INPUT, n_elems * n_rows, ty, dcllist); G4_RegVar * regVar; regVar = new (mem) G4_RegVar(dcl, G4_RegVar::RegVarType::Default); dcl->setRegVar(regVar); return dcl; } std::vector<G4_Declare*>& getDeclareList() {return dcllist;} }; // // interface for creating operands and instructions // class IR_Builder { public: const char* curFile; unsigned int curLine; int curCISAOffset; static const int OrphanVISAIndex = 0xffffffff; int debugInfoPlaceholder = OrphanVISAIndex; // used for debug info, catch all VISA offset for orphan instructions private: class GlobalImmPool { struct ImmVal { G4_Imm* imm; int numElt; bool operator==(const ImmVal& v) const { return imm == v.imm && numElt == v.numElt; } }; static const int MAX_POOL_SIZE = 8; // reg pressure control, for now just do naive first-come first-serve std::array<ImmVal, MAX_POOL_SIZE> immArray; std::array<G4_Declare*, MAX_POOL_SIZE> dclArray; int curSize = 0; IR_Builder& builder; public: GlobalImmPool(IR_Builder& b) : builder(b), immArray(), dclArray() {} G4_Declare* addImmVal(G4_Imm* imm, int numElt); int size() const { return curSize; } const ImmVal& getImmVal(int i) {return immArray[i];} G4_Declare* getImmDcl(int i) {return dclArray[i];} }; GlobalImmPool immPool; const TARGET_PLATFORM platform; //allocator pools USE_DEF_ALLOCATOR useDefAllocator; FINALIZER_INFO* metaData = nullptr; CompilerStats compilerStats; int subroutineId = -1; // the kernel itself has id 0, as we always emit a subroutine label for kernel too bool isKernel; // as opposed to what? // pre-defined declare that binds to R0 (the entire GRF) // when pre-emption is enabled, builtinR0 is replaced by a temp, // and a move is inserted at kernel entry // mov (8) builtinR0 realR0 G4_Declare* builtinR0 = nullptr; // this is either r0 or the temp if pre-emption is enabled G4_Declare* realR0 = nullptr; // this always refers to r0 // pre-defined declare that binds to A0.0:ud G4_Declare* builtinA0 = nullptr; // pre-defined declare that binds to A0.2:ud G4_Declare* builtinA0Dot2 = nullptr; //used for splitsend's ext msg descriptor // pre-defind declare that binds to HWTid (R0.5:ud) G4_Declare* builtinHWTID = nullptr; // pre-defined bindless surface index (252, 1 UD) G4_Declare* builtinT252 = nullptr; // pre-defined bindless sampler index (31, 1 UD) G4_Declare* builtinBindlessSampler = nullptr; // pre-defined sampler header G4_Declare* builtinSamplerHeader = nullptr; // common message header for spill/fill intrinsics // We put them here instead of spillManager since there may be multiple rounds of spill, // and we want to use a common header G4_Declare* spillFillHeader = nullptr; G4_Declare* oldA0Dot2Temp = nullptr; // Indicates that sampler header cache (builtinSamplerHeader) is correctly // initialized with r0 contents. // Used only when vISA_cacheSamplerHeader option is set. bool builtinSamplerHeaderInitialized; // function call related declares G4_Declare* be_sp = nullptr; G4_Declare* be_fp = nullptr; G4_Declare* tmpFCRet = nullptr; unsigned short arg_size; unsigned short return_var_size; unsigned int sampler8x8_group_id; // Populate this data structure so after compiling all kernels // in file, we can emit out patch file using this up-levelled // information. FCPatchingInfo* fcPatchInfo = nullptr; const PWA_TABLE m_pWaTable; Options *m_options = nullptr; std::map<G4_INST*, G4_FCALL*> m_fcallInfo; // Basic region descriptors. RegionDesc CanonicalRegionStride0, // <0; 1, 0> CanonicalRegionStride1, // <1; 1, 0> CanonicalRegionStride2, // <2; 1, 0> CanonicalRegionStride4; // <4; 1, 0> class PreDefinedVars { public: PreDefinedVars() { memset(hasPredefined, 0, sizeof(hasPredefined)); memset(predefinedVars, 0, sizeof(predefinedVars)); } void setHasPredefined(PreDefinedVarsInternal id, bool val) { hasPredefined[static_cast<int>(id)] = val; } bool isHasPredefined(PreDefinedVarsInternal id) const { return hasPredefined[static_cast<int>(id)]; } void setPredefinedVar(PreDefinedVarsInternal id, G4_Declare *dcl) { predefinedVars[static_cast<int>(id)] = dcl; } G4_Declare* getPreDefinedVar(PreDefinedVarsInternal id) const { if (id >= PreDefinedVarsInternal::VAR_LAST) { return nullptr; } return predefinedVars[static_cast<int>(id)]; } private: // records whether a vISA pre-defined var is used by the kernel // some predefined need to be expanded (e.g., HWTid, color) bool hasPredefined[static_cast<int>(PreDefinedVarsInternal::VAR_LAST)]; G4_Declare* predefinedVars[static_cast<int>(PreDefinedVarsInternal::VAR_LAST)]; }; bool hasNullReturnSampler = false; bool hasPerThreadProlog = false; // Have inserted two entires prolog for setting FFID for compute shaders bool hasComputeFFIDProlog = false; // FIXME: should not leak IGA IR into G4/vISA except in encoder const iga::Model* igaModel = nullptr; const CISA_IR_Builder* parentBuilder = nullptr; // stores all metadata ever allocated Mem_Manager metadataMem; std::vector<Metadata*> allMDs; std::vector<MDNode*> allMDNodes; public: PreDefinedVars preDefVars; Mem_Manager& mem; // memory for all operands and insts PhyRegPool phyregpool; // all physical regs OperandHashTable hashtable; // all created region operands RegionPool rgnpool; // all region description DeclarePool dclpool; // all created decalres INST_LIST instList; // all created insts // list of instructions ever allocated // This list may only grow and is freed when IR_Builder is destroyed std::vector<G4_INST*> instAllocList; G4_Kernel& kernel; // the following fileds are used for dcl name when a new dcl is created. // number of predefined variables are included. unsigned num_temp_dcl; // number of temp GRF vars created to hold spilled addr/flag uint32_t numAddrFlagSpillLoc = 0; std::vector<input_info_t*> m_inputVect; const Options* getOptions() const { return m_options; } bool getOption(vISAOptions opt) const {return m_options->getOption(opt); } uint32_t getuint32Option(vISAOptions opt) const { return m_options->getuInt32Option(opt); } void getOption(vISAOptions opt, const char *&str) const {return m_options->getOption(opt, str); } void addInputArg(input_info_t * inpt); input_info_t * getInputArg(unsigned int index); unsigned int getInputCount(); input_info_t * getRetIPArg(); // what's the void* really? const void* GetCurrentInst() const { return m_inst; }; void SetCurrentInst(const void* inst) { m_inst = inst; }; const CISA_IR_Builder* getParent() const { return parentBuilder; } void dump(std::ostream &os); // not const because G4_INST::emit isn't :( std::stringstream& criticalMsgStream(); const USE_DEF_ALLOCATOR& getAllocator() const { return useDefAllocator; } enum SubRegs_SP_FP { FE_SP = 0, // Can be either :ud or :uq FE_FP = 1, // Can be either :ud or :uq BE_SP = 6, // :ud BE_FP = 7 // :ud }; // Getter/setter for be_sp and be_fp G4_Declare* getBESP() { if (be_sp == NULL) { be_sp = createDeclareNoLookup("be_sp", G4_GRF, 1, 1, Type_UD); be_sp->getRegVar()->setPhyReg(phyregpool.getGreg(kernel.getFPSPGRF()), SubRegs_SP_FP::BE_SP); } return be_sp; } G4_Declare* getBEFP() { if (be_fp == NULL) { be_fp = createDeclareNoLookup("be_fp", G4_GRF, 1, 1, Type_UD); be_fp->getRegVar()->setPhyReg(phyregpool.getGreg(kernel.getFPSPGRF()), SubRegs_SP_FP::BE_FP); } return be_fp; } G4_Declare* getStackCallArg() const { return preDefVars.getPreDefinedVar(PreDefinedVarsInternal::ARG); } G4_Declare* getStackCallRet() const { return preDefVars.getPreDefinedVar(PreDefinedVarsInternal::RET); } G4_Declare* getFE_SP() const { return preDefVars.getPreDefinedVar(PreDefinedVarsInternal::FE_SP); } G4_Declare* getFE_FP() const { return preDefVars.getPreDefinedVar(PreDefinedVarsInternal::FE_FP); } bool isPreDefArg(G4_Declare* dcl) const { return dcl == getStackCallArg(); } bool isPreDefRet(G4_Declare* dcl) const { return dcl == getStackCallRet(); } bool isPreDefFEStackVar(G4_Declare* dcl) const { return dcl == getFE_SP() || dcl == getFE_FP(); } // this refers to vISA's internal stack for spill and caller/callee-save // Note that this is only valid after CFG is constructed // ToDo: make this a pass? bool usesStack() const { return kernel.fg.getHasStackCalls() || kernel.fg.getIsStackCallFunc(); } void bindInputDecl(G4_Declare* dcl, int grfOffset); // FIXME: Why is this needed, should not leak IGA internals into vISA! const iga::Model* getIGAModel() const { return igaModel; } uint32_t getPerThreadInputSize() const { return kernel.getInt32KernelAttr(Attributes::ATTR_PerThreadInputSize); } bool getHasPerThreadProlog() const { return hasPerThreadProlog; } void setHasPerThreadProlog() { hasPerThreadProlog = true; } bool getHasComputeFFIDProlog() const { return hasComputeFFIDProlog; } void setHasComputeFFIDProlog() { hasComputeFFIDProlog = true; } // // Check if opnd is or can be made "alignByte"-byte aligned. // These functions will change the underlying variable's alignment // (e.g., make a scalar variable GRF-aligned) when possible to satisfy // the alignment bool isOpndAligned(G4_Operand* opnd, int alignByte) const; bool isOpndAligned(G4_Operand *opnd, unsigned short &offset, int align_byte) const; void setIsKernel(bool value) { isKernel = value; } bool getIsKernel() const { return isKernel; } void predefinedVarRegAssignment(uint8_t inputSize); void expandPredefinedVars(); void setArgSize(unsigned short size) { arg_size = size; } unsigned short getArgSize() const { return arg_size; } void setRetVarSize(unsigned short size) { return_var_size = size; } unsigned short getRetVarSize() const { return return_var_size; } FCPatchingInfo* getFCPatchInfo(); void setFCPatchInfo(FCPatchingInfo* instance) { fcPatchInfo = instance; } const PWA_TABLE getPWaTable() const { return m_pWaTable; } const char* getNameString(Mem_Manager& mem, size_t size, const char* format, ...); G4_Predicate_Control vISAPredicateToG4Predicate( VISA_PREDICATE_CONTROL control, G4_ExecSize execSize); G4_FCALL* getFcallInfo(G4_INST* inst) const; // If this is true (detected in TranslateInterface.cpp), we need a sampler flush before EOT bool getHasNullReturnSampler() const { return hasNullReturnSampler; } // Initializes predefined vars for all the vISA versions void createPreDefinedVars(); void createBuiltinDecls(); G4_Declare* getSpillFillHeader(); G4_Declare* getOldA0Dot2Temp(); bool hasValidOldA0Dot2() { return oldA0Dot2Temp; } IR_Builder( TARGET_PLATFORM genPlatform, INST_LIST_NODE_ALLOCATOR &alloc, G4_Kernel &k, Mem_Manager &m, Options *options, CISA_IR_Builder* parent, FINALIZER_INFO *jitInfo, PWA_TABLE pWaTable); ~IR_Builder(); void rebuildPhyRegPool(unsigned int numRegisters) { phyregpool.rebuildRegPool(mem, numRegisters); } TARGET_PLATFORM getPlatform() const {return platform;} FINALIZER_INFO* getJitInfo() {return metaData;} CompilerStats &getcompilerStats() {return compilerStats;} G4_Declare* createDeclareNoLookup( const char* name, G4_RegFileKind regFile, unsigned short n_elems, unsigned short n_rows, G4_Type ty, DeclareType kind = Regular, G4_RegVar * base = NULL, G4_Operand * repRegion = NULL, G4_ExecSize execSize = G4_ExecSize(0)); G4_Declare* createPreVarDeclareNoLookup( PreDefinedVarsInternal index, unsigned short n_elems, unsigned short n_rows, G4_Type ty) { G4_Declare* dcl = dclpool.createPreVarDeclare(index, n_elems, n_rows, ty); kernel.Declares.push_back(dcl); return dcl; } G4_Declare* getBuiltinR0() {return builtinR0;} G4_Declare* getRealR0() const {return realR0;} // undefined terminology: what's "real" here (vs "builtin" above)? G4_Declare* getBuiltinA0() {return builtinA0;} G4_Declare* getBuiltinA0Dot2() {return builtinA0Dot2;} G4_Declare* getBuiltinHWTID() const {return builtinHWTID;} G4_Declare* getBuiltinT252() const {return builtinT252;} G4_Declare* getBuiltinBindlessSampler() const {return builtinBindlessSampler; } G4_Declare* getBuiltinSamplerHeader() const { return builtinSamplerHeader; } G4_Declare* getOldA0Dot2Temp() const { return oldA0Dot2Temp; } bool isBindlessSampler(const G4_Operand* sampler) const { return sampler->isSrcRegRegion() && sampler->getTopDcl() == getBuiltinBindlessSampler(); } bool isBindlessSurface(const G4_Operand* bti) const { return bti->isSrcRegRegion() && bti->getTopDcl() == getBuiltinT252(); } // IsSLMSurface - Check whether the given surface is SLM surface. static bool IsSLMSurface(const G4_Operand *surface) { // So far, it's only reliable to check an immediate surface. return surface->isImm() && surface->asImm()->getImm() == PREDEF_SURF_0; } static const G4_Declare *getDeclare(const G4_Operand *opnd) { const G4_Declare *dcl = opnd->getBase()->asRegVar()->getDeclare(); while (const G4_Declare *parentDcl = dcl->getAliasDeclare()) dcl = parentDcl; return dcl; } static G4_Declare *getDeclare(G4_Operand *opnd) { return const_cast<G4_Declare *>(getDeclare((const G4_Operand *)opnd)); } bool shouldForceSplitSend(const G4_Operand* surface) const { return surface->isSrcRegRegion() && surface->asSrcRegRegion()->getBase()->asRegVar()->getDeclare() == getBuiltinT252(); } /// getSplitEMask() calculates the new mask after splitting from the current /// execution mask at the given execution size. /// It only works with masks covering whole GRF and thus won't generate/consume /// nibbles. static uint32_t getSplitEMask(unsigned execSize, uint32_t eMask, bool isLo); static uint32_t getSplitLoEMask(unsigned execSize, uint32_t eMask) { return getSplitEMask(execSize, eMask, true); } static uint32_t getSplitHiEMask(unsigned execSize, uint32_t eMask) { return getSplitEMask(execSize, eMask, false); } // create a new temp GRF with the specified type/size and undefined regions G4_Declare* createTempVar( unsigned int numElements, G4_Type type, G4_SubReg_Align subAlign, const char* prefix = "TV", bool appendIdToName = true); // create a new temp GRF as the home location of a spilled addr/flag dcl G4_Declare* createAddrFlagSpillLoc(G4_Declare* dcl); // like the above, but also mark the variable as don't spill // this is used for temp variables in macro sequences where spilling woul not help // FIXME: can we somehow merge this with G4_RegVarTmp/G4_RegVarTransient? G4_Declare* createTempVarWithNoSpill( unsigned int numElements, G4_Type type, G4_SubReg_Align subAlign, const char* prefix = "TV") { G4_Declare* dcl = createTempVar(numElements, type, subAlign, prefix); dcl->setDoNotSpill(); return dcl; } // // Create a declare that is hardwired to some phyiscal GRF. // It is useful to implement various workarounds post RA where we want to directly // address some physical GRF. // regOff is in unit of the declare type. // caller is responsible for ensuring the resulting variable does not violate any HW restrictions // (e.g., operand does not cross two GRF) G4_Declare* createHardwiredDeclare( uint32_t numElements, G4_Type type, uint32_t regNum, uint32_t regOff); G4_INST* createPseudoKills(std::initializer_list<G4_Declare*> dcls, PseudoKillType ty); G4_INST* createPseudoKill(G4_Declare* dcl, PseudoKillType ty); // numRows is in hword units // offset is in hword units G4_INST* createSpill( G4_DstRegRegion* dst, G4_SrcRegRegion* header, G4_SrcRegRegion* payload, G4_ExecSize execSize, uint16_t numRows, uint32_t offset, G4_Declare* fp, G4_InstOption option); G4_INST* createSpill( G4_DstRegRegion* dst, G4_SrcRegRegion* payload, G4_ExecSize execSize, uint16_t numRows, uint32_t offset, G4_Declare* fp, G4_InstOption option); G4_INST* createFill( G4_SrcRegRegion* header, G4_DstRegRegion* dstData, G4_ExecSize execSize, uint16_t numRows, uint32_t offset, G4_Declare* fp, G4_InstOption option); G4_INST* createFill( G4_DstRegRegion* dstData, G4_ExecSize execSize, uint16_t numRows, uint32_t offset, G4_Declare* fp , G4_InstOption option); // numberOfFlags MEANS NUMBER OF WORDS (e.g., 1 means 16-bit), not number of bits or number of data elements in operands. G4_Declare* createTempFlag(unsigned short numberOfFlags, const char* prefix = "TEMP_FLAG_"); // like above, but pass numFlagElements instead. This allows us to distinguish between 1/8/16-bit flags, // which are all allocated as a UW. name is allocated by caller G4_Declare* createFlag(uint16_t numFlagElements, const char* name); G4_Declare* createPreVar( PreDefinedVarsInternal preDefVar_index, unsigned short numElements, G4_Type type); // // create <vstride; width, hstride> // // PLEASE use getRegion* interface to get regions if possible! // This function will be mostly used for external regions. const RegionDesc* createRegionDesc( uint16_t vstride, uint16_t width, uint16_t hstride) { return rgnpool.createRegion(vstride, width, hstride); } // Given the execution size and region parameters, create a region // descriptor. // // PLEASE use getRegion* interface to get regions if possible! // This function will be mostly used for external regions. const RegionDesc *createRegionDesc( uint16_t execSize, uint16_t vstride, uint16_t width, uint16_t hstride) { // Performs normalization for commonly used regions. switch (RegionDesc::getRegionDescKind(execSize, vstride, width, hstride)) { case RegionDesc::RK_Stride0: return getRegionScalar(); case RegionDesc::RK_Stride1: return getRegionStride1(); case RegionDesc::RK_Stride2: return getRegionStride2(); case RegionDesc::RK_Stride4: return getRegionStride4(); default: break; } return rgnpool.createRegion(vstride, width, hstride); } /// Helper to normalize an existing region descriptor. const RegionDesc *getNormalizedRegion(uint16_t execSize, const RegionDesc *rd) { return createRegionDesc(execSize, rd->vertStride, rd->width, rd->horzStride); } /// Get the predefined region descriptors. const RegionDesc *getRegionScalar() const { return &CanonicalRegionStride0; } const RegionDesc *getRegionStride1() const { return &CanonicalRegionStride1; } const RegionDesc *getRegionStride2() const { return &CanonicalRegionStride2; } const RegionDesc *getRegionStride4() const { return &CanonicalRegionStride4; } // ToDo: get rid of this version and use the message type specific ones below instead, // so we can avoid having to explicitly create extDesc bits G4_SendMsgDescriptor* createGeneralMsgDesc( uint32_t desc, uint32_t extDesc, SendAccess access, G4_Operand* bti = nullptr, G4_Operand* sti = nullptr); G4_SendMsgDescriptor* createReadMsgDesc( SFID sfid, uint32_t desc, G4_Operand* bti = nullptr); G4_SendMsgDescriptor* createWriteMsgDesc( SFID sfid, uint32_t desc, int src1Len, G4_Operand* bti = nullptr); G4_SendMsgDescriptor* createSyncMsgDesc( SFID sfid, uint32_t desc); G4_SendMsgDescriptor* createSampleMsgDesc( uint32_t desc, bool cps, int src1Len, G4_Operand* bti, G4_Operand* sti); static SendAccess getSendAccessType(bool isRead, bool isWrite) { if (isRead && isWrite) { return SendAccess::READ_WRITE; } return isRead ? SendAccess::READ_ONLY : SendAccess::WRITE_ONLY; } G4_SendMsgDescriptor* createSendMsgDesc( SFID sfid, uint32_t desc, uint32_t extDesc, int src1Len, SendAccess access, G4_Operand *bti, bool isValidFuncCtrl = true); G4_SendMsgDescriptor* createSendMsgDesc( unsigned funcCtrl, unsigned regs2rcv, unsigned regs2snd, SFID funcID, unsigned extMsgLength, uint16_t extFuncCtrl, SendAccess access, G4_Operand* bti = nullptr, G4_Operand* sti = nullptr); G4_Operand* emitSampleIndexGE16( G4_Operand* sampler, G4_Declare* headerDecl); // // deprecated, please use the one below // G4_SrcRegRegion* createSrcRegRegion(G4_SrcRegRegion& src) { G4_SrcRegRegion* rgn = new (mem)G4_SrcRegRegion(src); return rgn; } // Create a new srcregregion allocated in mem G4_SrcRegRegion* createSrcRegRegion( G4_VarBase* b, short roff, short sroff, const RegionDesc *rd, G4_Type ty, G4_AccRegSel regSel = ACC_UNDEFINED) { return createSrcRegRegion(Mod_src_undef, Direct, b, roff, sroff, rd, ty, regSel); } // Create a new srcregregion allocated in mem G4_SrcRegRegion* createSrcRegRegion( G4_SrcModifier m, G4_RegAccess a, G4_VarBase* b, short roff, short sroff, const RegionDesc *rd, G4_Type ty, G4_AccRegSel regSel = ACC_UNDEFINED) { G4_SrcRegRegion* rgn = new (mem)G4_SrcRegRegion(m, a, b, roff, sroff, rd, ty, regSel); return rgn; } G4_SrcRegRegion* createSrcWithNewRegOff(G4_SrcRegRegion* old, short newRegOff); G4_SrcRegRegion* createSrcWithNewSubRegOff(G4_SrcRegRegion* old, short newSubRegOff); G4_SrcRegRegion* createSrcWithNewBase(G4_SrcRegRegion* old, G4_VarBase* newBase); G4_SrcRegRegion* createIndirectSrc( G4_SrcModifier m, G4_VarBase* b, short roff, short sroff, const RegionDesc* rd, G4_Type ty, short immAddrOff) { G4_SrcRegRegion* rgn = new (mem) G4_SrcRegRegion(m, IndirGRF, b, roff, sroff, rd, ty, ACC_UNDEFINED); rgn->setImmAddrOff(immAddrOff); return rgn; } // // deprecated, please use the version below // G4_DstRegRegion* createDstRegRegion(G4_DstRegRegion& dst) { G4_DstRegRegion* rgn = new (mem) G4_DstRegRegion(dst); return rgn; } // create a new dstregregion allocated in mem // TODO: Avoid calling this directly since direct dst and indirect dst // have different parameters. Will make it private in the future. G4_DstRegRegion* createDstRegRegion( G4_RegAccess a, G4_VarBase* b, short roff, short sroff, unsigned short hstride, G4_Type ty, G4_AccRegSel regSel = ACC_UNDEFINED) { G4_DstRegRegion* rgn = new (mem) G4_DstRegRegion(a, b, roff, sroff, hstride, ty, regSel); return rgn; } // create a direct DstRegRegion G4_DstRegRegion* createDst( G4_VarBase* b, short roff, short sroff, unsigned short hstride, G4_Type ty, G4_AccRegSel regSel = ACC_UNDEFINED) { return createDstRegRegion(Direct, b, roff, sroff, hstride, ty, regSel); } // create a direct DstRegRegion G4_DstRegRegion* createDst(G4_VarBase* b, G4_Type ty) { return createDstRegRegion(Direct, b, 0, 0, 1, ty, ACC_UNDEFINED); } // create a indirect DstRegRegion // b is the address variable, which only supports subreg offset G4_DstRegRegion* createIndirectDst(G4_VarBase* b, short sroff, uint16_t hstride, G4_Type ty, int16_t immOff) { auto dst = createDstRegRegion(IndirGRF, b, 0, sroff, hstride, ty); dst->setImmAddrOff(immOff); return dst; } G4_DstRegRegion* createDstWithNewSubRegOff(G4_DstRegRegion* old, short newSubRegOff); // // return the imm operand; create one if not yet created // G4_Imm* createImm(int64_t imm, G4_Type ty) { G4_Imm* i = hashtable.lookupImm(imm, ty); return (i != NULL)? i : hashtable.createImm(imm, ty); } // // return the float operand; create one if not yet created // G4_Imm* createImm(float fp); // // return the double operand; create one if not yet created // G4_Imm* createDFImm(double fp); // For integer immediates use a narrower type if possible // also change byte type to word type since HW does not support byte imm G4_Type getNewType(int64_t imm, G4_Type ty); // // return the imm operand with its lowest type(W or above); create one if not yet created // G4_Imm* createImmWithLowerType(int64_t imm, G4_Type ty) { G4_Type new_type = getNewType(imm, ty); G4_Imm* i = hashtable.lookupImm(imm, new_type); return (i != NULL)? i : hashtable.createImm(imm, new_type); } // // Create immediate operand without looking up hash table. This operand // is a relocatable immediate type. // G4_Reloc_Imm* createRelocImm(G4_Type ty) { G4_Reloc_Imm* newImm; newImm = new (mem)G4_Reloc_Imm(ty); return newImm; } // // Create immediate operand without looking up hash table. This operand // is a relocatable immediate type. Specify the value of this imm field, // which will present in the output instruction's imm value. // G4_Reloc_Imm* createRelocImm(int64_t immval, G4_Type ty) { G4_Reloc_Imm* newImm; newImm = new (mem)G4_Reloc_Imm(immval, ty); return newImm; } // // return the label operand; create one if not found // G4_Label* lookupLabel(char* lab) { G4_Label* l = hashtable.lookupLabel(lab); return l; } // // return the label operand; create one if not found. // a new copy of "lab" is created for the new label, so // caller does not have to allocate memory for lab // G4_Label* createLabel(std::string& lab, VISA_Label_Kind kind) { auto labStr = lab.c_str(); G4_Label* l = hashtable.lookupLabel(labStr); return (l != NULL)? l : hashtable.createLabel(labStr); } G4_Predicate* createPredicate( G4_PredState s, G4_VarBase* flag, unsigned short srOff, G4_Predicate_Control ctrl = PRED_DEFAULT) { G4_Predicate* pred = new (mem)G4_Predicate(s, flag, srOff, ctrl); return pred; } G4_Predicate* createPredicate(G4_Predicate& prd) { G4_Predicate* p = new (mem) G4_Predicate(prd); return p; } G4_CondMod* createCondMod(G4_CondModifier m, G4_VarBase* flag, unsigned short off) { G4_CondMod* p = new (mem)G4_CondMod(m, flag, off); return p; } // // return the condition modifier; create one if not yet created // G4_CondMod* createCondMod(G4_CondMod& mod) { G4_CondMod* p = new (mem) G4_CondMod(mod); return p; } // // create register address expression normalized to (&reg +/- exp) // G4_AddrExp* createAddrExp(G4_RegVar* reg, int offset, G4_Type ty) { return new (mem) G4_AddrExp(reg, offset, ty); } private: // please leave all createInst() as private and use the public wrappers below // cond+sat+binary G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize size, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, bool addToInstList = true); // cond+sat+binary+line G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize size, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, int lineno, bool addToInstList = true); // TODO: remove // old template: // cond+sat+binary+line G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, int execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, int lineno, bool addToInstList = true) { G4_ExecSize sz((unsigned char)execSize); return createInst(prd, op, mod, sat, sz, dst, src0, src1, options, lineno); } // TODO: remove // old template: // cond+sat+binary G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, int execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, bool addToInstList = true) { G4_ExecSize sz((unsigned char)execSize); return createInst(prd, op, mod, sat, sz, dst, src0, src1, options); } // cond+sat+ternary G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options, bool addToInstList = true); // cond+sat+ternary+line G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options, int lineno, bool addToInstList = true); // TODO: remove // old template: // cond+sat+ternary G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, int execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts option, bool addToInstList = true) { G4_ExecSize sz((unsigned char)execSize); return createInst(prd, op, mod, sat, sz, dst, src0, src1, src2, option); } // old template: // cond+sat+ternary+line G4_INST* createInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, int execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts option, int lineno, bool addToInstList = true) { G4_ExecSize sz((unsigned char)execSize); return createInst(prd, op, mod, sat, sz, dst, src0, src1, src2, option, lineno); } public: G4_INST* createIf(G4_Predicate* prd, G4_ExecSize execSize, G4_InstOpts options); G4_INST* createElse(G4_ExecSize execSize, G4_InstOpts options); G4_INST* createEndif(G4_ExecSize execSize, G4_InstOpts options); G4_INST* createLabelInst(G4_Label* label, bool appendToInstList); G4_INST* createJmp( G4_Predicate* pred, G4_Operand* jmpTarget, G4_InstOpts options, bool appendToInstList); // ToDo: make createInternalInst() private as well and add wraper for them G4_INST* createInternalInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options); G4_INST* createInternalInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, int lineno, int CISAoff, const char* srcFilename); G4_INST* createInternalInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options); G4_INST* createInternalInst( G4_Predicate* prd, G4_opcode op, G4_CondMod* mod, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options, int lineno, int CISAoff, const char* srcFilename); G4_INST* createCFInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_Label* jip, G4_Label* uip, G4_InstOpts options, int lineno = 0, bool addToInstList= true); G4_INST* createInternalCFInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_Label* jip, G4_Label* uip, G4_InstOpts options, int lineno = 0, int CISAoff = -1, const char* srcFilename = NULL); G4_InstSend* createSendInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* postDst, G4_SrcRegRegion* payload, G4_Operand* msg, G4_InstOpts options, // FIXME: re-order options to follow all operands G4_SendMsgDescriptor *msgDesc, int lineno = 0, bool addToInstList = true); G4_InstSend* createInternalSendInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* postDst, G4_SrcRegRegion* payload, G4_Operand* msg, G4_InstOpts options, // FIXME: re-order options to follow all operands G4_SendMsgDescriptor *msgDesc, int lineno = 0, int CISAoff = -1, const char* srcFilename = NULL); G4_InstSend* createSplitSendInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_SrcRegRegion* src1, G4_SrcRegRegion* src2, G4_Operand* msg, G4_InstOpts options, G4_SendMsgDescriptor *msgDesc, G4_Operand* src3, int lineno = 0, bool addToInstList = true); G4_InstSend* createInternalSplitSendInst( G4_Predicate* prd, G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_SrcRegRegion* src1, G4_SrcRegRegion* src2, // TODO: reorder parameters to put options last G4_Operand* msg, G4_InstOpts options, G4_SendMsgDescriptor *msgDesc, G4_Operand* src3, int lineno = 0, int CISAoff = -1, const char* srcFilename = NULL); G4_INST* createMathInst( G4_Predicate* prd, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_MathOp mathOp, G4_InstOpts options, int lineno = 0, bool addToInstList = true); G4_INST* createInternalMathInst( G4_Predicate* prd, G4_Sat sat, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_MathOp mathOp, G4_InstOpts options, int lineno = 0, int CISAoff = -1, const char* srcFilename = NULL); G4_INST* createIntrinsicInst( G4_Predicate* prd, Intrinsic intrinId, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options, int lineno = 0, bool addToInstList = true); G4_INST* createInternalIntrinsicInst( G4_Predicate* prd, Intrinsic intrinId, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_InstOpts options, int lineno = 0, int CISAoff = -1, const char* srcFilename = nullptr); G4_INST* createNop(G4_InstOpts options); G4_INST* createSync(G4_opcode syncOp, G4_Operand* src); G4_INST* createMov( G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_InstOpts options, bool appendToInstList); G4_INST* createBinOp( G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, bool appendToInstList) { return createBinOp(nullptr, op, execSize, dst, src0, src1, options, appendToInstList); } G4_INST* createBinOp( G4_Predicate *pred, G4_opcode op, G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, bool appendToInstList = true); G4_INST* createMach( G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, G4_Type accType); G4_INST* createMacl( G4_ExecSize execSize, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_InstOpts options, G4_Type accType); static G4_MathOp Get_MathFuncCtrl(ISA_Opcode op, G4_Type type); void resizePredefinedStackVars(); template <typename T> T* duplicateOperand(T* opnd) {return static_cast<T *>(duplicateOpndImpl(opnd));} G4_Operand* duplicateOpndImpl(G4_Operand* opnd); G4_DstRegRegion *createSubDstOperand( G4_DstRegRegion* dst, uint16_t start, uint8_t size); G4_SrcRegRegion *createSubSrcOperand( G4_SrcRegRegion* src, uint16_t start, uint8_t size, uint16_t newVs, uint16_t newWd); G4_INST *makeSplittingInst(G4_INST *inst, G4_ExecSize execSize); G4_InstSend *Create_Send_Inst_For_CISA( G4_Predicate *pred, G4_DstRegRegion *postDst, G4_SrcRegRegion *payload, G4_ExecSize execSize, G4_SendMsgDescriptor *msgDesc, G4_InstOpts options, bool is_sendc); G4_InstSend *Create_SplitSend_Inst( G4_Predicate *pred, G4_DstRegRegion *dst, G4_SrcRegRegion *src1, G4_SrcRegRegion *src2, G4_ExecSize execSize, G4_SendMsgDescriptor *msgDesc, G4_InstOpts options, bool is_sendc); G4_InstSend *Create_SplitSend_Inst_For_RT( G4_Predicate *pred, G4_DstRegRegion *dst, G4_SrcRegRegion *src1, G4_SrcRegRegion *src2, G4_SrcRegRegion *extDesc, G4_ExecSize execSize, G4_SendMsgDescriptor *msgDesc, G4_InstOpts option); G4_InstSend* Create_Send_Inst_For_CISA( G4_Predicate* pred, G4_DstRegRegion* postDst, G4_SrcRegRegion* payload, unsigned regs2snd, unsigned regs2rcv, G4_ExecSize execsize, unsigned fc, SFID tf_id, bool head_present, SendAccess access, G4_Operand* bti, G4_Operand* sti, G4_InstOpts options, bool is_sendc); G4_InstSend* Create_SplitSend_Inst_For_CISA( G4_Predicate* pred, G4_DstRegRegion* dst, G4_SrcRegRegion* src1, unsigned regs2snd1, G4_SrcRegRegion* src2, unsigned regs2snd2, unsigned regs2rcv, G4_ExecSize execSize, unsigned fc, SFID tf_id, bool head_present, SendAccess access, G4_Operand* bti, G4_Operand* sti, G4_InstOpts option, bool is_sendc); // helper functions G4_Declare *createSendPayloadDcl(unsigned num_elt, G4_Type type); void Create_MOVR0_Inst( G4_Declare* dcl, short refOff, short subregOff, bool use_nomask = false); void Create_MOV_Inst( G4_Declare* dcl, short refOff, short subregOff, G4_ExecSize execsize, G4_Predicate* pred, G4_CondMod* condMod, G4_Operand* src_opnd, bool use_nomask = false); void Create_ADD_Inst( G4_Declare* dcl, short regOff, short subregOff, G4_ExecSize execSize, G4_Predicate* pred, G4_CondMod* condMod, G4_Operand* src0_opnd, G4_Operand* src1_opnd, G4_InstOption options); void Create_MOV_Send_Src_Inst( G4_Declare* dcl, short refOff, short subregOff, unsigned num_dword, G4_Operand* src_opnd, G4_InstOpts options); // short hand for creating a dstRegRegion G4_DstRegRegion* Create_Dst_Opnd_From_Dcl(G4_Declare* dcl, unsigned short hstride); G4_SrcRegRegion* Create_Src_Opnd_From_Dcl(G4_Declare* dcl, const RegionDesc* rd); // Create a null dst with scalar region and the given type G4_DstRegRegion* createNullDst(G4_Type dstType); // Create a null src with scalar region and the given type G4_SrcRegRegion* createNullSrc(G4_Type dstType); G4_DstRegRegion* Check_Send_Dst(G4_DstRegRegion *dst_opnd); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // translateXXXXXXX functions translate specific vISA instructions into // sequences of G4 IR that implement the operation // // Implementations are split amongst various files based on category. // Comments below will point the user to the correct implementation file. // Please keep implementations the same sequential order as in the header. // (Feel free to re-order, but reflect the re-order here.) // // During refactor anything that was in TranslationInterface.cpp was moved // to one of this VisaToG4/Translate* files, but some methods have nothing // to do with vISA and make sense in the BuildIRImpl.cpp and could be // moved there. Please move the declaration (prototype) upwards in // that case. /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Members related to general arithmetic/logic/shift ops are in // VisaToG4/TranslateALU.cpp int translateVISAAddrInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_DstRegRegion *dst_opnd, G4_Operand *src0_opnd, G4_Operand *src1_opnd); int translateVISAArithmeticInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Sat saturate, G4_CondMod* condMod, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd, G4_Operand *src2Opnd, G4_DstRegRegion *carryBorrow); int translateVISACompareInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, VISA_Cond_Mod relOp, G4_Declare* predDst, G4_Operand *src0_opnd, G4_Operand *src1_opnd); int translateVISACompareInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, VISA_Cond_Mod relOp, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd); int translateVISALogicInst( ISA_Opcode opcode, G4_Predicate *pred_opnd, G4_Sat saturate, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_DstRegRegion* dst, G4_Operand* src0, G4_Operand* src1, G4_Operand* src2, G4_Operand* src3); int translateVISADataMovementInst( ISA_Opcode opcode, CISA_MIN_MAX_SUB_OPCODE subOpcode, G4_Predicate *pred_opnd, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Sat saturate, G4_DstRegRegion *dst, G4_Operand *src0, G4_Operand *src1); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Control flow, function call, and branching ops are located in // VisaToG4/TranslateBranch.cpp int translateVISACFSwitchInst( G4_Operand *indexOpnd, uint8_t numLabels, G4_Label** lab); int translateVISACFLabelInst(G4_Label* lab); int translateVISACFCallInst( VISA_Exec_Size execsize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Label* lab); int translateVISACFJumpInst(G4_Predicate *predOpnd, G4_Label* lab); int translateVISACFFCallInst( VISA_Exec_Size execsize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, std::string funcName, uint8_t argSize, uint8_t returnSize); int translateVISACFIFCallInst( VISA_Exec_Size execsize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Operand* funcAddr, uint8_t argSize, uint8_t returnSize); int translateVISACFSymbolInst( const std::string& symbolName, G4_DstRegRegion* dst); int translateVISACFFretInst( VISA_Exec_Size execsize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd); int translateVISACFRetInst( VISA_Exec_Size execsize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd); int translateVISAGotoInst( G4_Predicate *predOpnd, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Label *label); /////////////////////////////////////////////////////////////////////////// // members related to special math sequences VisaToG4/TranslateMath.cpp void expandFdiv( G4_ExecSize exsize, G4_Predicate *predOpnd, G4_Sat saturate, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd, uint32_t instOpt); void expandPow( G4_ExecSize exsize, G4_Predicate *predOpnd, G4_Sat saturate, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd, uint32_t instOpt); int translateVISAArithmeticDoubleInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Sat saturate, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd); int translateVISAArithmeticSingleDivideIEEEInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Sat saturate, G4_CondMod* condMod, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd, G4_Operand *src1Opnd); int translateVISAArithmeticSingleSQRTIEEEInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Sat saturate, G4_CondMod* condMod, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd); int translateVISAArithmeticDoubleSQRTInst( ISA_Opcode opcode, VISA_Exec_Size execSize, VISA_EMask_Ctrl emask, G4_Predicate *predOpnd, G4_Sat saturate, G4_CondMod* condMod, G4_DstRegRegion *dstOpnd, G4_Operand *src0Opnd); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Members related miscellaneous instructions that don't fit any other // category are in VisaToG4/TranslateMisc.cpp // // (As stated above some of this could move to BuildIRImpl.cpp.) static bool isNoMask(VISA_EMask_Ctrl eMask); static G4_ExecSize toExecSize(VISA_Exec_Size execSize); VISA_Exec_Size roundUpExecSize(VISA_Exec_Size execSize); G4_Declare* getImmDcl(G4_Imm* val, int numElt); struct PayloadSource { G4_SrcRegRegion *opnd; G4_ExecSize execSize; G4_InstOpts instOpt; }; /// preparePayload - This method prepares payload from the specified header /// and sources. /// /// \param msgs Message(s) prepared. That 2-element array must /// be cleared before calling preparePayload(). /// \param sizes Size(s) (in GRF) of each message prepared. That /// 2-element array must be cleared before calling /// preparePayload(). /// \param batchExSize When it's required to copy sources, batchExSize /// specifies the SIMD width of copy. /// \param splitSendEnabled Whether feature split-send is available. When /// feature split-send is available, this function /// will check whether two consecutive regions /// could be prepared instead of one to take /// advantage of split-send. /// \param srcs The array of sources (including header if /// present). /// \param len The length of the array of sources. /// void preparePayload( G4_SrcRegRegion *msgs[2], unsigned sizes[2], G4_ExecSize batchExSize, bool splitSendEnabled, PayloadSource sources[], unsigned len); // Coalesce multiple payloads into a single region. Pads each region with // an optional alignment argument (e.g. a GRF size). The source region // sizes are determined by source dimension, so use an alias if you are // using a subregion. All copies are made under no mask semantics using // the maximal SIMD width for the current device. // // A second alignment option allows a caller to align the full payload // to some total. // // If all parameters are nullptr or the null register, we return the null // register. // // Some examples: // // 1. coalescePayloads(GRF_SIZE,GRF_SIZE,...); // Coalesces each source into a single region. Each source is padded // out to a full GRF, and the sum total result is also padded out to // a full GRF. // // 2. coalescePayloads(1,GRF_SIZE,...); // Coalesces each source into a single region packing each source // together, but padding the result. E.g. one could copy a QW and then // a DW and pad the result out to a GRF. // G4_SrcRegRegion *coalescePayload( unsigned alignSourcesTo, unsigned alignPayloadTo, uint32_t payloadSize, uint32_t srcSize, std::initializer_list<G4_SrcRegRegion *> srcs, VISA_EMask_Ctrl emask); // emask is InstOption void Copy_SrcRegRegion_To_Payload( G4_Declare* payload, unsigned int& regOff, G4_SrcRegRegion* src, G4_ExecSize execSize, uint32_t emask); unsigned int getByteOffsetSrcRegion(G4_SrcRegRegion* srcRegion); // only used in TranslateSend3D, maybe consider moving there if no // one else uses them. bool checkIfRegionsAreConsecutive( G4_SrcRegRegion* first, G4_SrcRegRegion* second, G4_ExecSize execSize); bool checkIfRegionsAreConsecutive( G4_SrcRegRegion* first, G4_SrcRegRegion* second, G4_ExecSize execSize, G4_Type type); int generateDebugInfoPlaceholder(); // TODO: move to BuildIRImpl.cpp? // legitimiately belongs in Misc int translateVISALifetimeInst(unsigned char properties, G4_Operand* var); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // members related to 3D and sampler ops are in VisaToG4/TranslateSend3D.cpp int translateVISASampleInfoInst( VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, ChannelMask chMask, G4_Operand* surface, G4_DstRegRegion* dst); int translateVISAResInfoInst( VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, ChannelMask chMask, G4_Operand* surface, G4_SrcRegRegion* lod, G4_DstRegRegion* dst); int translateVISAURBWrite3DInst( G4_Predicate* pred, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, uint8_t numOut, uint16_t globalOffset, G4_SrcRegRegion* channelMask, G4_SrcRegRegion* urbHandle, G4_SrcRegRegion* perSlotOffset, G4_SrcRegRegion* vertexData); int translateVISARTWrite3DInst( G4_Predicate* pred, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Operand *surface, G4_SrcRegRegion *r1HeaderOpnd, G4_Operand *rtIndex, vISA_RT_CONTROLS cntrls, G4_SrcRegRegion *sampleIndexOpnd, G4_Operand *cpsCounter, unsigned int numParms, G4_SrcRegRegion ** msgOpnds); int splitSampleInst( VISASampler3DSubOpCode actualop, bool pixelNullMask, bool cpsEnable, G4_Predicate* pred, ChannelMask srcChannel, int numChannels, G4_Operand *aoffimmi, G4_Operand *sampler, G4_Operand *surface, G4_DstRegRegion* dst, VISA_EMask_Ctrl emask, bool useHeader, unsigned numRows, // msg length for each simd8 unsigned int numParms, G4_SrcRegRegion ** params, bool uniformSampler = true); void doSamplerHeaderMove(G4_Declare* header, G4_Operand* sampler); G4_Declare* getSamplerHeader(bool isBindlessSampler, bool samplerIndexGE16); uint32_t getSamplerResponseLength( int numChannels, bool isFP16, int execSize, bool pixelNullMask, bool nullDst); int translateVISASampler3DInst( VISASampler3DSubOpCode actualop, bool pixelNullMask, bool cpsEnable, bool uniformSampler, G4_Predicate* pred, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, ChannelMask srcChannel, G4_Operand* aoffimmi, G4_Operand *sampler, G4_Operand *surface, G4_DstRegRegion* dst, unsigned int numParms, G4_SrcRegRegion ** params); int translateVISALoad3DInst( VISASampler3DSubOpCode actualop, bool pixelNullMask, G4_Predicate *pred, VISA_Exec_Size exeuctionSize, VISA_EMask_Ctrl em, ChannelMask channelMask, G4_Operand* aoffimmi, G4_Operand* surface, G4_DstRegRegion* dst, uint8_t numOpnds, G4_SrcRegRegion ** opndArray); int translateVISAGather3dInst( VISASampler3DSubOpCode actualop, bool pixelNullMask, G4_Predicate* pred, VISA_Exec_Size exeuctionSize, VISA_EMask_Ctrl em, ChannelMask channelMask, G4_Operand* aoffimmi, G4_Operand* sampler, G4_Operand* surface, G4_DstRegRegion* dst, unsigned int numOpnds, G4_SrcRegRegion ** opndArray); int translateVISASamplerNormInst( G4_Operand* surface, G4_Operand* sampler, ChannelMask channel, unsigned numEnabledChannels, G4_Operand* deltaUOpnd, G4_Operand* uOffOpnd, G4_Operand* deltaVOpnd, G4_Operand* vOffOpnd, G4_DstRegRegion* dst_opnd); int translateVISASamplerInst( unsigned simdMode, G4_Operand* surface, G4_Operand* sampler, ChannelMask channel, unsigned numEnabledChannels, G4_Operand* uOffOpnd, G4_Operand* vOffOpnd, G4_Operand* rOffOpnd, G4_DstRegRegion* dstOpnd); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // basic load and store (type and untyped) are located in // VisaToG4/TranslateSendLdStLegacy.cpp // IsHeaderOptional - Check whether the message header is optional. bool isMessageHeaderOptional(G4_Operand *surface, G4_Operand *Offset) const; // IsStatelessSurface - Check whether the give surface is statelesss surface. static bool isStatelessSurface(const G4_Operand *surface) { // So far, it's only reliable to check an immediate surface. return surface->isImm() && (surface->asImm()->getImm() == PREDEF_SURF_255 || surface->asImm()->getImm() == PREDEF_SURF_253); } uint32_t setOwordForDesc(uint32_t desc, int numOword, bool isSLM = false) const; int translateVISAOwordLoadInst( ISA_Opcode opcode, bool modified, G4_Operand* surface, VISA_Oword_Num size, G4_Operand* offOpnd, G4_DstRegRegion* dstOpnd); int translateVISAOwordStoreInst( G4_Operand* surface, VISA_Oword_Num size, G4_Operand* offOpnd, G4_SrcRegRegion* srcOpnd); int translateVISAGatherInst( VISA_EMask_Ctrl emask, bool modified, GATHER_SCATTER_ELEMENT_SIZE eltSize, VISA_Exec_Size executionSize, G4_Operand* surface, G4_Operand* gOffOpnd, G4_SrcRegRegion* eltOFfOpnd, G4_DstRegRegion* dstOpnd); int translateVISAScatterInst( VISA_EMask_Ctrl emask, GATHER_SCATTER_ELEMENT_SIZE eltSize, VISA_Exec_Size executionSize, G4_Operand* surface, G4_Operand* gOffOpnd, G4_SrcRegRegion* eltOffOpnd, G4_SrcRegRegion* srcOpnd); int translateVISAGather4Inst( VISA_EMask_Ctrl emask, bool modified, ChannelMask chMask, VISA_Exec_Size executionSize, G4_Operand* surface, G4_Operand* gOffOpnd, G4_SrcRegRegion* eltOffOpnd, G4_DstRegRegion* dstOpnd); int translateVISAScatter4Inst( VISA_EMask_Ctrl emask, ChannelMask chMask, VISA_Exec_Size executionSize, G4_Operand* surface, G4_Operand* gOffOpnd, G4_SrcRegRegion* eltOffOpnd, G4_SrcRegRegion* srcOpnd); int translateVISADwordAtomicInst( VISAAtomicOps subOpc, bool is16Bit, G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, G4_Operand* surface, G4_SrcRegRegion* offsets, G4_SrcRegRegion* src0, G4_SrcRegRegion* src1, G4_DstRegRegion* dst); void buildTypedSurfaceAddressPayload( G4_SrcRegRegion* u, G4_SrcRegRegion* v, G4_SrcRegRegion* r, G4_SrcRegRegion* lod, G4_ExecSize execSize, G4_InstOpts instOpt, PayloadSource sources[], uint32_t& len); int translateVISAGather4TypedInst( G4_Predicate *pred, VISA_EMask_Ctrl emask, ChannelMask chMask, G4_Operand *surfaceOpnd, VISA_Exec_Size executionSize, G4_SrcRegRegion *uOffsetOpnd, G4_SrcRegRegion *vOffsetOpnd, G4_SrcRegRegion *rOffsetOpnd, G4_SrcRegRegion *lodOpnd, G4_DstRegRegion *dstOpnd); int translateVISAScatter4TypedInst( G4_Predicate *pred, VISA_EMask_Ctrl emask, ChannelMask chMask, G4_Operand *surfaceOpnd, VISA_Exec_Size executionSize, G4_SrcRegRegion *uOffsetOpnd, G4_SrcRegRegion *vOffsetOpnd, G4_SrcRegRegion *rOffsetOpnd, G4_SrcRegRegion *lodOpnd, G4_SrcRegRegion *srcOpnd); int translateVISATypedAtomicInst( VISAAtomicOps atomicOp, bool is16Bit, G4_Predicate *pred, VISA_EMask_Ctrl emask, VISA_Exec_Size execSize, G4_Operand *surface, G4_SrcRegRegion *uOffsetOpnd, G4_SrcRegRegion *vOffsetOpnd, G4_SrcRegRegion *rOffsetOpnd, G4_SrcRegRegion *lodOpnd, G4_SrcRegRegion *src0, G4_SrcRegRegion *src1, G4_DstRegRegion *dst); void applySideBandOffset(G4_Operand* sideBand, G4_SendMsgDescriptor* sendMsgDesc); int translateVISASLMUntypedScaledInst( bool isRead, G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, uint16_t scale, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_Operand *srcOrDst); int translateVISAGather4ScaledInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateVISAScatter4ScaledInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); int translateGather4Inst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateScatter4Inst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); int translateVISAGatherScaledInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, VISA_SVM_Block_Num numBlocks, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateVISAScatterScaledInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, VISA_SVM_Block_Num numBlocks, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); int translateVISASLMByteScaledInst( bool isRead, G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, VISA_SVM_Block_Type blockSize, VISA_SVM_Block_Num numBlocks, uint8_t scale, G4_Operand *sideBand, G4_SrcRegRegion *offsets, G4_Operand *srcOrDst); int translateByteGatherInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, VISA_SVM_Block_Num numBlocks, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateByteScatterInst( G4_Predicate *pred, VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, VISA_SVM_Block_Num numBlocks, G4_Operand *surface, G4_Operand *globalOffset, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); int translateVISASVMBlockReadInst( VISA_Oword_Num numOword, bool unaligned, G4_Operand* address, G4_DstRegRegion* dst); int translateVISASVMBlockWriteInst( VISA_Oword_Num numOword, G4_Operand* address, G4_SrcRegRegion* src); int translateVISASVMScatterReadInst( VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Predicate* pred, VISA_SVM_Block_Type blockSize, VISA_SVM_Block_Num numBlocks, G4_SrcRegRegion* addresses, G4_DstRegRegion* dst); int translateVISASVMScatterWriteInst( VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Predicate* pred, VISA_SVM_Block_Type blockSize, VISA_SVM_Block_Num numBlocks, G4_SrcRegRegion* addresses, G4_SrcRegRegion* src); int translateVISASVMAtomicInst( VISAAtomicOps op, unsigned short bitwidth, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, G4_Predicate* pred, G4_SrcRegRegion* addresses, G4_SrcRegRegion* src0, G4_SrcRegRegion* src1, G4_DstRegRegion* dst); // return globalOffset + offsets as a contiguous operand G4_SrcRegRegion* getSVMOffset( G4_Operand* globalOffset, G4_SrcRegRegion* offsets, uint16_t exSize, G4_Predicate* pred, uint32_t mask); int translateSVMGather4Inst( VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Predicate *pred, G4_Operand *address, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateSVMScatter4Inst( VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Predicate *pred, G4_Operand *address, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); int translateVISASVMGather4ScaledInst( VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Predicate *pred, G4_Operand *address, G4_SrcRegRegion *offsets, G4_DstRegRegion *dst); int translateVISASVMScatter4ScaledInst( VISA_Exec_Size execSize, VISA_EMask_Ctrl eMask, ChannelMask chMask, G4_Predicate *pred, G4_Operand *address, G4_SrcRegRegion *offsets, G4_SrcRegRegion *src); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // members related to media and VME are in VisaToG4/TranslateSendMedia.cpp int translateVISAMediaLoadInst( MEDIA_LD_mod mod, G4_Operand* surface, unsigned planeID, unsigned blockWidth, unsigned blockHeight, G4_Operand* xOffOpnd, G4_Operand* yOffOpnd, G4_DstRegRegion* dst_opnd); int translateVISAMediaStoreInst( MEDIA_ST_mod mod, G4_Operand* surface, unsigned planeID, unsigned blockWidth, unsigned blockHeight, G4_Operand* xOffOpnd, G4_Operand* yOffOpnd, G4_SrcRegRegion* srcOpnd); int translateVISAVmeImeInst( uint8_t stream_mode, uint8_t search_ctrl, G4_Operand* surfaceOpnd, G4_Operand* uniInputOpnd, G4_Operand* imeInputOpnd, G4_Operand* ref0Opnd, G4_Operand* ref1Opnd, G4_Operand* costCenterOpnd, G4_DstRegRegion* outputOpnd); int translateVISAVmeSicInst( G4_Operand* surfaceOpnd, G4_Operand* uniInputOpnd, G4_Operand* sicInputOpnd, G4_DstRegRegion* outputOpnd); int translateVISAVmeFbrInst( G4_Operand* surfaceOpnd, G4_Operand* unitInputOpnd, G4_Operand* fbrInputOpnd, G4_Operand* fbrMbModOpnd, G4_Operand* fbrSubMbShapeOpnd, G4_Operand* fbrSubPredModeOpnd, G4_DstRegRegion* outputOpnd); int translateVISAVmeIdmInst( G4_Operand* surfaceOpnd, G4_Operand* unitInputOpnd, G4_Operand* idmInputOpnd, G4_DstRegRegion* outputOpnd); int translateVISASamplerVAGenericInst( G4_Operand* surface, G4_Operand* sampler, G4_Operand* uOffOpnd, G4_Operand* vOffOpnd, G4_Operand* vSizeOpnd, G4_Operand* hSizeOpnd, G4_Operand* mmfMode, unsigned char cntrl, unsigned char msgSeq, VA_fopcode fopcode, G4_DstRegRegion* dstOpnd, G4_Type dstType, unsigned dstSize, bool isBigKernel = false); int translateVISAAvsInst( G4_Operand* surface, G4_Operand* sampler, ChannelMask channel, unsigned numEnabledChannels, G4_Operand* deltaUOpnd, G4_Operand* uOffOpnd, G4_Operand* deltaVOpnd, G4_Operand* vOffOpnd, G4_Operand* u2dOpnd, G4_Operand* groupIDOpnd, G4_Operand* verticalBlockNumberOpnd, unsigned char cntrl, G4_Operand* v2dOpnd, unsigned char execMode, G4_Operand* eifbypass, G4_DstRegRegion* dstOpnd); int translateVISAVaSklPlusGeneralInst( ISA_VA_Sub_Opcode sub_opcode, G4_Operand* surface, G4_Operand* sampler, unsigned char mode, unsigned char functionality, G4_Operand* uOffOpnd, G4_Operand* vOffOpnd, //1pixel convolve G4_Operand * offsetsOpnd, //FloodFill G4_Operand* loopCountOpnd, G4_Operand* pixelHMaskOpnd, G4_Operand* pixelVMaskLeftOpnd, G4_Operand* pixelVMaskRightOpnd, //LBP Correlation G4_Operand* disparityOpnd, //Correlation Search G4_Operand* verticalOriginOpnd, G4_Operand* horizontalOriginOpnd, G4_Operand* xDirectionSizeOpnd, G4_Operand* yDirectionSizeOpnd, G4_Operand* xDirectionSearchSizeOpnd, G4_Operand* yDirectionSearchSizeOpnd, G4_DstRegRegion* dstOpnd, G4_Type dstType, unsigned dstSize, //HDC unsigned char pixelSize, G4_Operand* dstSurfaceOpnd, G4_Operand *dstXOpnd, G4_Operand* dstYOpnd, bool hdcMode); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Raw send related members are in VisaToG4/TranslateSendRaw.cpp int translateVISARawSendInst( G4_Predicate *predOpnd, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, uint8_t modifiers, unsigned int exDesc, uint8_t numSrc, uint8_t numDst, G4_Operand* msgDescOpnd, G4_SrcRegRegion* msgOpnd, G4_DstRegRegion* dstOpnd); int translateVISARawSendsInst( G4_Predicate *predOpnd, VISA_Exec_Size executionSize, VISA_EMask_Ctrl emask, uint8_t modifiers, G4_Operand* exDesc, uint8_t numSrc0, uint8_t numSrc1, uint8_t numDst, G4_Operand* msgDescOpnd, G4_Operand* msgOpnd0, G4_Operand* msgOpnd1, G4_DstRegRegion* dstOpnd, unsigned ffid, bool hasEOT = false); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // Raw send related members are in VisaToG4/TranslateSendSync.cpp G4_INST* createFenceInstruction( uint8_t flushParam, bool commitEnable, bool globalMemFence, bool isSendc); G4_INST* createSLMFence(); int translateVISAWaitInst(G4_Operand* mask); void generateBarrierSend(); void generateBarrierWait(); int translateVISASyncInst(ISA_Opcode opcode, unsigned int mask); int translateVISASplitBarrierInst(bool isSignal); /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // return either 253 or 255 for A64 messages, depending on whether we want I/A coherency or not uint8_t getA64BTI() const { return m_options->getOption(vISA_noncoherentStateless) ? 0xFD : 0xFF; } bool useSends() const { return getPlatform() >= GENX_SKL && m_options->getOption(vISA_UseSends) && !(VISA_WA_CHECK(m_pWaTable, WaDisableSendsSrc0DstOverlap)); } Metadata* allocateMD() { Metadata* newMD = new (metadataMem) Metadata(); allMDs.push_back(newMD); return newMD; } MDNode* allocateMDString(const std::string& str) { auto newNode = new (metadataMem) MDString(str); allMDNodes.push_back(newNode); return newNode; } MDLocation* allocateMDLocation(int line, const char* file) { auto newNode = new (metadataMem) MDLocation(line, file); allMDNodes.push_back(newNode); return newNode; } void materializeGlobalImm(G4_BB* entryBB); // why is in FlowGraph.cpp??? #include "HWCaps.inc" private: const void* m_inst; G4_SrcRegRegion* createBindlessExDesc(uint32_t exdesc); }; } // namespace vISA // G4IR instructions added by JIT that do not result from lowering // any CISA bytecode will be assigned CISA offset = 0xffffffff. // This includes pseudo nodes, G4_labels, mov introduced for copying // r0 for pre-emption support. constexpr int UNMAPPABLE_VISA_INDEX = IR_Builder::OrphanVISAIndex; #endif
{ "language": "C++" }
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // This file was modified by Oracle on 2013, 2014, 2015. // Modifications copyright (c) 2013-2015 Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_IMPLEMENTATION_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_IMPLEMENTATION_HPP #include <boost/geometry/core/tags.hpp> #include <boost/geometry/algorithms/detail/relate/interface.hpp> #include <boost/geometry/algorithms/detail/relate/point_point.hpp> #include <boost/geometry/algorithms/detail/relate/point_geometry.hpp> #include <boost/geometry/algorithms/detail/relate/linear_linear.hpp> #include <boost/geometry/algorithms/detail/relate/linear_areal.hpp> #include <boost/geometry/algorithms/detail/relate/areal_areal.hpp> namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template <typename Point1, typename Point2> struct relate<Point1, Point2, point_tag, point_tag, 0, 0, false> : detail::relate::point_point<Point1, Point2> {}; template <typename Point, typename MultiPoint> struct relate<Point, MultiPoint, point_tag, multi_point_tag, 0, 0, false> : detail::relate::point_multipoint<Point, MultiPoint> {}; template <typename MultiPoint, typename Point> struct relate<MultiPoint, Point, multi_point_tag, point_tag, 0, 0, false> : detail::relate::multipoint_point<MultiPoint, Point> {}; template <typename MultiPoint1, typename MultiPoint2> struct relate<MultiPoint1, MultiPoint2, multi_point_tag, multi_point_tag, 0, 0, false> : detail::relate::multipoint_multipoint<MultiPoint1, MultiPoint2> {}; // TODO - for now commented out because before implementing it we must consider: // 1. how the Box degenerated to a Point should be treated // 2. what should be the definition of a Box degenerated to a Point // 3. what fields should the matrix/mask contain for dimension > 2 and dimension > 9 // //template <typename Point, typename Box, int TopDim2> //struct relate<Point, Box, point_tag, box_tag, 0, TopDim2, false> // : detail::relate::point_box<Point, Box> //{}; // //template <typename Box, typename Point, int TopDim1> //struct relate<Box, Point, box_tag, point_tag, TopDim1, 0, false> // : detail::relate::box_point<Box, Point> //{}; template <typename Point, typename Geometry, typename Tag2, int TopDim2> struct relate<Point, Geometry, point_tag, Tag2, 0, TopDim2, true> : detail::relate::point_geometry<Point, Geometry> {}; template <typename Geometry, typename Point, typename Tag1, int TopDim1> struct relate<Geometry, Point, Tag1, point_tag, TopDim1, 0, true> : detail::relate::geometry_point<Geometry, Point> {}; template <typename Linear1, typename Linear2, typename Tag1, typename Tag2> struct relate<Linear1, Linear2, Tag1, Tag2, 1, 1, true> : detail::relate::linear_linear<Linear1, Linear2> {}; template <typename Linear, typename Areal, typename Tag1, typename Tag2> struct relate<Linear, Areal, Tag1, Tag2, 1, 2, true> : detail::relate::linear_areal<Linear, Areal> {}; template <typename Areal, typename Linear, typename Tag1, typename Tag2> struct relate<Areal, Linear, Tag1, Tag2, 2, 1, true> : detail::relate::areal_linear<Areal, Linear> {}; template <typename Areal1, typename Areal2, typename Tag1, typename Tag2> struct relate<Areal1, Areal2, Tag1, Tag2, 2, 2, true> : detail::relate::areal_areal<Areal1, Areal2> {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_RELATE_IMPLEMENTATION_HPP
{ "language": "C++" }
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // 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 <google/protobuf/unittest.pb.h> #include <google/protobuf/unittest_preserve_unknown_enum.pb.h> #include <google/protobuf/unittest_preserve_unknown_enum2.pb.h> #include <google/protobuf/dynamic_message.h> #include <google/protobuf/descriptor.h> #include <gtest/gtest.h> namespace google { namespace protobuf { namespace { void FillMessage( proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra* message) { message->set_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); message->add_repeated_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); message->add_repeated_packed_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); message->add_repeated_packed_unexpected_e( proto3_preserve_unknown_enum_unittest::E_EXTRA); message->set_oneof_e_1( proto3_preserve_unknown_enum_unittest::E_EXTRA); } void CheckMessage( const proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra& message) { EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.e()); EXPECT_EQ(1, message.repeated_e_size()); EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.repeated_e(0)); EXPECT_EQ(1, message.repeated_packed_e_size()); EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.repeated_packed_e(0)); EXPECT_EQ(1, message.repeated_packed_unexpected_e_size()); EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.repeated_packed_unexpected_e(0)); EXPECT_EQ(proto3_preserve_unknown_enum_unittest::E_EXTRA, message.oneof_e_1()); } void CheckMessage( const proto3_preserve_unknown_enum_unittest::MyMessage& message) { EXPECT_EQ(static_cast<int>( proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast<int>(message.e())); EXPECT_EQ(1, message.repeated_e_size()); EXPECT_EQ(static_cast<int>( proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast<int>(message.repeated_e(0))); EXPECT_EQ(1, message.repeated_packed_e_size()); EXPECT_EQ(static_cast<int>( proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast<int>(message.repeated_packed_e(0))); EXPECT_EQ(1, message.repeated_packed_unexpected_e_size()); EXPECT_EQ(static_cast<int>( proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast<int>(message.repeated_packed_unexpected_e(0))); EXPECT_EQ(static_cast<int>( proto3_preserve_unknown_enum_unittest::E_EXTRA), static_cast<int>(message.oneof_e_1())); } } // anonymous namespace // Test that parsing preserves an unknown value in the enum field and does not // punt it to the UnknownFieldSet. TEST(PreserveUnknownEnumTest, PreserveParseAndSerialize) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); string serialized; orig_message.SerializeToString(&serialized); proto3_preserve_unknown_enum_unittest::MyMessage message; EXPECT_EQ(true, message.ParseFromString(serialized)); CheckMessage(message); serialized.clear(); message.SerializeToString(&serialized); EXPECT_EQ(true, orig_message.ParseFromString(serialized)); CheckMessage(orig_message); } // Test that reflection based implementation also keeps unknown enum values and // doesn't put them into UnknownFieldSet. TEST(PreserveUnknownEnumTest, PreserveParseAndSerializeDynamicMessage) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); string serialized = orig_message.SerializeAsString(); google::protobuf::DynamicMessageFactory factory; google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype( proto3_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); message->DiscardUnknownFields(); serialized = message->SerializeAsString(); EXPECT_EQ(true, orig_message.ParseFromString(serialized)); CheckMessage(orig_message); } // Test that for proto2 messages, unknown values are in unknown fields. TEST(PreserveUnknownEnumTest, Proto2HidesUnknownValues) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); string serialized; orig_message.SerializeToString(&serialized); proto2_preserve_unknown_enum_unittest::MyMessage message; EXPECT_EQ(true, message.ParseFromString(serialized)); // The intermediate message has everything in its "unknown fields". proto2_preserve_unknown_enum_unittest::MyMessage message2 = message; message2.DiscardUnknownFields(); EXPECT_EQ(0, message2.ByteSize()); // But when we pass it to the correct structure, all values are there. serialized.clear(); message.SerializeToString(&serialized); EXPECT_EQ(true, orig_message.ParseFromString(serialized)); CheckMessage(orig_message); } // Same as before, for a dynamic message. TEST(PreserveUnknownEnumTest, DynamicProto2HidesUnknownValues) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); string serialized; orig_message.SerializeToString(&serialized); google::protobuf::DynamicMessageFactory factory; google::protobuf::scoped_ptr<google::protobuf::Message> message(factory.GetPrototype( proto2_preserve_unknown_enum_unittest::MyMessage::descriptor())->New()); EXPECT_EQ(true, message->ParseFromString(serialized)); // The intermediate message has everything in its "unknown fields". proto2_preserve_unknown_enum_unittest::MyMessage message2; message2.CopyFrom(*message); message2.DiscardUnknownFields(); EXPECT_EQ(0, message2.ByteSize()); // But when we pass it to the correct structure, all values are there. serialized.clear(); message->SerializeToString(&serialized); EXPECT_EQ(true, orig_message.ParseFromString(serialized)); CheckMessage(orig_message); } // Test that reflection provides EnumValueDescriptors for unknown values. TEST(PreserveUnknownEnumTest, DynamicEnumValueDescriptors) { proto3_preserve_unknown_enum_unittest::MyMessagePlusExtra orig_message; FillMessage(&orig_message); string serialized; orig_message.SerializeToString(&serialized); proto3_preserve_unknown_enum_unittest::MyMessage message; EXPECT_EQ(true, message.ParseFromString(serialized)); CheckMessage(message); const google::protobuf::Reflection* r = message.GetReflection(); const google::protobuf::Descriptor* d = message.GetDescriptor(); const google::protobuf::FieldDescriptor* field = d->FindFieldByName("e"); // This should dynamically create an EnumValueDescriptor. const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message, field); EXPECT_EQ(enum_value->number(), static_cast<int>(proto3_preserve_unknown_enum_unittest::E_EXTRA)); // Fetching value for a second time should return the same pointer. const google::protobuf::EnumValueDescriptor* enum_value_second = r->GetEnum(message, field); EXPECT_EQ(enum_value, enum_value_second); // Check the repeated case too. const google::protobuf::FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e"); enum_value = r->GetRepeatedEnum(message, repeated_field, 0); EXPECT_EQ(enum_value->number(), static_cast<int>(proto3_preserve_unknown_enum_unittest::E_EXTRA)); // Should reuse the same EnumValueDescriptor, even for a different field. EXPECT_EQ(enum_value, enum_value_second); // We should be able to use the returned value descriptor to set a value on // another message. google::protobuf::Message* m = message.New(); r->SetEnum(m, field, enum_value); EXPECT_EQ(enum_value, r->GetEnum(*m, field)); delete m; } // Test that the new integer-based enum reflection API works. TEST(PreserveUnknownEnumTest, IntegerEnumReflectionAPI) { proto3_preserve_unknown_enum_unittest::MyMessage message; const google::protobuf::Reflection* r = message.GetReflection(); const google::protobuf::Descriptor* d = message.GetDescriptor(); const google::protobuf::FieldDescriptor* singular_field = d->FindFieldByName("e"); const google::protobuf::FieldDescriptor* repeated_field = d->FindFieldByName("repeated_e"); r->SetEnumValue(&message, singular_field, 42); EXPECT_EQ(42, r->GetEnumValue(message, singular_field)); r->AddEnumValue(&message, repeated_field, 42); r->AddEnumValue(&message, repeated_field, 42); EXPECT_EQ(42, r->GetRepeatedEnumValue(message, repeated_field, 0)); r->SetRepeatedEnumValue(&message, repeated_field, 1, 84); EXPECT_EQ(84, r->GetRepeatedEnumValue(message, repeated_field, 1)); const google::protobuf::EnumValueDescriptor* enum_value = r->GetEnum(message, singular_field); EXPECT_EQ(42, enum_value->number()); } // Test that the EnumValue API works properly for proto2 messages as well. TEST(PreserveUnknownEnumTest, Proto2CatchesUnknownValues) { protobuf_unittest::TestAllTypes message; // proto2 message const google::protobuf::Reflection* r = message.GetReflection(); const google::protobuf::Descriptor* d = message.GetDescriptor(); const google::protobuf::FieldDescriptor* repeated_field = d->FindFieldByName("repeated_nested_enum"); // Add one element to the repeated field so that we can test // SetRepeatedEnumValue. const google::protobuf::EnumValueDescriptor* enum_value = repeated_field->enum_type()->FindValueByName("BAR"); EXPECT_TRUE(enum_value != NULL); r->AddEnum(&message, repeated_field, enum_value); #ifdef PROTOBUF_HAS_DEATH_TEST const google::protobuf::FieldDescriptor* singular_field = d->FindFieldByName("optional_nested_enum"); // Enum-field integer-based setters GOOGLE_DCHECK-fail on invalid values, in order to // remain consistent with proto2 generated code. EXPECT_DEBUG_DEATH({ r->SetEnumValue(&message, singular_field, 4242); r->GetEnum(message, singular_field)->number(); }, "SetEnumValue accepts only valid integer values"); EXPECT_DEBUG_DEATH({ r->SetRepeatedEnumValue(&message, repeated_field, 0, 4242); r->GetRepeatedEnum(message, repeated_field, 0); }, "SetRepeatedEnumValue accepts only valid integer values"); EXPECT_DEBUG_DEATH({ r->AddEnumValue(&message, repeated_field, 4242); r->GetRepeatedEnum(message, repeated_field, 1); }, "AddEnumValue accepts only valid integer values"); #endif // PROTOBUF_HAS_DEATH_TEST } TEST(PreserveUnknownEnumTest, SupportsUnknownEnumValuesAPI) { protobuf_unittest::TestAllTypes proto2_message; proto3_preserve_unknown_enum_unittest::MyMessage new_message; const google::protobuf::Reflection* proto2_reflection = proto2_message.GetReflection(); const google::protobuf::Reflection* new_reflection = new_message.GetReflection(); EXPECT_FALSE(proto2_reflection->SupportsUnknownEnumValues()); EXPECT_TRUE(new_reflection->SupportsUnknownEnumValues()); } } // namespace protobuf } // namespace google
{ "language": "C++" }
#ifndef _LIBCPP_TYPE_TRAITS #define _LIBCPP_TYPE_TRAITS template <class _Tp> struct underlying_type { typedef __underlying_type(_Tp) type; }; #endif // _LIBCPP_TYPE_TRAITS
{ "language": "C++" }
/* * 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. */ /** \file * \ingroup freestyle */ #ifndef __FREESTYLE_PYTHON_UNARYPREDICATE1D_H__ #define __FREESTYLE_PYTHON_UNARYPREDICATE1D_H__ extern "C" { #include <Python.h> } #include "../stroke/Predicates1D.h" using namespace Freestyle; #ifdef __cplusplus extern "C" { #endif /////////////////////////////////////////////////////////////////////////////////////////// extern PyTypeObject UnaryPredicate1D_Type; #define BPy_UnaryPredicate1D_Check(v) \ (PyObject_IsInstance((PyObject *)v, (PyObject *)&UnaryPredicate1D_Type)) /*---------------------------Python BPy_UnaryPredicate1D structure definition----------*/ typedef struct { PyObject_HEAD UnaryPredicate1D *up1D; } BPy_UnaryPredicate1D; /*---------------------------Python BPy_UnaryPredicate1D visible prototypes-----------*/ int UnaryPredicate1D_Init(PyObject *module); /////////////////////////////////////////////////////////////////////////////////////////// #ifdef __cplusplus } #endif #endif /* __FREESTYLE_PYTHON_UNARYPREDICATE1D_H__ */
{ "language": "C++" }
/* * Copyright (c) 2007, 2018, Oracle and/or its affiliates. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2.0, * as published by the Free Software Foundation. * * This program is also distributed with certain software (including * but not limited to OpenSSL) that is licensed under separate terms, as * designated in a particular file or component or in included license * documentation. The authors of MySQL hereby grant you an additional * permission to link the program and your derivative works with the * separately licensed software that they have included with MySQL. * 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ #include "text_input_dialog.h" #include "grt/common.h" #include "base/string_utilities.h" using namespace grtui; TextInputDialog::TextInputDialog(mforms::Form *owner) : mforms::Form(owner, mforms::FormResizable), _button_box(true) { set_name("Input Dialog"); setInternalName("input_dialog"); _table.set_padding(12); _table.set_row_count(3); _table.set_column_count(2); _table.add(&_description, 1, 2, 0, 1); _table.add(&_caption, 0, 1, 1, 2); _table.add(&_input, 1, 2, 1, 2); _table.set_row_spacing(8); _table.set_column_spacing(8); _table.add(&_button_box, 0, 2, 2, 3); _button_box.set_spacing(8); _cancel_button.set_text(_("Cancel")); _cancel_button.enable_internal_padding(true); _ok_button.set_text(_("OK")); _ok_button.enable_internal_padding(true); _button_box.add_end(&_cancel_button, false, true); _button_box.add_end(&_ok_button, false, true); set_content(&_table); set_size(350, 150); } void TextInputDialog::set_description(const std::string &text) { _description.set_text(text); } void TextInputDialog::set_caption(const std::string &text) { _caption.set_text(text); } void TextInputDialog::set_value(const std::string &text) { _input.set_value(text); } std::string TextInputDialog::get_value() { return _input.get_string_value(); } bool TextInputDialog::run() { return run_modal(&_ok_button, &_cancel_button); }
{ "language": "C++" }
// 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. #ifndef UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_ #define UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_ #include <memory> #include "base/macros.h" #include "base/time/time.h" #include "cc/animation/animation_curve.h" #include "cc/animation/transform_operations.h" #include "ui/compositor/compositor_export.h" #include "ui/gfx/animation/tween.h" #include "ui/gfx/transform.h" #include "ui/gfx/transform_util.h" namespace ui { class COMPOSITOR_EXPORT TransformAnimationCurveAdapter : public cc::TransformAnimationCurve { public: TransformAnimationCurveAdapter(gfx::Tween::Type tween_type, gfx::Transform intial_value, gfx::Transform target_value, base::TimeDelta duration); TransformAnimationCurveAdapter(const TransformAnimationCurveAdapter& other); ~TransformAnimationCurveAdapter() override; // TransformAnimationCurve implementation. base::TimeDelta Duration() const override; std::unique_ptr<AnimationCurve> Clone() const override; cc::TransformOperations GetValue(base::TimeDelta t) const override; bool IsTranslation() const override; bool PreservesAxisAlignment() const override; bool AnimationStartScale(bool forward_direction, float* start_scale) const override; bool MaximumTargetScale(bool forward_direction, float* max_scale) const override; private: gfx::Tween::Type tween_type_; gfx::Transform initial_value_; cc::TransformOperations initial_wrapped_value_; gfx::Transform target_value_; cc::TransformOperations target_wrapped_value_; gfx::DecomposedTransform decomposed_initial_value_; gfx::DecomposedTransform decomposed_target_value_; base::TimeDelta duration_; DISALLOW_ASSIGN(TransformAnimationCurveAdapter); }; class COMPOSITOR_EXPORT InverseTransformCurveAdapter : public cc::TransformAnimationCurve { public: InverseTransformCurveAdapter(TransformAnimationCurveAdapter base_curve, gfx::Transform initial_value, base::TimeDelta duration); ~InverseTransformCurveAdapter() override; base::TimeDelta Duration() const override; std::unique_ptr<AnimationCurve> Clone() const override; cc::TransformOperations GetValue(base::TimeDelta t) const override; bool IsTranslation() const override; bool PreservesAxisAlignment() const override; bool AnimationStartScale(bool forward_direction, float* start_scale) const override; bool MaximumTargetScale(bool forward_direction, float* max_scale) const override; private: TransformAnimationCurveAdapter base_curve_; gfx::Transform initial_value_; cc::TransformOperations initial_wrapped_value_; gfx::Transform effective_initial_value_; base::TimeDelta duration_; DISALLOW_ASSIGN(InverseTransformCurveAdapter); }; } // namespace ui #endif // UI_COMPOSITOR_TRANSFORM_ANIMATION_CURVE_ADAPTER_H_
{ "language": "C++" }
/* * Copyright 2004-2006, Jérôme DUVAL. All rights reserved. * Copyright 2010, Karsten Heimrich. All rights reserved. * Copyright 2013, Rene Gollent, rene@gollent.com. * Distributed under the terms of the MIT License. */ #include "ExpanderWindow.h" #include <algorithm> #include <Alert.h> #include <Box.h> #include <Button.h> #include <Catalog.h> #include <CheckBox.h> #include <ControlLook.h> #include <Entry.h> #include <File.h> #include <LayoutBuilder.h> #include <Locale.h> #include <Menu.h> #include <MenuBar.h> #include <MenuItem.h> #include <Path.h> #include <Screen.h> #include <ScrollView.h> #include <StringView.h> #include <TextView.h> #include "ExpanderApp.h" #include "ExpanderThread.h" #include "ExpanderPreferences.h" #include "PasswordAlert.h" const uint32 MSG_SOURCE = 'mSOU'; const uint32 MSG_DEST = 'mDES'; const uint32 MSG_EXPAND = 'mEXP'; const uint32 MSG_SHOW = 'mSHO'; const uint32 MSG_STOP = 'mSTO'; const uint32 MSG_PREFERENCES = 'mPRE'; const uint32 MSG_SOURCETEXT = 'mSTX'; const uint32 MSG_DESTTEXT = 'mDTX'; const uint32 MSG_SHOWCONTENTS = 'mSCT'; class StatusView : public BStringView { public: StatusView() : BStringView(NULL, "") { } virtual ~StatusView() { } void SetStatus(const BString &text) { fStatus = text; Invalidate(); } void Draw(BRect updateRect) { BString truncated = fStatus; if(fStatus.IsEmpty() == false) { be_plain_font->TruncateString(&truncated, B_TRUNCATE_END, Bounds().Width()); } SetText(truncated); BStringView::Draw(updateRect); } private: BString fStatus; }; #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ExpanderWindow" ExpanderWindow::ExpanderWindow(BRect frame, const entry_ref* ref, BMessage* settings) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME("Expander"), B_TITLED_WINDOW, B_NORMAL_WINDOW_FEEL), fSourcePanel(NULL), fDestPanel(NULL), fSourceChanged(true), fListingThread(NULL), fListingStarted(false), fExpandingThread(NULL), fExpandingStarted(false), fSettings(*settings), fPreferences(NULL) { _CreateMenuBar(); fDestButton = new BButton(B_TRANSLATE("Destination"), new BMessage(MSG_DEST)); fSourceButton = new BButton(B_TRANSLATE("Source"), new BMessage(MSG_SOURCE)); fExpandButton = new BButton(B_TRANSLATE("Expand"), new BMessage(MSG_EXPAND)); BSize size = fDestButton->PreferredSize(); size.width = std::max(size.width, fSourceButton->PreferredSize().width); size.width = std::max(size.width, fExpandButton->PreferredSize().width); fDestButton->SetExplicitSize(size); fSourceButton->SetExplicitSize(size); fExpandButton->SetExplicitSize(size); fListingText = new BTextView("listingText"); fListingText->SetText(""); fListingText->MakeEditable(false); fListingText->SetStylable(false); fListingText->SetWordWrap(false); BFont font = be_fixed_font; fListingText->SetFontAndColor(&font); fScrollView = new BScrollView("", fListingText, B_INVALIDATE_AFTER_LAYOUT, true, true); const float spacing = be_control_look->DefaultItemSpacing(); BGroupLayout* pathLayout; BLayoutBuilder::Group<>(this, B_VERTICAL, 0) .Add(fBar) .AddGroup(B_VERTICAL, B_USE_ITEM_SPACING) .AddGroup(B_HORIZONTAL, B_USE_ITEM_SPACING) .Add(fSourceButton) .Add(fSourceText = new BTextControl(NULL, NULL, new BMessage(MSG_SOURCETEXT))) .End() .AddGroup(B_HORIZONTAL, B_USE_ITEM_SPACING) .Add(fDestButton) .Add(fDestText = new BTextControl(NULL, NULL, new BMessage(MSG_DESTTEXT))) .End() .AddGroup(B_HORIZONTAL, B_USE_ITEM_SPACING) .Add(fExpandButton) .AddGroup(B_HORIZONTAL, B_USE_ITEM_SPACING) .GetLayout(&pathLayout) .Add(fShowContents = new BCheckBox( B_TRANSLATE("Show contents"), new BMessage(MSG_SHOWCONTENTS))) .Add(fStatusView = new StatusView()) .End() .End() .SetInsets(B_USE_WINDOW_SPACING) .End() .Add(fScrollView); pathLayout->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); size = GetLayout()->View()->PreferredSize(); fSizeLimit = size.Height() - fScrollView->PreferredSize().height - spacing; fStatusView->SetExplicitMinSize(BSize(50.0f, B_SIZE_UNSET)); fStatusView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, B_SIZE_UNSET)); ResizeTo(Bounds().Width(), fSizeLimit); SetSizeLimits(size.Width(), 32767.0f, fSizeLimit, fSizeLimit); SetZoomLimits(Bounds().Width(), fSizeLimit); fPreviousHeight = -1; fScrollView->Hide(); Show(); } ExpanderWindow::~ExpanderWindow() { if (fDestPanel && fDestPanel->RefFilter()) delete fDestPanel->RefFilter(); if (fSourcePanel && fSourcePanel->RefFilter()) delete fSourcePanel->RefFilter(); delete fDestPanel; delete fSourcePanel; } bool ExpanderWindow::ValidateDest() { BEntry entry(fDestText->Text(), true); BVolume volume; if (!entry.Exists()) { BAlert* alert = new BAlert("destAlert", B_TRANSLATE("Destination folder doesn't exist. " "Would you like to create it?"), B_TRANSLATE("Create"), B_TRANSLATE("Cancel"), NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() != 0) return false; if (create_directory(fDestText->Text(), 0755) != B_OK) { BAlert* alert = new BAlert("stopAlert", B_TRANSLATE("Failed to create the destination folder."), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return false; } BEntry newEntry(fDestText->Text(), true); newEntry.GetRef(&fDestRef); return true; } if (!entry.IsDirectory()) { BAlert* alert = new BAlert("destAlert", B_TRANSLATE("The destination is not a folder."), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return false; } if (entry.GetVolume(&volume) != B_OK || volume.IsReadOnly()) { BAlert* alert = new BAlert("destAlert", B_TRANSLATE("The destination is read only."), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return false; } entry.GetRef(&fDestRef); return true; } void ExpanderWindow::MessageReceived(BMessage* message) { switch (message->what) { case MSG_SOURCE: { BEntry entry(fSourceText->Text(), true); entry_ref srcRef; if (entry.Exists() && entry.IsDirectory()) entry.GetRef(&srcRef); if (!fSourcePanel) { BMessenger messenger(this); fSourcePanel = new BFilePanel(B_OPEN_PANEL, &messenger, &srcRef, B_FILE_NODE, false, NULL, new RuleRefFilter(fRules), true); (fSourcePanel->Window())->SetTitle( B_TRANSLATE("Expander: Open")); } else fSourcePanel->SetPanelDirectory(&srcRef); fSourcePanel->Show(); break; } case MSG_DEST: { BEntry entry(fDestText->Text(), true); entry_ref destRef; if (entry.Exists() && entry.IsDirectory()) entry.GetRef(&destRef); if (!fDestPanel) { BMessenger messenger(this); fDestPanel = new DirectoryFilePanel(B_OPEN_PANEL, &messenger, &destRef, B_DIRECTORY_NODE, false, NULL, new DirectoryRefFilter(), true); } else fDestPanel->SetPanelDirectory(&destRef); fDestPanel->Show(); break; } case MSG_DIRECTORY: { entry_ref ref; fDestPanel->GetPanelDirectory(&ref); fDestRef = ref; BEntry entry(&ref); BPath path(&entry); fDestText->SetText(path.Path()); fDestPanel->Hide(); break; } case B_SIMPLE_DATA: case B_REFS_RECEIVED: RefsReceived(message); break; case MSG_EXPAND: if (!ValidateDest()) break; if (!fExpandingStarted) { StartExpanding(); break; } // supposed to fall through case MSG_STOP: if (fExpandingStarted) { fExpandingThread->SuspendExternalExpander(); BAlert* alert = new BAlert("stopAlert", B_TRANSLATE("Are you sure you want to stop expanding this " "archive? The expanded items may not be complete."), B_TRANSLATE("Stop"), B_TRANSLATE("Continue"), NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() == 0) { fExpandingThread->ResumeExternalExpander(); StopExpanding(); } else fExpandingThread->ResumeExternalExpander(); } break; case MSG_SHOW: fShowContents->SetValue(fShowContents->Value() == B_CONTROL_OFF ? B_CONTROL_ON : B_CONTROL_OFF); // supposed to fall through case MSG_SHOWCONTENTS: // change menu item label fShowItem->SetLabel(fShowContents->Value() == B_CONTROL_OFF ? B_TRANSLATE("Show contents") : B_TRANSLATE("Hide contents")); if (fShowContents->Value() == B_CONTROL_OFF) { if (fListingStarted) StopListing(); fScrollView->Hide(); _UpdateWindowSize(false); } else { fScrollView->Show(); StartListing(); } break; case MSG_SOURCETEXT: { BEntry entry(fSourceText->Text(), true); if (!entry.Exists()) { BAlert* alert = new BAlert("srcAlert", B_TRANSLATE("The file doesn't exist"), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); break; } entry_ref ref; entry.GetRef(&ref); ExpanderRule* rule = fRules.MatchingRule(&ref); if (rule) { fSourceChanged = true; fSourceRef = ref; fShowContents->SetEnabled(true); fExpandButton->SetEnabled(true); fExpandItem->SetEnabled(true); fShowItem->SetEnabled(true); break; } BString string = "The file : "; string += fSourceText->Text(); string += B_TRANSLATE_MARK(" is not supported"); BAlert* alert = new BAlert("srcAlert", string.String(), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_INFO_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); fShowContents->SetEnabled(false); fExpandButton->SetEnabled(false); fExpandItem->SetEnabled(false); fShowItem->SetEnabled(false); break; } case MSG_DESTTEXT: ValidateDest(); break; case MSG_PREFERENCES: if (fPreferences == NULL) fPreferences = new ExpanderPreferences(&fSettings); fPreferences->Show(); break; case 'outp': if (!fExpandingStarted && fListingStarted) { // Check if the vertical scroll bar is at the end float max, pos; fScrollView->ScrollBar(B_VERTICAL)->GetRange(NULL, &max); pos = fScrollView->ScrollBar(B_VERTICAL)->Value(); bool atEnd = (pos == max); BString string; int32 i = 0; while (message->FindString("output", i++, &string) == B_OK) { float length = fListingText->StringWidth(string.String()); if (length > fLongestLine) fLongestLine = length; fListingText->Insert(string.String()); } if (atEnd && fScrollView->ScrollBar(B_VERTICAL)->Value() == pos) { fScrollView->ScrollBar(B_VERTICAL)->GetRange(NULL, &max); fScrollView->ScrollBar(B_VERTICAL)->SetValue(max); } } else if (fExpandingStarted) { BString string; int32 i = 0; while (message->FindString("output", i++, &string) == B_OK) { if (strstr(string.String(), "Enter password") != NULL) { fExpandingThread->SuspendExternalExpander(); BString password; PasswordAlert* alert = new PasswordAlert("passwordAlert", string); alert->Go(password); fExpandingThread->ResumeExternalExpander(); fExpandingThread->PushInput(password); } } } break; case 'errp': { BString string; if (message->FindString("error", &string) == B_OK && fExpandingStarted) { fExpandingThread->SuspendExternalExpander(); if (strstr(string.String(), "password") != NULL) { BString password; PasswordAlert* alert = new PasswordAlert("passwordAlert", string); alert->Go(password); fExpandingThread->ResumeExternalExpander(); fExpandingThread->PushInput(password); } else { BAlert* alert = new BAlert("stopAlert", string, B_TRANSLATE("Stop"), B_TRANSLATE("Continue"), NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() == 0) { fExpandingThread->ResumeExternalExpander(); StopExpanding(); } else fExpandingThread->ResumeExternalExpander(); } } break; } case 'exit': // thread has finished // (finished, quit, killed, we don't know) // reset window state if (fExpandingStarted) { fStatusView->SetStatus(B_TRANSLATE("File expanded")); StopExpanding(); OpenDestFolder(); CloseWindowOrKeepOpen(); } else if (fListingStarted) { fSourceChanged = false; StopListing(); _ExpandListingText(); } else fStatusView->SetStatus(""); break; case 'exrr': // thread has finished // reset window state fStatusView->SetStatus(B_TRANSLATE("Error when expanding archive")); CloseWindowOrKeepOpen(); break; default: BWindow::MessageReceived(message); } } bool ExpanderWindow::CanQuit() { if ((fSourcePanel && fSourcePanel->IsShowing()) || (fDestPanel && fDestPanel->IsShowing())) { return false; } if (fExpandingStarted) { fExpandingThread->SuspendExternalExpander(); BAlert* alert = new BAlert("stopAlert", B_TRANSLATE("Are you sure you want to stop expanding this " "archive? The expanded items may not be complete."), B_TRANSLATE("Stop"), B_TRANSLATE("Continue"), NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); if (alert->Go() == 0) { fExpandingThread->ResumeExternalExpander(); StopExpanding(); } else { fExpandingThread->ResumeExternalExpander(); return false; } } return true; } bool ExpanderWindow::QuitRequested() { if (!CanQuit()) return false; if (fListingStarted) StopListing(); be_app->PostMessage(B_QUIT_REQUESTED); fSettings.ReplacePoint("window_position", Frame().LeftTop()); ((ExpanderApp*)(be_app))->UpdateSettingsFrom(&fSettings); return true; } void ExpanderWindow::RefsReceived(BMessage* message) { entry_ref ref; int32 i = 0; int8 destinationFolder = 0x63; fSettings.FindInt8("destination_folder", &destinationFolder); while (message->FindRef("refs", i++, &ref) == B_OK) { BEntry entry(&ref, true); BPath path(&entry); BNode node(&entry); if (node.IsFile()) { fSourceChanged = true; fSourceRef = ref; fSourceText->SetText(path.Path()); if (destinationFolder == 0x63) { BPath parent; path.GetParent(&parent); fDestText->SetText(parent.Path()); get_ref_for_path(parent.Path(), &fDestRef); } else if (destinationFolder == 0x65) { fSettings.FindRef("destination_folder_use", &fDestRef); BEntry dEntry(&fDestRef, true); BPath dPath(&dEntry); fDestText->SetText(dPath.Path()); } BEntry dEntry(&fDestRef, true); if (dEntry.Exists()) { fExpandButton->SetEnabled(true); fExpandItem->SetEnabled(true); } if (fShowContents->Value() == B_CONTROL_ON) { StopListing(); StartListing(); } else { fShowContents->SetEnabled(true); fShowItem->SetEnabled(true); } bool fromApp; if (message->FindBool("fromApp", &fromApp) == B_OK) { AutoExpand(); } else AutoListing(); } else if (node.IsDirectory()) { fDestRef = ref; fDestText->SetText(path.Path()); } } } #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ExpanderMenu" void ExpanderWindow::_CreateMenuBar() { fBar = new BMenuBar("menu_bar", B_ITEMS_IN_ROW, B_INVALIDATE_AFTER_LAYOUT); BMenu* menu = new BMenu(B_TRANSLATE("File")); menu->AddItem(fSourceItem = new BMenuItem(B_TRANSLATE("Set source" B_UTF8_ELLIPSIS), new BMessage(MSG_SOURCE), 'O')); menu->AddItem(fDestItem = new BMenuItem(B_TRANSLATE("Set destination" B_UTF8_ELLIPSIS), new BMessage(MSG_DEST), 'D')); menu->AddSeparatorItem(); menu->AddItem(fExpandItem = new BMenuItem(B_TRANSLATE("Expand"), new BMessage(MSG_EXPAND), 'E')); fExpandItem->SetEnabled(false); menu->AddItem(fShowItem = new BMenuItem(B_TRANSLATE("Show contents"), new BMessage(MSG_SHOW), 'L')); fShowItem->SetEnabled(false); menu->AddSeparatorItem(); menu->AddItem(fStopItem = new BMenuItem(B_TRANSLATE("Stop"), new BMessage(MSG_STOP), 'K')); fStopItem->SetEnabled(false); menu->AddSeparatorItem(); menu->AddItem(new BMenuItem(B_TRANSLATE("Close"), new BMessage(B_QUIT_REQUESTED), 'W')); fBar->AddItem(menu); menu = new BMenu(B_TRANSLATE("Settings")); menu->AddItem(fPreferencesItem = new BMenuItem(B_TRANSLATE("Settings" B_UTF8_ELLIPSIS), new BMessage(MSG_PREFERENCES), ',')); fBar->AddItem(menu); } #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "ExpanderWindow" void ExpanderWindow::StartExpanding() { ExpanderRule* rule = fRules.MatchingRule(&fSourceRef); if (!rule) return; BEntry destEntry(fDestText->Text(), true); if (!destEntry.Exists()) { BAlert* alert = new BAlert("destAlert", B_TRANSLATE("The folder was either moved, renamed or not supported."), B_TRANSLATE("Cancel"), NULL, NULL, B_WIDTH_AS_USUAL, B_EVEN_SPACING, B_WARNING_ALERT); alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(); return; } BMessage message; message.AddString("cmd", rule->ExpandCmd()); message.AddRef("srcRef", &fSourceRef); message.AddRef("destRef", &fDestRef); fExpandButton->SetLabel(B_TRANSLATE("Stop")); fSourceButton->SetEnabled(false); fDestButton->SetEnabled(false); fShowContents->SetEnabled(false); fSourceItem->SetEnabled(false); fDestItem->SetEnabled(false); fExpandItem->SetEnabled(false); fShowItem->SetEnabled(false); fStopItem->SetEnabled(true); fPreferencesItem->SetEnabled(false); BEntry entry(&fSourceRef); BPath path(&entry); BString text(B_TRANSLATE("Expanding '%s'" B_UTF8_ELLIPSIS)); text.ReplaceFirst("%s", path.Leaf()); fStatusView->SetStatus(text.String()); fExpandingThread = new ExpanderThread(&message, new BMessenger(this)); fExpandingThread->Start(); fExpandingStarted = true; } void ExpanderWindow::StopExpanding(void) { if (fExpandingThread) { fExpandingThread->InterruptExternalExpander(); fExpandingThread = NULL; } fExpandingStarted = false; fExpandButton->SetLabel(B_TRANSLATE("Expand")); fSourceButton->SetEnabled(true); fDestButton->SetEnabled(true); fShowContents->SetEnabled(true); fSourceItem->SetEnabled(true); fDestItem->SetEnabled(true); fExpandItem->SetEnabled(true); fShowItem->SetEnabled(true); fStopItem->SetEnabled(false); fPreferencesItem->SetEnabled(true); } void ExpanderWindow::_ExpandListingText() { float delta = fLongestLine - fListingText->Frame().Width(); if (delta > 0) { BScreen screen; BRect screenFrame = screen.Frame(); if (Frame().right + delta > screenFrame.right) delta = screenFrame.right - Frame().right - 4.0f; ResizeBy(delta, 0.0f); } float minWidth, maxWidth, minHeight, maxHeight; GetSizeLimits(&minWidth, &maxWidth, &minHeight, &maxHeight); if (minWidth < Frame().Width() + delta) { // set the Zoom limit as the minimal required size SetZoomLimits(Frame().Width() + delta, std::min(fSizeLimit + fListingText->TextRect().Height() + fLineHeight + B_H_SCROLL_BAR_HEIGHT + 1.0f, maxHeight)); } else { // set the zoom limit based on minimal window size allowed SetZoomLimits(minWidth, std::min(fSizeLimit + fListingText->TextRect().Height() + fLineHeight + B_H_SCROLL_BAR_HEIGHT + 1.0f, maxHeight)); } } void ExpanderWindow::_UpdateWindowSize(bool showContents) { float minWidth, maxWidth, minHeight, maxHeight; GetSizeLimits(&minWidth, &maxWidth, &minHeight, &maxHeight); float bottom = fSizeLimit; if (showContents) { if (fPreviousHeight < 0.0) { BFont font; font_height fontHeight; fListingText->GetFont(&font); font.GetHeight(&fontHeight); fLineHeight = ceilf(fontHeight.ascent + fontHeight.descent + fontHeight.leading); fPreviousHeight = bottom + 10.0 * fLineHeight; } minHeight = bottom + 5.0 * fLineHeight; maxHeight = 32767.0; bottom = std::max(fPreviousHeight, minHeight); } else { minHeight = fSizeLimit; maxHeight = fSizeLimit; fPreviousHeight = Frame().Height(); } SetSizeLimits(minWidth, maxWidth, minHeight, maxHeight); ResizeTo(Frame().Width(), bottom); } void ExpanderWindow::StartListing() { _UpdateWindowSize(true); if (!fSourceChanged) return; fPreviousHeight = -1.0; fLongestLine = 0.0f; ExpanderRule* rule = fRules.MatchingRule(&fSourceRef); if (!rule) return; BMessage message; message.AddString("cmd", rule->ListingCmd()); message.AddRef("srcRef", &fSourceRef); fShowContents->SetEnabled(true); fSourceItem->SetEnabled(false); fDestItem->SetEnabled(false); fExpandItem->SetEnabled(false); fShowItem->SetEnabled(true); fShowItem->SetLabel(B_TRANSLATE("Hide contents")); fStopItem->SetEnabled(false); fPreferencesItem->SetEnabled(false); fSourceButton->SetEnabled(false); fDestButton->SetEnabled(false); fExpandButton->SetEnabled(false); BEntry entry(&fSourceRef); BPath path(&entry); BString text(B_TRANSLATE("Creating listing for '%s'" B_UTF8_ELLIPSIS)); text.ReplaceFirst("%s", path.Leaf()); fStatusView->SetStatus(text.String()); fListingText->SetText(""); fListingText->MakeSelectable(false); fListingThread = new ExpanderThread(&message, new BMessenger(this)); fListingThread->Start(); fListingStarted = true; } void ExpanderWindow::StopListing(void) { if (fListingThread) { fListingThread->InterruptExternalExpander(); fListingThread = NULL; } fListingStarted = false; fListingText->MakeSelectable(true); fShowContents->SetEnabled(true); fSourceItem->SetEnabled(true); fDestItem->SetEnabled(true); fExpandItem->SetEnabled(true); fShowItem->SetEnabled(true); fStopItem->SetEnabled(false); fPreferencesItem->SetEnabled(true); fSourceButton->SetEnabled(true); fDestButton->SetEnabled(true); fExpandButton->SetEnabled(true); fStatusView->SetStatus(""); } void ExpanderWindow::CloseWindowOrKeepOpen() { bool expandFiles = false; fSettings.FindBool("automatically_expand_files", &expandFiles); bool closeWhenDone = false; fSettings.FindBool("close_when_done", &closeWhenDone); if (expandFiles || closeWhenDone) PostMessage(B_QUIT_REQUESTED); } void ExpanderWindow::OpenDestFolder() { bool openFolder = true; fSettings.FindBool("open_destination_folder", &openFolder); if (!openFolder) return; BMessage* message = new BMessage(B_REFS_RECEIVED); message->AddRef("refs", &fDestRef); BPath path(&fDestRef); BMessenger tracker("application/x-vnd.Be-TRAK"); tracker.SendMessage(message); } void ExpanderWindow::AutoListing() { bool showContents = false; fSettings.FindBool("show_contents_listing", &showContents); if (!showContents) return; fShowContents->SetValue(B_CONTROL_ON); fShowContents->Invoke(); } void ExpanderWindow::AutoExpand() { bool expandFiles = false; fSettings.FindBool("automatically_expand_files", &expandFiles); if (!expandFiles) { AutoListing(); return; } fExpandButton->Invoke(); }
{ "language": "C++" }
// Copyright 2015 Google Inc. All Rights Reserved. // // Use of this source code is governed by a BSD-style license // that can be found in the COPYING file in the root of the source // tree. An additional intellectual property rights grant can be found // in the file PATENTS. All contributing project authors may // be found in the AUTHORS file in the root of the source tree. // ----------------------------------------------------------------------------- // // SSE2 variant of alpha filters // // Author: Skal (pascal.massimino@gmail.com) #include "src/dsp/dsp.h" #if defined(WEBP_USE_SSE2) #include <assert.h> #include <emmintrin.h> #include <stdlib.h> #include <string.h> //------------------------------------------------------------------------------ // Helpful macro. # define SANITY_CHECK(in, out) \ assert((in) != NULL); \ assert((out) != NULL); \ assert(width > 0); \ assert(height > 0); \ assert(stride >= width); \ assert(row >= 0 && num_rows > 0 && row + num_rows <= height); \ (void)height; // Silence unused warning. static void PredictLineTop_SSE2(const uint8_t* src, const uint8_t* pred, uint8_t* dst, int length) { int i; const int max_pos = length & ~31; assert(length >= 0); for (i = 0; i < max_pos; i += 32) { const __m128i A0 = _mm_loadu_si128((const __m128i*)&src[i + 0]); const __m128i A1 = _mm_loadu_si128((const __m128i*)&src[i + 16]); const __m128i B0 = _mm_loadu_si128((const __m128i*)&pred[i + 0]); const __m128i B1 = _mm_loadu_si128((const __m128i*)&pred[i + 16]); const __m128i C0 = _mm_sub_epi8(A0, B0); const __m128i C1 = _mm_sub_epi8(A1, B1); _mm_storeu_si128((__m128i*)&dst[i + 0], C0); _mm_storeu_si128((__m128i*)&dst[i + 16], C1); } for (; i < length; ++i) dst[i] = src[i] - pred[i]; } // Special case for left-based prediction (when preds==dst-1 or preds==src-1). static void PredictLineLeft_SSE2(const uint8_t* src, uint8_t* dst, int length) { int i; const int max_pos = length & ~31; assert(length >= 0); for (i = 0; i < max_pos; i += 32) { const __m128i A0 = _mm_loadu_si128((const __m128i*)(src + i + 0 )); const __m128i B0 = _mm_loadu_si128((const __m128i*)(src + i + 0 - 1)); const __m128i A1 = _mm_loadu_si128((const __m128i*)(src + i + 16 )); const __m128i B1 = _mm_loadu_si128((const __m128i*)(src + i + 16 - 1)); const __m128i C0 = _mm_sub_epi8(A0, B0); const __m128i C1 = _mm_sub_epi8(A1, B1); _mm_storeu_si128((__m128i*)(dst + i + 0), C0); _mm_storeu_si128((__m128i*)(dst + i + 16), C1); } for (; i < length; ++i) dst[i] = src[i] - src[i - 1]; } //------------------------------------------------------------------------------ // Horizontal filter. static WEBP_INLINE void DoHorizontalFilter_SSE2(const uint8_t* in, int width, int height, int stride, int row, int num_rows, uint8_t* out) { const size_t start_offset = row * stride; const int last_row = row + num_rows; SANITY_CHECK(in, out); in += start_offset; out += start_offset; if (row == 0) { // Leftmost pixel is the same as input for topmost scanline. out[0] = in[0]; PredictLineLeft_SSE2(in + 1, out + 1, width - 1); row = 1; in += stride; out += stride; } // Filter line-by-line. while (row < last_row) { // Leftmost pixel is predicted from above. out[0] = in[0] - in[-stride]; PredictLineLeft_SSE2(in + 1, out + 1, width - 1); ++row; in += stride; out += stride; } } //------------------------------------------------------------------------------ // Vertical filter. static WEBP_INLINE void DoVerticalFilter_SSE2(const uint8_t* in, int width, int height, int stride, int row, int num_rows, uint8_t* out) { const size_t start_offset = row * stride; const int last_row = row + num_rows; SANITY_CHECK(in, out); in += start_offset; out += start_offset; if (row == 0) { // Very first top-left pixel is copied. out[0] = in[0]; // Rest of top scan-line is left-predicted. PredictLineLeft_SSE2(in + 1, out + 1, width - 1); row = 1; in += stride; out += stride; } // Filter line-by-line. while (row < last_row) { PredictLineTop_SSE2(in, in - stride, out, width); ++row; in += stride; out += stride; } } //------------------------------------------------------------------------------ // Gradient filter. static WEBP_INLINE int GradientPredictor_SSE2(uint8_t a, uint8_t b, uint8_t c) { const int g = a + b - c; return ((g & ~0xff) == 0) ? g : (g < 0) ? 0 : 255; // clip to 8bit } static void GradientPredictDirect_SSE2(const uint8_t* const row, const uint8_t* const top, uint8_t* const out, int length) { const int max_pos = length & ~7; int i; const __m128i zero = _mm_setzero_si128(); for (i = 0; i < max_pos; i += 8) { const __m128i A0 = _mm_loadl_epi64((const __m128i*)&row[i - 1]); const __m128i B0 = _mm_loadl_epi64((const __m128i*)&top[i]); const __m128i C0 = _mm_loadl_epi64((const __m128i*)&top[i - 1]); const __m128i D = _mm_loadl_epi64((const __m128i*)&row[i]); const __m128i A1 = _mm_unpacklo_epi8(A0, zero); const __m128i B1 = _mm_unpacklo_epi8(B0, zero); const __m128i C1 = _mm_unpacklo_epi8(C0, zero); const __m128i E = _mm_add_epi16(A1, B1); const __m128i F = _mm_sub_epi16(E, C1); const __m128i G = _mm_packus_epi16(F, zero); const __m128i H = _mm_sub_epi8(D, G); _mm_storel_epi64((__m128i*)(out + i), H); } for (; i < length; ++i) { const int delta = GradientPredictor_SSE2(row[i - 1], top[i], top[i - 1]); out[i] = (uint8_t)(row[i] - delta); } } static WEBP_INLINE void DoGradientFilter_SSE2(const uint8_t* in, int width, int height, int stride, int row, int num_rows, uint8_t* out) { const size_t start_offset = row * stride; const int last_row = row + num_rows; SANITY_CHECK(in, out); in += start_offset; out += start_offset; // left prediction for top scan-line if (row == 0) { out[0] = in[0]; PredictLineLeft_SSE2(in + 1, out + 1, width - 1); row = 1; in += stride; out += stride; } // Filter line-by-line. while (row < last_row) { out[0] = (uint8_t)(in[0] - in[-stride]); GradientPredictDirect_SSE2(in + 1, in + 1 - stride, out + 1, width - 1); ++row; in += stride; out += stride; } } #undef SANITY_CHECK //------------------------------------------------------------------------------ static void HorizontalFilter_SSE2(const uint8_t* data, int width, int height, int stride, uint8_t* filtered_data) { DoHorizontalFilter_SSE2(data, width, height, stride, 0, height, filtered_data); } static void VerticalFilter_SSE2(const uint8_t* data, int width, int height, int stride, uint8_t* filtered_data) { DoVerticalFilter_SSE2(data, width, height, stride, 0, height, filtered_data); } static void GradientFilter_SSE2(const uint8_t* data, int width, int height, int stride, uint8_t* filtered_data) { DoGradientFilter_SSE2(data, width, height, stride, 0, height, filtered_data); } //------------------------------------------------------------------------------ // Inverse transforms static void HorizontalUnfilter_SSE2(const uint8_t* prev, const uint8_t* in, uint8_t* out, int width) { int i; __m128i last; out[0] = (uint8_t)(in[0] + (prev == NULL ? 0 : prev[0])); if (width <= 1) return; last = _mm_set_epi32(0, 0, 0, out[0]); for (i = 1; i + 8 <= width; i += 8) { const __m128i A0 = _mm_loadl_epi64((const __m128i*)(in + i)); const __m128i A1 = _mm_add_epi8(A0, last); const __m128i A2 = _mm_slli_si128(A1, 1); const __m128i A3 = _mm_add_epi8(A1, A2); const __m128i A4 = _mm_slli_si128(A3, 2); const __m128i A5 = _mm_add_epi8(A3, A4); const __m128i A6 = _mm_slli_si128(A5, 4); const __m128i A7 = _mm_add_epi8(A5, A6); _mm_storel_epi64((__m128i*)(out + i), A7); last = _mm_srli_epi64(A7, 56); } for (; i < width; ++i) out[i] = (uint8_t)(in[i] + out[i - 1]); } static void VerticalUnfilter_SSE2(const uint8_t* prev, const uint8_t* in, uint8_t* out, int width) { if (prev == NULL) { HorizontalUnfilter_SSE2(NULL, in, out, width); } else { int i; const int max_pos = width & ~31; assert(width >= 0); for (i = 0; i < max_pos; i += 32) { const __m128i A0 = _mm_loadu_si128((const __m128i*)&in[i + 0]); const __m128i A1 = _mm_loadu_si128((const __m128i*)&in[i + 16]); const __m128i B0 = _mm_loadu_si128((const __m128i*)&prev[i + 0]); const __m128i B1 = _mm_loadu_si128((const __m128i*)&prev[i + 16]); const __m128i C0 = _mm_add_epi8(A0, B0); const __m128i C1 = _mm_add_epi8(A1, B1); _mm_storeu_si128((__m128i*)&out[i + 0], C0); _mm_storeu_si128((__m128i*)&out[i + 16], C1); } for (; i < width; ++i) out[i] = (uint8_t)(in[i] + prev[i]); } } static void GradientPredictInverse_SSE2(const uint8_t* const in, const uint8_t* const top, uint8_t* const row, int length) { if (length > 0) { int i; const int max_pos = length & ~7; const __m128i zero = _mm_setzero_si128(); __m128i A = _mm_set_epi32(0, 0, 0, row[-1]); // left sample for (i = 0; i < max_pos; i += 8) { const __m128i tmp0 = _mm_loadl_epi64((const __m128i*)&top[i]); const __m128i tmp1 = _mm_loadl_epi64((const __m128i*)&top[i - 1]); const __m128i B = _mm_unpacklo_epi8(tmp0, zero); const __m128i C = _mm_unpacklo_epi8(tmp1, zero); const __m128i D = _mm_loadl_epi64((const __m128i*)&in[i]); // base input const __m128i E = _mm_sub_epi16(B, C); // unclipped gradient basis B - C __m128i out = zero; // accumulator for output __m128i mask_hi = _mm_set_epi32(0, 0, 0, 0xff); int k = 8; while (1) { const __m128i tmp3 = _mm_add_epi16(A, E); // delta = A + B - C const __m128i tmp4 = _mm_packus_epi16(tmp3, zero); // saturate delta const __m128i tmp5 = _mm_add_epi8(tmp4, D); // add to in[] A = _mm_and_si128(tmp5, mask_hi); // 1-complement clip out = _mm_or_si128(out, A); // accumulate output if (--k == 0) break; A = _mm_slli_si128(A, 1); // rotate left sample mask_hi = _mm_slli_si128(mask_hi, 1); // rotate mask A = _mm_unpacklo_epi8(A, zero); // convert 8b->16b } A = _mm_srli_si128(A, 7); // prepare left sample for next iteration _mm_storel_epi64((__m128i*)&row[i], out); } for (; i < length; ++i) { const int delta = GradientPredictor_SSE2(row[i - 1], top[i], top[i - 1]); row[i] = (uint8_t)(in[i] + delta); } } } static void GradientUnfilter_SSE2(const uint8_t* prev, const uint8_t* in, uint8_t* out, int width) { if (prev == NULL) { HorizontalUnfilter_SSE2(NULL, in, out, width); } else { out[0] = (uint8_t)(in[0] + prev[0]); // predict from above GradientPredictInverse_SSE2(in + 1, prev + 1, out + 1, width - 1); } } //------------------------------------------------------------------------------ // Entry point extern void VP8FiltersInitSSE2(void); WEBP_TSAN_IGNORE_FUNCTION void VP8FiltersInitSSE2(void) { WebPUnfilters[WEBP_FILTER_HORIZONTAL] = HorizontalUnfilter_SSE2; WebPUnfilters[WEBP_FILTER_VERTICAL] = VerticalUnfilter_SSE2; WebPUnfilters[WEBP_FILTER_GRADIENT] = GradientUnfilter_SSE2; WebPFilters[WEBP_FILTER_HORIZONTAL] = HorizontalFilter_SSE2; WebPFilters[WEBP_FILTER_VERTICAL] = VerticalFilter_SSE2; WebPFilters[WEBP_FILTER_GRADIENT] = GradientFilter_SSE2; } #else // !WEBP_USE_SSE2 WEBP_DSP_INIT_STUB(VP8FiltersInitSSE2) #endif // WEBP_USE_SSE2
{ "language": "C++" }
#ifndef BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP #define BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP // MS compatible compilers support #pragma once #if defined(_MSC_VER) && (_MSC_VER >= 1020) # pragma once #endif /////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8 // polymorphic_iarchive.hpp // (C) Copyright 2002 Robert Ramey - http://www.rrsd.com . // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org for updates, documentation, and revision history. #include <cstddef> // std::size_t #include <climits> // ULONG_MAX #include <string> #include <boost/config.hpp> #if defined(BOOST_NO_STDC_NAMESPACE) namespace std{ using ::size_t; } // namespace std #endif #include <boost/cstdint.hpp> #include <boost/serialization/pfto.hpp> #include <boost/archive/detail/iserializer.hpp> #include <boost/archive/detail/interface_iarchive.hpp> #include <boost/serialization/nvp.hpp> #include <boost/archive/detail/register_archive.hpp> #include <boost/archive/detail/decl.hpp> #include <boost/archive/detail/abi_prefix.hpp> // must be the last header namespace boost { template<class T> class shared_ptr; namespace serialization { class extended_type_info; } // namespace serialization namespace archive { namespace detail { class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive; class BOOST_ARCHIVE_DECL(BOOST_PP_EMPTY()) basic_iarchive; } class polymorphic_iarchive; class polymorphic_iarchive_impl : public detail::interface_iarchive<polymorphic_iarchive> { #ifdef BOOST_NO_MEMBER_TEMPLATE_FRIENDS public: #else friend class detail::interface_iarchive<polymorphic_iarchive>; friend class load_access; #endif // primitive types the only ones permitted by polymorphic archives virtual void load(bool & t) = 0; virtual void load(char & t) = 0; virtual void load(signed char & t) = 0; virtual void load(unsigned char & t) = 0; #ifndef BOOST_NO_CWCHAR #ifndef BOOST_NO_INTRINSIC_WCHAR_T virtual void load(wchar_t & t) = 0; #endif #endif virtual void load(short & t) = 0; virtual void load(unsigned short & t) = 0; virtual void load(int & t) = 0; virtual void load(unsigned int & t) = 0; virtual void load(long & t) = 0; virtual void load(unsigned long & t) = 0; #if defined(BOOST_HAS_LONG_LONG) virtual void load(boost::long_long_type & t) = 0; virtual void load(boost::ulong_long_type & t) = 0; #elif defined(BOOST_HAS_MS_INT64) virtual void load(__int64 & t) = 0; virtual void load(unsigned __int64 & t) = 0; #endif virtual void load(float & t) = 0; virtual void load(double & t) = 0; // string types are treated as primitives virtual void load(std::string & t) = 0; #ifndef BOOST_NO_STD_WSTRING virtual void load(std::wstring & t) = 0; #endif // used for xml and other tagged formats virtual void load_start(const char * name) = 0; virtual void load_end(const char * name) = 0; virtual void register_basic_serializer(const detail::basic_iserializer & bis) = 0; // msvc and borland won't automatically pass these to the base class so // make it explicit here template<class T> void load_override(T & t, BOOST_PFTO int) { archive::load(* this->This(), t); } // special treatment for name-value pairs. template<class T> void load_override( #ifndef BOOST_NO_FUNCTION_TEMPLATE_ORDERING const #endif boost::serialization::nvp<T> & t, int ){ load_start(t.name()); archive::load(* this->This(), t.value()); load_end(t.name()); } protected: virtual ~polymorphic_iarchive_impl(){}; public: // utility function implemented by all legal archives virtual void set_library_version(library_version_type archive_library_version) = 0; virtual library_version_type get_library_version() const = 0; virtual unsigned int get_flags() const = 0; virtual void delete_created_pointers() = 0; virtual void reset_object_address( const void * new_address, const void * old_address ) = 0; virtual void load_binary(void * t, std::size_t size) = 0; // these are used by the serialization library implementation. virtual void load_object( void *t, const detail::basic_iserializer & bis ) = 0; virtual const detail::basic_pointer_iserializer * load_pointer( void * & t, const detail::basic_pointer_iserializer * bpis_ptr, const detail::basic_pointer_iserializer * (*finder)( const boost::serialization::extended_type_info & type ) ) = 0; }; } // namespace archive } // namespace boost #include <boost/archive/detail/abi_suffix.hpp> // pops abi_suffix.hpp pragmas // note special treatment of shared_ptr. This type needs a special // structure associated with every archive. We created a "mix-in" // class to provide this functionality. Since shared_ptr holds a // special esteem in the boost library - we included it here by default. #include <boost/archive/shared_ptr_helper.hpp> namespace boost { namespace archive { class polymorphic_iarchive : public polymorphic_iarchive_impl, public detail::shared_ptr_helper { public: virtual ~polymorphic_iarchive(){}; }; } // namespace archive } // namespace boost // required by export BOOST_SERIALIZATION_REGISTER_ARCHIVE(boost::archive::polymorphic_iarchive) #endif // BOOST_ARCHIVE_POLYMORPHIC_IARCHIVE_HPP
{ "language": "C++" }
#include <stdlib.h> #include "PriorityQueue.h" /* This comparison function is used to sort elements in key descending order. */ int compfunc(const FiboNode * const, const FiboNode * const); static int compFunc(const FiboNode * const node1, const FiboNode * const node2) { return ( ( ((QueueElement*)(node1))->key > ((QueueElement*)(node2))->key ) ? -1 : 1); } int PQ_init(PriorityQueue * const q, int size) { int i; q->size = size; q->elements = malloc(sizeof(QueueElement *) * size); for(i=0; i < size; i++) q->elements[i]=NULL; return fiboTreeInit((FiboTree *)q, compFunc); } void PQ_exit(PriorityQueue * const q) { int i; for(i = 0; i < q->size; i++) { if(q->elements[i] != NULL) free(q->elements[i]); } if(q->elements != NULL) free(q->elements); fiboTreeExit((FiboTree *)q); } void PQ_free(PriorityQueue * const q) { int i; for(i = 0; i < q->size; i++) { if(q->elements[i] != NULL) free(q->elements[i]); } fiboTreeFree((FiboTree *)q); } int PQ_isEmpty(PriorityQueue * const q) { FiboTree * tree = (FiboTree *)q; /* if the tree root is linked to itself then the tree is empty */ if(&(tree->rootdat) == (tree->rootdat.linkdat.nextptr)) return 1; return 0; } void PQ_insertElement(PriorityQueue * const q, QueueElement * const e) { if(e->value >= 0 && e->value < q->size) { fiboTreeAdd((FiboTree *)q, (FiboNode *)(e)); q->elements[e->value] = e; e->isInQueue = 1; } } void PQ_deleteElement(PriorityQueue * const q, QueueElement * const e) { fiboTreeDel((FiboTree *)q, (FiboNode *)(e)); q->elements[e->value] = NULL; e->isInQueue = 0; } void PQ_insert(PriorityQueue * const q, int val, double key) { if( val >= 0 && val < q->size) { QueueElement * e = malloc(sizeof(QueueElement)); e->value = val; e->key = key; PQ_insertElement(q, e); } } void PQ_delete(PriorityQueue * const q, int val) { QueueElement * e = q->elements[val]; PQ_deleteElement(q, e); free(e); } QueueElement * PQ_findMaxElement(PriorityQueue * const q) { QueueElement * e = (QueueElement *)(fiboTreeMin((FiboTree *)q)); return e; } QueueElement * PQ_deleteMaxElement(PriorityQueue * const q) { QueueElement * e = (QueueElement *)(fiboTreeMin((FiboTree *)q)); if(e != NULL) { PQ_deleteElement(q, e); } return e; } double PQ_findMaxKey(PriorityQueue * const q) { QueueElement * e = PQ_findMaxElement(q); if(e!=NULL) return e->key; return 0; } int PQ_deleteMax(PriorityQueue * const q) { QueueElement * e = PQ_deleteMaxElement(q); int res = -1; if(e != NULL) res = e->value; free(e); return res; } void PQ_increaseElementKey(PriorityQueue * const q, QueueElement * const e, double i) { if(e->isInQueue) { PQ_deleteElement(q, e); e->key += i; PQ_insertElement(q, e); } } void PQ_decreaseElementKey(PriorityQueue * const q, QueueElement * const e, double i) { if(e->isInQueue) { PQ_deleteElement(q, e); e->key -= i; PQ_insertElement(q, e); } } void PQ_adjustElementKey(PriorityQueue * const q, QueueElement * const e, double i) { if(e->isInQueue) { PQ_deleteElement(q, e); e->key = i; PQ_insertElement(q, e); } } void PQ_increaseKey(PriorityQueue * const q, int val, double i) { QueueElement * e = q->elements[val]; if(e != NULL) PQ_increaseElementKey(q, e, i); } void PQ_decreaseKey(PriorityQueue * const q, int val, double i) { QueueElement * e = q->elements[val]; if(e != NULL) PQ_decreaseElementKey(q, e, i); } void PQ_adjustKey(PriorityQueue * const q, int val, double i) { QueueElement * e = q->elements[val]; if(e != NULL) PQ_adjustElementKey(q, e, i); }
{ "language": "C++" }
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * Copyright by The HDF Group. * * Copyright by the Board of Trustees of the University of Illinois. * * All rights reserved. * * * * This file is part of HDF5. The full HDF5 copyright notice, including * * terms governing use, modification, and redistribution, is contained in * * the files COPYING and Copyright.html. COPYING can be found at the root * * of the source code distribution tree; Copyright.html can be found at the * * root level of an installed copy of the electronic HDF5 document set and * * is linked from the top-level documents page. It can also be found at * * http://hdfgroup.org/HDF5/doc/Copyright.html. If you do not have * * access to either file, you may request a copy from help@hdfgroup.org. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /*------------------------------------------------------------------------- * * Created: H5Ostab.c * Aug 6 1997 * Robb Matzke <matzke@llnl.gov> * * Purpose: Symbol table messages. * *------------------------------------------------------------------------- */ #define H5G_PACKAGE /*suppress error about including H5Gpkg */ #define H5O_PACKAGE /*suppress error about including H5Opkg */ #include "H5private.h" /* Generic Functions */ #include "H5Eprivate.h" /* Error handling */ #include "H5FLprivate.h" /* Free lists */ #include "H5Gpkg.h" /* Groups */ #include "H5HLprivate.h" /* Local Heaps */ #include "H5Opkg.h" /* Object headers */ /* PRIVATE PROTOTYPES */ static void *H5O_stab_decode(H5F_t *f, hid_t dxpl_id, H5O_t *open_oh, unsigned mesg_flags, unsigned *ioflags, const uint8_t *p); static herr_t H5O_stab_encode(H5F_t *f, hbool_t disable_shared, uint8_t *p, const void *_mesg); static void *H5O_stab_copy(const void *_mesg, void *_dest); static size_t H5O_stab_size(const H5F_t *f, hbool_t disable_shared, const void *_mesg); static herr_t H5O_stab_free(void *_mesg); static herr_t H5O_stab_delete(H5F_t *f, hid_t dxpl_id, H5O_t *open_oh, void *_mesg); static void *H5O_stab_copy_file(H5F_t *file_src, void *native_src, H5F_t *file_dst, hbool_t *recompute_size, unsigned *mesg_flags, H5O_copy_t *cpy_info, void *_udata, hid_t dxpl_id); static herr_t H5O_stab_post_copy_file(const H5O_loc_t *src_oloc, const void *mesg_src, H5O_loc_t *dst_oloc, void *mesg_dst, unsigned *mesg_flags, hid_t dxpl_id, H5O_copy_t *cpy_info); static herr_t H5O_stab_debug(H5F_t *f, hid_t dxpl_id, const void *_mesg, FILE * stream, int indent, int fwidth); /* This message derives from H5O message class */ const H5O_msg_class_t H5O_MSG_STAB[1] = {{ H5O_STAB_ID, /*message id number */ "stab", /*message name for debugging */ sizeof(H5O_stab_t), /*native message size */ 0, /* messages are sharable? */ H5O_stab_decode, /*decode message */ H5O_stab_encode, /*encode message */ H5O_stab_copy, /*copy the native value */ H5O_stab_size, /*size of symbol table entry */ NULL, /*default reset method */ H5O_stab_free, /* free method */ H5O_stab_delete, /* file delete method */ NULL, /* link method */ NULL, /*set share method */ NULL, /*can share method */ NULL, /* pre copy native value to file */ H5O_stab_copy_file, /* copy native value to file */ H5O_stab_post_copy_file, /* post copy native value to file */ NULL, /* get creation index */ NULL, /* set creation index */ H5O_stab_debug /*debug the message */ }}; /* Declare a free list to manage the H5O_stab_t struct */ H5FL_DEFINE_STATIC(H5O_stab_t); /*------------------------------------------------------------------------- * Function: H5O_stab_decode * * Purpose: Decode a symbol table message and return a pointer to * a newly allocated one. * * Return: Success: Ptr to new message in native order. * * Failure: NULL * * Programmer: Robb Matzke * matzke@llnl.gov * Aug 6 1997 * *------------------------------------------------------------------------- */ static void * H5O_stab_decode(H5F_t *f, hid_t UNUSED dxpl_id, H5O_t UNUSED *open_oh, unsigned UNUSED mesg_flags, unsigned UNUSED *ioflags, const uint8_t *p) { H5O_stab_t *stab = NULL; void *ret_value; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* check args */ HDassert(f); HDassert(p); /* decode */ if(NULL == (stab = H5FL_CALLOC(H5O_stab_t))) HGOTO_ERROR(H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed") H5F_addr_decode(f, &p, &(stab->btree_addr)); H5F_addr_decode(f, &p, &(stab->heap_addr)); /* Set return value */ ret_value = stab; done: if(ret_value == NULL) { if(stab != NULL) stab = H5FL_FREE(H5O_stab_t, stab); } /* end if */ FUNC_LEAVE_NOAPI(ret_value) } /* end H5O_stab_decode() */ /*------------------------------------------------------------------------- * Function: H5O_stab_encode * * Purpose: Encodes a symbol table message. * * Return: Non-negative on success/Negative on failure * * Programmer: Robb Matzke * matzke@llnl.gov * Aug 6 1997 * *------------------------------------------------------------------------- */ static herr_t H5O_stab_encode(H5F_t *f, hbool_t UNUSED disable_shared, uint8_t *p, const void *_mesg) { const H5O_stab_t *stab = (const H5O_stab_t *) _mesg; FUNC_ENTER_NOAPI_NOINIT_NOERR /* check args */ assert(f); assert(p); assert(stab); /* encode */ H5F_addr_encode(f, &p, stab->btree_addr); H5F_addr_encode(f, &p, stab->heap_addr); FUNC_LEAVE_NOAPI(SUCCEED) } /*------------------------------------------------------------------------- * Function: H5O_stab_copy * * Purpose: Copies a message from _MESG to _DEST, allocating _DEST if * necessary. * * Return: Success: Ptr to _DEST * * Failure: NULL * * Programmer: Robb Matzke * matzke@llnl.gov * Aug 6 1997 * *------------------------------------------------------------------------- */ static void * H5O_stab_copy(const void *_mesg, void *_dest) { const H5O_stab_t *stab = (const H5O_stab_t *) _mesg; H5O_stab_t *dest = (H5O_stab_t *) _dest; void *ret_value; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* check args */ HDassert(stab); if(!dest && NULL == (dest = H5FL_MALLOC(H5O_stab_t))) HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed"); /* copy */ *dest = *stab; /* Set return value */ ret_value = dest; done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5O_stab_copy() */ /*------------------------------------------------------------------------- * Function: H5O_stab_size * * Purpose: Returns the size of the raw message in bytes not counting * the message type or size fields, but only the data fields. * This function doesn't take into account alignment. * * Return: Success: Message data size in bytes without alignment. * * Failure: zero * * Programmer: Robb Matzke * matzke@llnl.gov * Aug 6 1997 * *------------------------------------------------------------------------- */ static size_t H5O_stab_size(const H5F_t *f, hbool_t UNUSED disable_shared, const void UNUSED *_mesg) { size_t ret_value; /* Return value */ FUNC_ENTER_NOAPI_NOINIT_NOERR /* Set return value */ ret_value=2 * H5F_SIZEOF_ADDR(f); FUNC_LEAVE_NOAPI(ret_value) } /*------------------------------------------------------------------------- * Function: H5O_stab_free * * Purpose: Free's the message * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * Thursday, March 30, 2000 * * Modifications: * *------------------------------------------------------------------------- */ static herr_t H5O_stab_free(void *mesg) { FUNC_ENTER_NOAPI_NOINIT_NOERR HDassert(mesg); mesg = H5FL_FREE(H5O_stab_t, mesg); FUNC_LEAVE_NOAPI(SUCCEED) } /* end H5O_stab_free() */ /*------------------------------------------------------------------------- * Function: H5O_stab_delete * * Purpose: Free file space referenced by message * * Return: Non-negative on success/Negative on failure * * Programmer: Quincey Koziol * Thursday, March 20, 2003 * *------------------------------------------------------------------------- */ static herr_t H5O_stab_delete(H5F_t *f, hid_t dxpl_id, H5O_t UNUSED *open_oh, void *mesg) { herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* check args */ HDassert(f); HDassert(mesg); /* Free the file space for the symbol table */ if(H5G__stab_delete(f, dxpl_id, (const H5O_stab_t *)mesg) < 0) HGOTO_ERROR(H5E_OHDR, H5E_CANTFREE, FAIL, "unable to free symbol table") done: FUNC_LEAVE_NOAPI(ret_value) } /* end H5O_stab_delete() */ /*------------------------------------------------------------------------- * Function: H5O_stab_copy_file * * Purpose: Copies a message from _MESG to _DEST in file * * Return: Success: Ptr to _DEST * * Failure: NULL * * Programmer: Peter Cao * September 10, 2005 * *------------------------------------------------------------------------- */ static void * H5O_stab_copy_file(H5F_t *file_src, void *native_src, H5F_t *file_dst, hbool_t UNUSED *recompute_size, unsigned UNUSED *mesg_flags, H5O_copy_t UNUSED *cpy_info, void *_udata, hid_t dxpl_id) { H5O_stab_t *stab_src = (H5O_stab_t *) native_src; H5O_stab_t *stab_dst = NULL; H5G_copy_file_ud_t *udata = (H5G_copy_file_ud_t *)_udata; size_t size_hint; /* Local heap initial size */ void *ret_value; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* check args */ HDassert(stab_src); HDassert(file_dst); /* Allocate space for the destination stab */ if(NULL == (stab_dst = H5FL_MALLOC(H5O_stab_t))) HGOTO_ERROR (H5E_RESOURCE, H5E_NOSPACE, NULL, "memory allocation failed") /* Get the old local heap's size and use that as the hint for the new heap */ if(H5HL_get_size(file_src, dxpl_id, stab_src->heap_addr, &size_hint) < 0) HGOTO_ERROR(H5E_SYM, H5E_CANTGETSIZE, NULL, "can't query local heap size") /* Create components of symbol table message */ if(H5G__stab_create_components(file_dst, stab_dst, size_hint, dxpl_id) < 0) HGOTO_ERROR(H5E_SYM, H5E_CANTINIT, NULL, "can't create symbol table components") /* Cache stab in udata */ udata->cache_type = H5G_CACHED_STAB; udata->cache.stab.btree_addr = stab_dst->btree_addr; udata->cache.stab.heap_addr = stab_dst->heap_addr; /* Set return value */ ret_value = stab_dst; done: if(!ret_value) if(stab_dst) stab_dst = H5FL_FREE(H5O_stab_t, stab_dst); FUNC_LEAVE_NOAPI(ret_value) } /* H5O_stab_copy_file() */ /*------------------------------------------------------------------------- * Function: H5O_stab_post_copy_file * * Purpose: Finish copying a message from between files * * Return: Non-negative on success/Negative on failure * * Programmer: Peter Cao * September 28, 2005 * *------------------------------------------------------------------------- */ static herr_t H5O_stab_post_copy_file(const H5O_loc_t *src_oloc, const void *mesg_src, H5O_loc_t *dst_oloc, void *mesg_dst, unsigned UNUSED *mesg_flags, hid_t dxpl_id, H5O_copy_t *cpy_info) { const H5O_stab_t *stab_src = (const H5O_stab_t *)mesg_src; H5O_stab_t *stab_dst = (H5O_stab_t *)mesg_dst; H5G_bt_it_cpy_t udata; /* B-tree user data */ herr_t ret_value = SUCCEED; /* Return value */ FUNC_ENTER_NOAPI_NOINIT /* check args */ HDassert(stab_src); HDassert(H5F_addr_defined(dst_oloc->addr)); HDassert(dst_oloc->file); HDassert(stab_dst); HDassert(cpy_info); /* If we are performing a 'shallow hierarchy' copy, get out now */ if(cpy_info->max_depth >= 0 && cpy_info->curr_depth >= cpy_info->max_depth) HGOTO_DONE(SUCCEED) /* Set up B-tree iteration user data */ udata.src_oloc = src_oloc; udata.src_heap_addr = stab_src->heap_addr; udata.dst_file = dst_oloc->file; udata.dst_stab = stab_dst; udata.cpy_info = cpy_info; /* Iterate over objects in group, copying them */ if((H5B_iterate(src_oloc->file, dxpl_id, H5B_SNODE, stab_src->btree_addr, H5G__node_copy, &udata)) < 0) HGOTO_ERROR(H5E_SYM, H5E_CANTINIT, FAIL, "iteration operator failed") done: FUNC_LEAVE_NOAPI(ret_value) } /* H5O_stab_post_copy_file() */ /*------------------------------------------------------------------------- * Function: H5O_stab_debug * * Purpose: Prints debugging info for a symbol table message. * * Return: Non-negative on success/Negative on failure * * Programmer: Robb Matzke * matzke@llnl.gov * Aug 6 1997 * * Modifications: * *------------------------------------------------------------------------- */ static herr_t H5O_stab_debug(H5F_t UNUSED *f, hid_t UNUSED dxpl_id, const void *_mesg, FILE * stream, int indent, int fwidth) { const H5O_stab_t *stab = (const H5O_stab_t *) _mesg; FUNC_ENTER_NOAPI_NOINIT_NOERR /* check args */ assert(f); assert(stab); assert(stream); assert(indent >= 0); assert(fwidth >= 0); HDfprintf(stream, "%*s%-*s %a\n", indent, "", fwidth, "B-tree address:", stab->btree_addr); HDfprintf(stream, "%*s%-*s %a\n", indent, "", fwidth, "Name heap address:", stab->heap_addr); FUNC_LEAVE_NOAPI(SUCCEED) }
{ "language": "C++" }
// // ip/tcp.hpp // ~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_IP_TCP_HPP #define ASIO_IP_TCP_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #include "asio/basic_socket_acceptor.hpp" #include "asio/basic_socket_iostream.hpp" #include "asio/basic_stream_socket.hpp" #include "asio/detail/socket_option.hpp" #include "asio/detail/socket_types.hpp" #include "asio/ip/basic_endpoint.hpp" #include "asio/ip/basic_resolver.hpp" #include "asio/ip/basic_resolver_iterator.hpp" #include "asio/ip/basic_resolver_query.hpp" #include "asio/detail/push_options.hpp" namespace asio { namespace ip { /// Encapsulates the flags needed for TCP. /** * The asio::ip::tcp class contains flags necessary for TCP sockets. * * @par Thread Safety * @e Distinct @e objects: Safe.@n * @e Shared @e objects: Safe. * * @par Concepts: * Protocol, InternetProtocol. */ class tcp { public: /// The type of a TCP endpoint. typedef basic_endpoint<tcp> endpoint; /// Construct to represent the IPv4 TCP protocol. static tcp v4() { return tcp(ASIO_OS_DEF(AF_INET)); } /// Construct to represent the IPv6 TCP protocol. static tcp v6() { return tcp(ASIO_OS_DEF(AF_INET6)); } /// Obtain an identifier for the type of the protocol. int type() const { return ASIO_OS_DEF(SOCK_STREAM); } /// Obtain an identifier for the protocol. int protocol() const { return ASIO_OS_DEF(IPPROTO_TCP); } /// Obtain an identifier for the protocol family. int family() const { return family_; } /// The TCP socket type. typedef basic_stream_socket<tcp> socket; /// The TCP acceptor type. typedef basic_socket_acceptor<tcp> acceptor; /// The TCP resolver type. typedef basic_resolver<tcp> resolver; #if !defined(ASIO_NO_IOSTREAM) /// The TCP iostream type. typedef basic_socket_iostream<tcp> iostream; #endif // !defined(ASIO_NO_IOSTREAM) /// Socket option for disabling the Nagle algorithm. /** * Implements the IPPROTO_TCP/TCP_NODELAY socket option. * * @par Examples * Setting the option: * @code * asio::ip::tcp::socket socket(io_context); * ... * asio::ip::tcp::no_delay option(true); * socket.set_option(option); * @endcode * * @par * Getting the current option value: * @code * asio::ip::tcp::socket socket(io_context); * ... * asio::ip::tcp::no_delay option; * socket.get_option(option); * bool is_set = option.value(); * @endcode * * @par Concepts: * Socket_Option, Boolean_Socket_Option. */ #if defined(GENERATING_DOCUMENTATION) typedef implementation_defined no_delay; #else typedef asio::detail::socket_option::boolean< ASIO_OS_DEF(IPPROTO_TCP), ASIO_OS_DEF(TCP_NODELAY)> no_delay; #endif /// Compare two protocols for equality. friend bool operator==(const tcp& p1, const tcp& p2) { return p1.family_ == p2.family_; } /// Compare two protocols for inequality. friend bool operator!=(const tcp& p1, const tcp& p2) { return p1.family_ != p2.family_; } private: // Construct with a specific family. explicit tcp(int protocol_family) : family_(protocol_family) { } int family_; }; } // namespace ip } // namespace asio #include "asio/detail/pop_options.hpp" #endif // ASIO_IP_TCP_HPP
{ "language": "C++" }
// // executor_work_guard.hpp // ~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP #define BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include <boost/asio/detail/config.hpp> #include <boost/asio/associated_executor.hpp> #include <boost/asio/detail/type_traits.hpp> #include <boost/asio/is_executor.hpp> #include <boost/asio/detail/push_options.hpp> namespace boost { namespace asio { /// An object of type @c executor_work_guard controls ownership of executor work /// within a scope. template <typename Executor> class executor_work_guard { public: /// The underlying executor type. typedef Executor executor_type; /// Constructs a @c executor_work_guard object for the specified executor. /** * Stores a copy of @c e and calls <tt>on_work_started()</tt> on it. */ explicit executor_work_guard(const executor_type& e) BOOST_ASIO_NOEXCEPT : executor_(e), owns_(true) { executor_.on_work_started(); } /// Copy constructor. executor_work_guard(const executor_work_guard& other) BOOST_ASIO_NOEXCEPT : executor_(other.executor_), owns_(other.owns_) { if (owns_) executor_.on_work_started(); } #if defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Move constructor. executor_work_guard(executor_work_guard&& other) : executor_(BOOST_ASIO_MOVE_CAST(Executor)(other.executor_)), owns_(other.owns_) { other.owns_ = false; } #endif // defined(BOOST_ASIO_HAS_MOVE) || defined(GENERATING_DOCUMENTATION) /// Destructor. /** * Unless the object has already been reset, or is in a moved-from state, * calls <tt>on_work_finished()</tt> on the stored executor. */ ~executor_work_guard() { if (owns_) executor_.on_work_finished(); } /// Obtain the associated executor. executor_type get_executor() const BOOST_ASIO_NOEXCEPT { return executor_; } /// Whether the executor_work_guard object owns some outstanding work. bool owns_work() const BOOST_ASIO_NOEXCEPT { return owns_; } /// Indicate that the work is no longer outstanding. /* * Unless the object has already been reset, or is in a moved-from state, * calls <tt>on_work_finished()</tt> on the stored executor. */ void reset() BOOST_ASIO_NOEXCEPT { if (owns_) { executor_.on_work_finished(); owns_ = false; } } private: // Disallow assignment. executor_work_guard& operator=(const executor_work_guard&); executor_type executor_; bool owns_; }; /// Create an @ref executor_work_guard object. template <typename Executor> inline executor_work_guard<Executor> make_work_guard(const Executor& ex, typename enable_if<is_executor<Executor>::value>::type* = 0) { return executor_work_guard<Executor>(ex); } /// Create an @ref executor_work_guard object. template <typename ExecutionContext> inline executor_work_guard<typename ExecutionContext::executor_type> make_work_guard(ExecutionContext& ctx, typename enable_if< is_convertible<ExecutionContext&, execution_context&>::value>::type* = 0) { return executor_work_guard<typename ExecutionContext::executor_type>( ctx.get_executor()); } /// Create an @ref executor_work_guard object. template <typename T> inline executor_work_guard<typename associated_executor<T>::type> make_work_guard(const T& t, typename enable_if<!is_executor<T>::value && !is_convertible<T&, execution_context&>::value>::type* = 0) { return executor_work_guard<typename associated_executor<T>::type>( associated_executor<T>::get(t)); } /// Create an @ref executor_work_guard object. template <typename T, typename Executor> inline executor_work_guard<typename associated_executor<T, Executor>::type> make_work_guard(const T& t, const Executor& ex, typename enable_if<is_executor<Executor>::value>::type* = 0) { return executor_work_guard<typename associated_executor<T, Executor>::type>( associated_executor<T, Executor>::get(t, ex)); } /// Create an @ref executor_work_guard object. template <typename T, typename ExecutionContext> inline executor_work_guard<typename associated_executor<T, typename ExecutionContext::executor_type>::type> make_work_guard(const T& t, ExecutionContext& ctx, typename enable_if<!is_executor<T>::value && !is_convertible<T&, execution_context&>::value && is_convertible<ExecutionContext&, execution_context&>::value>::type* = 0) { return executor_work_guard<typename associated_executor<T, typename ExecutionContext::executor_type>::type>( associated_executor<T, typename ExecutionContext::executor_type>::get( t, ctx.get_executor())); } } // namespace asio } // namespace boost #include <boost/asio/detail/pop_options.hpp> #endif // BOOST_ASIO_EXECUTOR_WORK_GUARD_HPP
{ "language": "C++" }
#ifndef BOOST_SERIALIZATION_ARRAY_HPP #define BOOST_SERIALIZATION_ARRAY_HPP // (C) Copyright 2005 Matthias Troyer and Dave Abrahams // Use, modification and distribution is subject to the Boost Software // License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // for serialization of <array>. If <array> not supported by the standard // library - this file becomes empty. This is to avoid breaking backward // compatibiliy for applications which used this header to support // serialization of native arrays. Code to serialize native arrays is // now always include by default. RR #include <boost/config.hpp> // msvc 6.0 needs this for warning suppression #if defined(BOOST_NO_STDC_NAMESPACE) #include <iostream> #include <cstddef> // std::size_t namespace std{ using ::size_t; } // namespace std #endif #include <boost/serialization/array_wrapper.hpp> #ifndef BOOST_NO_CXX11_HDR_ARRAY #include <array> #include <boost/serialization/nvp.hpp> namespace boost { namespace serialization { template <class Archive, class T, std::size_t N> void serialize(Archive& ar, std::array<T,N>& a, const unsigned int /* version */) { ar & boost::serialization::make_nvp( "elems", *static_cast<T (*)[N]>(static_cast<void *>(a.data())) ); } } } // end namespace boost::serialization #endif // BOOST_NO_CXX11_HDR_ARRAY #endif //BOOST_SERIALIZATION_ARRAY_HPP
{ "language": "C++" }
/* crypto/sha/sha256t.c */ /* ==================================================================== * Copyright (c) 2004 The OpenSSL Project. All rights reserved. * ==================================================================== */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/sha.h> #include <openssl/evp.h> #if defined(OPENSSL_NO_SHA) || defined(OPENSSL_NO_SHA256) int main(int argc, char *argv[]) { printf("No SHA256 support\n"); return (0); } #else unsigned char app_b1[SHA256_DIGEST_LENGTH] = { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }; unsigned char app_b2[SHA256_DIGEST_LENGTH] = { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }; unsigned char app_b3[SHA256_DIGEST_LENGTH] = { 0xcd, 0xc7, 0x6e, 0x5c, 0x99, 0x14, 0xfb, 0x92, 0x81, 0xa1, 0xc7, 0xe2, 0x84, 0xd7, 0x3e, 0x67, 0xf1, 0x80, 0x9a, 0x48, 0xa4, 0x97, 0x20, 0x0e, 0x04, 0x6d, 0x39, 0xcc, 0xc7, 0x11, 0x2c, 0xd0 }; unsigned char addenum_1[SHA224_DIGEST_LENGTH] = { 0x23, 0x09, 0x7d, 0x22, 0x34, 0x05, 0xd8, 0x22, 0x86, 0x42, 0xa4, 0x77, 0xbd, 0xa2, 0x55, 0xb3, 0x2a, 0xad, 0xbc, 0xe4, 0xbd, 0xa0, 0xb3, 0xf7, 0xe3, 0x6c, 0x9d, 0xa7 }; unsigned char addenum_2[SHA224_DIGEST_LENGTH] = { 0x75, 0x38, 0x8b, 0x16, 0x51, 0x27, 0x76, 0xcc, 0x5d, 0xba, 0x5d, 0xa1, 0xfd, 0x89, 0x01, 0x50, 0xb0, 0xc6, 0x45, 0x5c, 0xb4, 0xf5, 0x8b, 0x19, 0x52, 0x52, 0x25, 0x25 }; unsigned char addenum_3[SHA224_DIGEST_LENGTH] = { 0x20, 0x79, 0x46, 0x55, 0x98, 0x0c, 0x91, 0xd8, 0xbb, 0xb4, 0xc1, 0xea, 0x97, 0x61, 0x8a, 0x4b, 0xf0, 0x3f, 0x42, 0x58, 0x19, 0x48, 0xb2, 0xee, 0x4e, 0xe7, 0xad, 0x67 }; int main(int argc, char **argv) { unsigned char md[SHA256_DIGEST_LENGTH]; int i; EVP_MD_CTX evp; fprintf(stdout, "Testing SHA-256 "); EVP_Digest("abc", 3, md, NULL, EVP_sha256(), NULL); if (memcmp(md, app_b1, sizeof(app_b1))) { fflush(stdout); fprintf(stderr, "\nTEST 1 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); EVP_Digest("abcdbcde" "cdefdefg" "efghfghi" "ghijhijk" "ijkljklm" "klmnlmno" "mnopnopq", 56, md, NULL, EVP_sha256(), NULL); if (memcmp(md, app_b2, sizeof(app_b2))) { fflush(stdout); fprintf(stderr, "\nTEST 2 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha256(), NULL); for (i = 0; i < 1000000; i += 160) EVP_DigestUpdate(&evp, "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa", (1000000 - i) < 160 ? 1000000 - i : 160); EVP_DigestFinal_ex(&evp, md, NULL); EVP_MD_CTX_cleanup(&evp); if (memcmp(md, app_b3, sizeof(app_b3))) { fflush(stdout); fprintf(stderr, "\nTEST 3 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); fprintf(stdout, " passed.\n"); fflush(stdout); fprintf(stdout, "Testing SHA-224 "); EVP_Digest("abc", 3, md, NULL, EVP_sha224(), NULL); if (memcmp(md, addenum_1, sizeof(addenum_1))) { fflush(stdout); fprintf(stderr, "\nTEST 1 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); EVP_Digest("abcdbcde" "cdefdefg" "efghfghi" "ghijhijk" "ijkljklm" "klmnlmno" "mnopnopq", 56, md, NULL, EVP_sha224(), NULL); if (memcmp(md, addenum_2, sizeof(addenum_2))) { fflush(stdout); fprintf(stderr, "\nTEST 2 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); EVP_MD_CTX_init(&evp); EVP_DigestInit_ex(&evp, EVP_sha224(), NULL); for (i = 0; i < 1000000; i += 64) EVP_DigestUpdate(&evp, "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa" "aaaaaaaa", (1000000 - i) < 64 ? 1000000 - i : 64); EVP_DigestFinal_ex(&evp, md, NULL); EVP_MD_CTX_cleanup(&evp); if (memcmp(md, addenum_3, sizeof(addenum_3))) { fflush(stdout); fprintf(stderr, "\nTEST 3 of 3 failed.\n"); return 1; } else fprintf(stdout, "."); fflush(stdout); fprintf(stdout, " passed.\n"); fflush(stdout); return 0; } #endif
{ "language": "C++" }
// // detail/operation.hpp // ~~~~~~~~~~~~~~~~~~~~ // // Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com) // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // #ifndef ASIO_DETAIL_OPERATION_HPP #define ASIO_DETAIL_OPERATION_HPP #if defined(_MSC_VER) && (_MSC_VER >= 1200) # pragma once #endif // defined(_MSC_VER) && (_MSC_VER >= 1200) #include "asio/detail/config.hpp" #if defined(ASIO_HAS_IOCP) # include "asio/detail/win_iocp_operation.hpp" #else # include "asio/detail/scheduler_operation.hpp" #endif namespace asio { namespace detail { #if defined(ASIO_HAS_IOCP) typedef win_iocp_operation operation; #else typedef scheduler_operation operation; #endif } // namespace detail } // namespace asio #endif // ASIO_DETAIL_OPERATION_HPP
{ "language": "C++" }
/**************************************************************************** * VCGLib o o * * Visual and Computer Graphics Library o o * * _ O _ * * Copyright(C) 2014 \/)\/ * * Visual Computing Lab /\/| * * ISTI - Italian National Research Council | * * \ * * All rights reserved. * * * * 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 (http://www.gnu.org/licenses/gpl.txt) * * for more details. * * * ****************************************************************************/ /* Optimizes given UV-mapping with * [Least Square Conformal Maps] * (minimizes angle distrotions). * * Needs: * (-) per-vertex texture coords * (-) some fixed boundary: * Fixed vertices are the flagged ones. * By default: (use fixedMask parameter to customize) * BORDER or SELECTED verts are fixed. * * Example of usage: * MyMesh m; * vcg::tri::UpdateFlags< MyMesh >::VertexBorderFromNone( m ); * vcg::tri::OptimizeUV_LSCM( m ); * */ #ifndef __VCG_IGL_LEAST_SQUARES_CONFORMAL_MAPS #define __VCG_IGL_LEAST_SQUARES_CONFORMAL_MAPS #include <igl/lscm.h> #include <vcg/complex/algorithms/mesh_to_matrix.h> namespace vcg{ namespace tri{ template<class MeshType > void OptimizeUV_LSCM( MeshType& m , unsigned int fixedMask = MeshType::VertexType::BORDER | MeshType::VertexType::SELECTED ) { // check requirements vcg::tri::VertexVectorHasPerVertexTexCoord( m.vert ); vcg::tri::VertexVectorHasPerVertexFlags( m.vert ); Eigen::MatrixXd V; Eigen::MatrixXi F; Eigen::VectorXi b; Eigen::MatrixXd bc; Eigen::MatrixXd V_uv; vcg::tri::MeshToMatrix< MeshType >::GetTriMeshData( m, F, V ); // build fixed points data size_t nFixed = 0; for (int i=0; i<(int)m.vert.size(); i++) { if (m.vert[i].Flags()&fixedMask) nFixed++; } // all fixed, nothing to do? get out to avoid crashes if (nFixed == m.vert.size()) return; b.resize(nFixed); bc.resize(nFixed,2); for (int i=0,k=0; i<(int)m.vert.size(); i++) { if (m.vert[i].Flags()&fixedMask) { b(k) = i; bc(k,0) = m.vert[i].T().P()[0]; bc(k,1) = m.vert[i].T().P()[1]; k++; } } // apply Least Square Conformal Maps ::igl::lscm(V,F,b,bc,V_uv); // copy results back to mesh for (int i=0; i<(int)m.vert.size(); i++) { m.vert[i].T().P()[0] = V_uv(i,0); m.vert[i].T().P()[1] = V_uv(i,1); } } }} // namespaces #endif
{ "language": "C++" }
// Copyright (c) 2017 The vulkano developers // Licensed under the Apache License, Version 2.0 // <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT // license <LICENSE-MIT or http://opensource.org/licenses/MIT>, // at your option. All files in the project carrying such // notice may not be copied, modified, or distributed except // according to those terms. use std::error; use std::fmt; use device::Device; use format::FormatTy; use image::ImageAccess; use image::ImageDimensions; use sampler::Filter; use VulkanObject; /// Checks whether a blit image command is valid. /// /// Note that this doesn't check whether `layer_count` is equal to 0. TODO: change that? /// /// # Panic /// /// - Panics if the source or the destination was not created with `device`. /// pub fn check_blit_image<S, D>( device: &Device, source: &S, source_top_left: [i32; 3], source_bottom_right: [i32; 3], source_base_array_layer: u32, source_mip_level: u32, destination: &D, destination_top_left: [i32; 3], destination_bottom_right: [i32; 3], destination_base_array_layer: u32, destination_mip_level: u32, layer_count: u32, filter: Filter, ) -> Result<(), CheckBlitImageError> where S: ?Sized + ImageAccess, D: ?Sized + ImageAccess, { let source_inner = source.inner(); let destination_inner = destination.inner(); assert_eq!( source_inner.image.device().internal_object(), device.internal_object() ); assert_eq!( destination_inner.image.device().internal_object(), device.internal_object() ); if !source_inner.image.usage_transfer_source() { return Err(CheckBlitImageError::MissingTransferSourceUsage); } if !destination_inner.image.usage_transfer_destination() { return Err(CheckBlitImageError::MissingTransferDestinationUsage); } if !source_inner.image.supports_blit_source() { return Err(CheckBlitImageError::SourceFormatNotSupported); } if !destination_inner.image.supports_blit_destination() { return Err(CheckBlitImageError::DestinationFormatNotSupported); } if source.samples() != 1 || destination.samples() != 1 { return Err(CheckBlitImageError::UnexpectedMultisampled); } let source_format_ty = source.format().ty(); let destination_format_ty = destination.format().ty(); if source_format_ty.is_depth_and_or_stencil() { if source.format() != destination.format() { return Err(CheckBlitImageError::DepthStencilFormatMismatch); } if filter != Filter::Nearest { return Err(CheckBlitImageError::DepthStencilNearestMandatory); } } let types_should_be_same = source_format_ty == FormatTy::Uint || destination_format_ty == FormatTy::Uint || source_format_ty == FormatTy::Sint || destination_format_ty == FormatTy::Sint; if types_should_be_same && (source_format_ty != destination_format_ty) { return Err(CheckBlitImageError::IncompatibleFormatsTypes { source_format_ty: source.format().ty(), destination_format_ty: destination.format().ty(), }); } let source_dimensions = match source.dimensions().mipmap_dimensions(source_mip_level) { Some(d) => d, None => return Err(CheckBlitImageError::SourceCoordinatesOutOfRange), }; let destination_dimensions = match destination .dimensions() .mipmap_dimensions(destination_mip_level) { Some(d) => d, None => return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange), }; if source_base_array_layer + layer_count > source_dimensions.array_layers() { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if destination_base_array_layer + layer_count > destination_dimensions.array_layers() { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if source_top_left[0] < 0 || source_top_left[0] > source_dimensions.width() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if source_top_left[1] < 0 || source_top_left[1] > source_dimensions.height() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if source_top_left[2] < 0 || source_top_left[2] > source_dimensions.depth() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if source_bottom_right[0] < 0 || source_bottom_right[0] > source_dimensions.width() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if source_bottom_right[1] < 0 || source_bottom_right[1] > source_dimensions.height() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if source_bottom_right[2] < 0 || source_bottom_right[2] > source_dimensions.depth() as i32 { return Err(CheckBlitImageError::SourceCoordinatesOutOfRange); } if destination_top_left[0] < 0 || destination_top_left[0] > destination_dimensions.width() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if destination_top_left[1] < 0 || destination_top_left[1] > destination_dimensions.height() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if destination_top_left[2] < 0 || destination_top_left[2] > destination_dimensions.depth() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if destination_bottom_right[0] < 0 || destination_bottom_right[0] > destination_dimensions.width() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if destination_bottom_right[1] < 0 || destination_bottom_right[1] > destination_dimensions.height() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } if destination_bottom_right[2] < 0 || destination_bottom_right[2] > destination_dimensions.depth() as i32 { return Err(CheckBlitImageError::DestinationCoordinatesOutOfRange); } match source_dimensions { ImageDimensions::Dim1d { .. } => { if source_top_left[1] != 0 || source_bottom_right[1] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } if source_top_left[2] != 0 || source_bottom_right[2] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } } ImageDimensions::Dim2d { .. } => { if source_top_left[2] != 0 || source_bottom_right[2] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } } ImageDimensions::Dim3d { .. } => {} } match destination_dimensions { ImageDimensions::Dim1d { .. } => { if destination_top_left[1] != 0 || destination_bottom_right[1] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } if destination_top_left[2] != 0 || destination_bottom_right[2] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } } ImageDimensions::Dim2d { .. } => { if destination_top_left[2] != 0 || destination_bottom_right[2] != 1 { return Err(CheckBlitImageError::IncompatibleRangeForImageType); } } ImageDimensions::Dim3d { .. } => {} } Ok(()) } /// Error that can happen from `check_clear_color_image`. #[derive(Debug, Copy, Clone)] pub enum CheckBlitImageError { /// The source is missing the transfer source usage. MissingTransferSourceUsage, /// The destination is missing the transfer destination usage. MissingTransferDestinationUsage, /// The format of the source image doesn't support blit operations. SourceFormatNotSupported, /// The format of the destination image doesn't support blit operations. DestinationFormatNotSupported, /// You must use the nearest filter when blitting depth/stencil images. DepthStencilNearestMandatory, /// The format of the source and destination must be equal when blitting depth/stencil images. DepthStencilFormatMismatch, /// The types of the source format and the destination format aren't compatible. IncompatibleFormatsTypes { source_format_ty: FormatTy, destination_format_ty: FormatTy, }, /// Blitting between multisampled images is forbidden. UnexpectedMultisampled, /// The offsets, array layers and/or mipmap levels are out of range in the source image. SourceCoordinatesOutOfRange, /// The offsets, array layers and/or mipmap levels are out of range in the destination image. DestinationCoordinatesOutOfRange, /// The top-left and/or bottom-right coordinates are incompatible with the image type. IncompatibleRangeForImageType, } impl error::Error for CheckBlitImageError {} impl fmt::Display for CheckBlitImageError { #[inline] fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!( fmt, "{}", match *self { CheckBlitImageError::MissingTransferSourceUsage => { "the source is missing the transfer source usage" } CheckBlitImageError::MissingTransferDestinationUsage => { "the destination is missing the transfer destination usage" } CheckBlitImageError::SourceFormatNotSupported => { "the format of the source image doesn't support blit operations" } CheckBlitImageError::DestinationFormatNotSupported => { "the format of the destination image doesn't support blit operations" } CheckBlitImageError::DepthStencilNearestMandatory => { "you must use the nearest filter when blitting depth/stencil images" } CheckBlitImageError::DepthStencilFormatMismatch => { "the format of the source and destination must be equal when blitting \ depth/stencil images" } CheckBlitImageError::IncompatibleFormatsTypes { .. } => { "the types of the source format and the destination format aren't compatible" } CheckBlitImageError::UnexpectedMultisampled => { "blitting between multisampled images is forbidden" } CheckBlitImageError::SourceCoordinatesOutOfRange => { "the offsets, array layers and/or mipmap levels are out of range in the source \ image" } CheckBlitImageError::DestinationCoordinatesOutOfRange => { "the offsets, array layers and/or mipmap levels are out of range in the \ destination image" } CheckBlitImageError::IncompatibleRangeForImageType => { "the top-left and/or bottom-right coordinates are incompatible with the image type" } } ) } }
{ "language": "C++" }
// Ryzom - MMORPG Framework <http://dev.ryzom.com/projects/ryzom/> // Copyright (C) 2010 Winch Gate Property Limited // // This program 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. // // 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/>. ///////////// // INCLUDE // ///////////// #include "stdpch.h" // Client #include "demo.h" #include "entities.h" #include "client_cfg.h" #include "ingame_database_manager.h" #include "user_entity.h" #include "time_client.h" #include "net_manager.h" // MISC #include "nel/misc/sheet_id.h" /////////// // USING // /////////// using namespace NLMISC; using namespace std; //////////// // GLOBAL // //////////// // Hierarchical timer H_AUTO_DECL ( RZ_Client_Update_Demo ) /////////////// // FUNCTIONS // /////////////// //----------------------------------------------- // initDemo : // Call a function for a demo to init. //----------------------------------------------- void initDemo() { for(uint i = 0; i<ClientCfg.StartCommands.size()/7; ++i) { //////////// // CREATE // //////////// // Which slot to use. CLFECOMMON::TCLEntityId entitySlot = i+1; // Try to create the sheet with the parameter as a string. CSheetId sheetId; if(!sheetId.buildSheetId(ClientCfg.StartCommands[i*7])) { nlwarning("initDemo: cannot create the entity %d '%s'.", i*7, ClientCfg.StartCommands[i*7].c_str()); continue; } // Remove the old entity. EntitiesMngr.remove(entitySlot, false); // Create the new entity. TNewEntityInfo emptyEntityInfo; emptyEntityInfo.reset(); CEntityCL *entity = EntitiesMngr.create(entitySlot, sheetId.asInt(), emptyEntityInfo); if(entity) { double xTmp, yTmp, zTmp; fromString(ClientCfg.StartCommands[i*7+1], xTmp); fromString(ClientCfg.StartCommands[i*7+2], yTmp); fromString(ClientCfg.StartCommands[i*7+3], zTmp); // Compute the position (FIRST POS AFTER CREATE IS THE START POSITION). sint64 x = (sint64)(xTmp*1000.0); sint64 y = (sint64)(yTmp*1000.0); sint64 z = (sint64)(zTmp*1000.0); // Write the position in the DB. IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P0", x); IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P1", y); IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P2", z); // Update the position. uint gameCycle = NetMngr.getCurrentClientTick(); uint prop = 0; // 0: Position ; 3: orientation ; 4: mode ; 5: behaviour ; 6: nameId ; 7: target ; 8: visual1 ; 9: visual2 EntitiesMngr.updateVisualProperty(gameCycle, entitySlot, prop); // Set the direction float xTmp2, yTmp2, zTmp2; fromString(ClientCfg.StartCommands[i*7+4], xTmp2); fromString(ClientCfg.StartCommands[i*7+5], yTmp2); fromString(ClientCfg.StartCommands[i*7+6], zTmp2); entity->front(CVector(xTmp2, yTmp2, zTmp2)); entity->dir(UserEntity->front()); /* ////////// // MOVE // ////////// gameCycle = NetMngr.getCurrentClientTick()+100; // 10sec later. x = (sint64)((entity->pos().x+UserEntity->front().x*50.0)*1000.0); y = (sint64)((entity->pos().y+UserEntity->front().y*50.0)*1000.0); z = (sint64)((entity->pos().z+UserEntity->front().z*50.0)*1000.0); // Write the position in the DB. IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P0", x); IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P1", y); IngameDbMngr.setProp("Entities:E" + toString(entitySlot) + ":P2", z); // Update the position. EntitiesMngr.updateVisualProperty(gameCycle, entitySlot, prop); */ } else nldebug("initDemo: entity(%s) in slot %d cannot be created.", sheetId.toString().c_str(), entitySlot); } }// initDemo // //----------------------------------------------- // updateDemo : // Call a function for a demo to update. //----------------------------------------------- void updateDemo(double /* timeElapsed */) { H_AUTO_USE ( RZ_Client_Update_Demo ) }// updateDemo //
{ "language": "C++" }
#ifndef GAINPUTINPUTDEVICEKEYBOARDEVDEV_H_ #define GAINPUTINPUTDEVICEKEYBOARDEVDEV_H_ #include "../GainputHelpersEvdev.h" #include "../../../include/gainput/GainputHelpers.h" namespace gainput { class InputDeviceKeyboardImplEvdev : public InputDeviceKeyboardImpl { public: InputDeviceKeyboardImplEvdev(InputManager& manager, InputDevice& device, InputState& state, InputState& previousState) : manager_(manager), device_(device), textInputEnabled_(true), dialect_(manager_.GetAllocator()), fd_(-1), state_(&state) { unsigned matchingDeviceCount = 0; for (unsigned i = 0; i < EvdevDeviceCount; ++i) { fd_ = open(EvdevDeviceIds[i], O_RDONLY|O_NONBLOCK); if (fd_ == -1) { continue; } EvdevDevice evdev(fd_); if (evdev.IsValid()) { if (evdev.GetDeviceType() == InputDevice::DT_KEYBOARD) { if (matchingDeviceCount == manager_.GetDeviceCountByType(InputDevice::DT_KEYBOARD)) { break; } ++matchingDeviceCount; } } close(fd_); fd_ = -1; } dialect_[KEY_ESC] = KeyEscape; dialect_[KEY_1] = Key1; dialect_[KEY_2] = Key2; dialect_[KEY_3] = Key3; dialect_[KEY_4] = Key4; dialect_[KEY_5] = Key5; dialect_[KEY_6] = Key6; dialect_[KEY_7] = Key7; dialect_[KEY_8] = Key8; dialect_[KEY_9] = Key9; dialect_[KEY_0] = Key0; dialect_[KEY_MINUS] = KeyMinus; dialect_[KEY_EQUAL] = KeyEqual; dialect_[KEY_BACKSPACE] = KeyBackSpace; dialect_[KEY_TAB] = KeyTab; dialect_[KEY_Q] = KeyQ; dialect_[KEY_W] = KeyW; dialect_[KEY_E] = KeyE; dialect_[KEY_R] = KeyR; dialect_[KEY_T] = KeyT; dialect_[KEY_Y] = KeyY; dialect_[KEY_U] = KeyU; dialect_[KEY_I] = KeyI; dialect_[KEY_O] = KeyO; dialect_[KEY_P] = KeyP; dialect_[KEY_LEFTBRACE] = KeyBraceLeft; dialect_[KEY_RIGHTBRACE] = KeyBraceRight; dialect_[KEY_ENTER] = KeyReturn; dialect_[KEY_LEFTCTRL] = KeyCtrlL; dialect_[KEY_A] = KeyA; dialect_[KEY_S] = KeyS; dialect_[KEY_D] = KeyD; dialect_[KEY_F] = KeyF; dialect_[KEY_G] = KeyG; dialect_[KEY_H] = KeyH; dialect_[KEY_J] = KeyJ; dialect_[KEY_K] = KeyK; dialect_[KEY_L] = KeyL; dialect_[KEY_SEMICOLON] = KeySemicolon; dialect_[KEY_APOSTROPHE] = KeyApostrophe; dialect_[KEY_GRAVE] = KeyGrave; dialect_[KEY_LEFTSHIFT] = KeyShiftL; dialect_[KEY_BACKSLASH] = KeyBackslash; dialect_[KEY_Z] = KeyZ; dialect_[KEY_X] = KeyX; dialect_[KEY_C] = KeyC; dialect_[KEY_V] = KeyV; dialect_[KEY_B] = KeyB; dialect_[KEY_N] = KeyN; dialect_[KEY_M] = KeyM; dialect_[KEY_COMMA] = KeyComma; dialect_[KEY_DOT] = KeyPeriod; dialect_[KEY_SLASH] = KeySlash; dialect_[KEY_RIGHTSHIFT] = KeyShiftR; dialect_[KEY_KPASTERISK] = KeyKpMultiply; dialect_[KEY_LEFTALT] = KeyAltL; dialect_[KEY_SPACE] = KeySpace; dialect_[KEY_CAPSLOCK] = KeyCapsLock; dialect_[KEY_F1] = KeyF1; dialect_[KEY_F2] = KeyF2; dialect_[KEY_F3] = KeyF3; dialect_[KEY_F4] = KeyF4; dialect_[KEY_F5] = KeyF5; dialect_[KEY_F6] = KeyF6; dialect_[KEY_F7] = KeyF7; dialect_[KEY_F8] = KeyF8; dialect_[KEY_F9] = KeyF9; dialect_[KEY_F10] = KeyF10; dialect_[KEY_NUMLOCK] = KeyNumLock; dialect_[KEY_SCROLLLOCK] = KeyScrollLock; dialect_[KEY_KP7] = KeyKpHome; dialect_[KEY_KP8] = KeyKpUp; dialect_[KEY_KP9] = KeyKpPageUp; dialect_[KEY_KPMINUS] = KeyKpSubtract; dialect_[KEY_KP4] = KeyKpLeft; dialect_[KEY_KP5] = KeyKpBegin; dialect_[KEY_KP6] = KeyKpRight; dialect_[KEY_KPPLUS] = KeyKpAdd; dialect_[KEY_KP1] = KeyKpEnd; dialect_[KEY_KP2] = KeyKpDown; dialect_[KEY_KP3] = KeyKpPageDown; dialect_[KEY_KP0] = KeyKpInsert; dialect_[KEY_KPDOT] = KeyKpDelete; dialect_[KEY_F11] = KeyF11; dialect_[KEY_F12] = KeyF12; dialect_[KEY_KPENTER] = KeyKpEnter; dialect_[KEY_RIGHTCTRL] = KeyCtrlR; dialect_[KEY_KPSLASH] = KeyKpDivide; dialect_[KEY_SYSRQ] = KeySysRq; dialect_[KEY_RIGHTALT] = KeyAltR; dialect_[KEY_HOME] = KeyHome; dialect_[KEY_UP] = KeyUp; dialect_[KEY_PAGEUP] = KeyPageUp; dialect_[KEY_LEFT] = KeyLeft; dialect_[KEY_RIGHT] = KeyRight; dialect_[KEY_END] = KeyEnd; dialect_[KEY_DOWN] = KeyDown; dialect_[KEY_PAGEDOWN] = KeyPageDown; dialect_[KEY_INSERT] = KeyInsert; dialect_[KEY_DELETE] = KeyDelete; dialect_[KEY_MUTE] = KeyMute; dialect_[KEY_VOLUMEDOWN] = KeyVolumeDown; dialect_[KEY_VOLUMEUP] = KeyVolumeUp; dialect_[KEY_POWER] = KeyPower; dialect_[KEY_PAUSE] = KeyBreak; dialect_[KEY_KPCOMMA] = KeyKpDelete; dialect_[KEY_LEFTMETA] = KeySuperL; dialect_[KEY_RIGHTMETA] = KeySuperR; dialect_[KEY_BACK] = KeyBack; dialect_[KEY_FORWARD] = KeyForward; dialect_[KEY_NEXTSONG] = KeyMediaNext; dialect_[KEY_PLAYPAUSE] = KeyMediaPlayPause; dialect_[KEY_PREVIOUSSONG] = KeyMediaPrevious; dialect_[KEY_STOPCD] = KeyMediaStop; dialect_[KEY_CAMERA] = KeyCamera; dialect_[KEY_COMPOSE] = KeyEnvelope; dialect_[KEY_REWIND] = KeyMediaRewind; dialect_[KEY_FASTFORWARD] = KeyMediaFastForward; } ~InputDeviceKeyboardImplEvdev() { if (fd_ != -1) { close(fd_); } } InputDevice::DeviceVariant GetVariant() const { return InputDevice::DV_RAW; } InputDevice::DeviceState GetState() const { return fd_ != -1 ? InputDevice::DS_OK : InputDevice::DS_UNAVAILABLE; } virtual InputState * GetNextInputState() override { return NULL; } void Update(InputDeltaState* delta) { if (fd_ < 0) { return; } struct input_event event; for (;;) { int len = read(fd_, &event, sizeof(struct input_event)); if (len != sizeof(struct input_event)) { break; } if (event.type == EV_KEY) { if (dialect_.count(event.code)) { const DeviceButtonId button = dialect_[event.code]; HandleButton(device_, *state_, delta, button, bool(event.value)); } } } } bool IsTextInputEnabled() const { return textInputEnabled_; } void SetTextInputEnabled(bool enabled) { textInputEnabled_ = enabled; } wchar_t* GetTextInput(uint32_t* count) { *count = 0; return NULL; } private: InputManager& manager_; InputDevice& device_; bool textInputEnabled_; HashMap<unsigned, DeviceButtonId> dialect_; int fd_; InputState* state_; }; } #endif
{ "language": "C++" }
 /* Copyright (c) 2016-present Maximus5 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 name of the authors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #define HIDE_USE_EXCEPTION_INFO #define SHOWDEBUGSTR #include "Header.h" #include "ConEmu.h" #include "LngRc.h" #include "OptionsClass.h" #include "SetColorPalette.h" #include "SetDlgLists.h" #include "SetDlgButtons.h" #include "SetDlgColors.h" #include "SetPgColors.h" CSetPgColors::CSetPgColors() { } CSetPgColors::~CSetPgColors() { } LRESULT CSetPgColors::OnInitDialog(HWND hDlg, bool abInitial) { #if 0 if (gpSetCls->EnableThemeDialogTextureF) gpSetCls->EnableThemeDialogTextureF(hDlg, 6/*ETDT_ENABLETAB*/); #endif checkRadioButton(hDlg, rbColorRgbDec, rbColorBgrHex, rbColorRgbDec + gpSetCls->m_ColorFormat); for (int c = c0; c <= CSetDlgColors::MAX_COLOR_EDT_ID; c++) { ColorSetEdit(hDlg, c); InvalidateCtrl(GetDlgItem(hDlg, c), TRUE); } CSetDlgLists::FillListBoxItems(GetDlgItem(hDlg, lbConClrText), CSetDlgLists::eColorIdxTh, gpSet->AppStd.nTextColorIdx, true); CSetDlgLists::FillListBoxItems(GetDlgItem(hDlg, lbConClrBack), CSetDlgLists::eColorIdxTh, gpSet->AppStd.nBackColorIdx, true); CSetDlgLists::FillListBoxItems(GetDlgItem(hDlg, lbConClrPopText), CSetDlgLists::eColorIdxTh, gpSet->AppStd.nPopTextColorIdx, true); CSetDlgLists::FillListBoxItems(GetDlgItem(hDlg, lbConClrPopBack), CSetDlgLists::eColorIdxTh, gpSet->AppStd.nPopBackColorIdx, true); //WARNING("Отладка..."); //if (gpSet->AppStd.nPopTextColorIdx <= 15 || gpSet->AppStd.nPopBackColorIdx <= 15 // || RELEASEDEBUGTEST(FALSE,TRUE)) //{ // EnableWindow(GetDlgItem(hDlg, lbConClrPopText), TRUE); // EnableWindow(GetDlgItem(hDlg, lbConClrPopBack), TRUE); //} checkDlgButton(hDlg, cbTrueColorer, gpSet->isTrueColorer ? BST_CHECKED : BST_UNCHECKED); checkDlgButton(hDlg, cbVividColors, gpSet->isVividColors ? BST_CHECKED : BST_UNCHECKED); checkDlgButton(hDlg, cbFadeInactive, gpSet->isFadeInactive ? BST_CHECKED : BST_UNCHECKED); SetDlgItemInt(hDlg, tFadeLow, gpSet->mn_FadeLow, FALSE); SetDlgItemInt(hDlg, tFadeHigh, gpSet->mn_FadeHigh, FALSE); // Palette const ColorPalette* pPal; // Default colors if (!abInitial && gbLastColorsOk) { // активация уже загруженной вкладки, текущую палитру уже запомнили } else if ((pPal = gpSet->PaletteGet(-1)) != NULL) { memmove(&gLastColors, pPal, sizeof(gLastColors)); if (gLastColors.pszName == NULL) { _ASSERTE(gLastColors.pszName!=NULL); static wchar_t szCurrentScheme[64] = L""; lstrcpyn(szCurrentScheme, CLngRc::getRsrc(lng_CurClrScheme/*"<Current color scheme>"*/), countof(szCurrentScheme)); gLastColors.pszName = szCurrentScheme; } } else { EnableWindow(hDlg, FALSE); MBoxAssert(pPal && "PaletteGet(-1) failed"); return 0; } SendMessage(GetDlgItem(hDlg, lbDefaultColors), CB_RESETCONTENT, 0, 0); SendDlgItemMessage(hDlg, lbDefaultColors, CB_ADDSTRING, 0, (LPARAM)gLastColors.pszName); for (int i = 0; (pPal = gpSet->PaletteGet(i)) != NULL; i++) { SendDlgItemMessage(hDlg, lbDefaultColors, CB_ADDSTRING, 0, (LPARAM)pPal->pszName); } // Find saved palette with current colors and attributes pPal = gpSet->PaletteFindCurrent(true); if (pPal) CSetDlgLists::SelectStringExact(hDlg, lbDefaultColors, pPal->pszName); else SendDlgItemMessage(hDlg, lbDefaultColors, CB_SETCURSEL, 0, 0); bool bBtnEnabled = pPal && !pPal->bPredefined; // Save & Delete buttons EnableWindow(GetDlgItem(hDlg, cbColorSchemeSave), bBtnEnabled); EnableWindow(GetDlgItem(hDlg, cbColorSchemeDelete), bBtnEnabled); gbLastColorsOk = TRUE; return 0; } INT_PTR CSetPgColors::OnComboBox(HWND hDlg, WORD nCtrlId, WORD code) { bool bDoUpdate = true; switch (nCtrlId) { case lbConClrText: { gpSet->AppStd.nTextColorIdx = SendDlgItemMessage(hDlg, nCtrlId, CB_GETCURSEL, 0, 0); if (gpSet->AppStd.nTextColorIdx != gpSet->AppStd.nBackColorIdx) gpSetCls->UpdateTextColorSettings(TRUE, FALSE); break; } // lbConClrText case lbConClrBack: { gpSet->AppStd.nBackColorIdx = SendDlgItemMessage(hDlg, nCtrlId, CB_GETCURSEL, 0, 0); if (gpSet->AppStd.nTextColorIdx != gpSet->AppStd.nBackColorIdx) gpSetCls->UpdateTextColorSettings(TRUE, FALSE); break; } // lbConClrBack case lbConClrPopText: { gpSet->AppStd.nPopTextColorIdx = SendDlgItemMessage(hDlg, nCtrlId, CB_GETCURSEL, 0, 0); if (gpSet->AppStd.nPopTextColorIdx != gpSet->AppStd.nPopBackColorIdx) gpSetCls->UpdateTextColorSettings(FALSE, TRUE); break; } // lbConClrPopText case lbConClrPopBack: { gpSet->AppStd.nPopBackColorIdx = SendDlgItemMessage(hDlg, nCtrlId, CB_GETCURSEL, 0, 0); if (gpSet->AppStd.nPopTextColorIdx != gpSet->AppStd.nPopBackColorIdx) gpSetCls->UpdateTextColorSettings(FALSE, TRUE); break; } // lbConClrPopBack case lbDefaultColors: { HWND hList = GetDlgItem(hDlg, lbDefaultColors); INT_PTR nIdx = SendMessage(hList, CB_GETCURSEL, 0, 0); // Save & Delete buttons { bool bEnabled = false; wchar_t* pszText = NULL; if (code == CBN_EDITCHANGE) { INT_PTR nLen = GetWindowTextLength(hList); pszText = (nLen > 0) ? (wchar_t*)malloc((nLen+1)*sizeof(wchar_t)) : NULL; if (pszText) GetWindowText(hList, pszText, nLen+1); } else if ((code == CBN_SELCHANGE) && nIdx > 0) // 0 -- current color scheme. ее удалять/сохранять "нельзя" { INT_PTR nLen = SendMessage(hList, CB_GETLBTEXTLEN, nIdx, 0); pszText = (nLen > 0) ? (wchar_t*)malloc((nLen+1)*sizeof(wchar_t)) : NULL; if (pszText) SendMessage(hList, CB_GETLBTEXT, nIdx, (LPARAM)pszText); } if (pszText) { bEnabled = (wcspbrk(pszText, L"<>") == NULL); SafeFree(pszText); } EnableWindow(GetDlgItem(hDlg, cbColorSchemeSave), bEnabled); EnableWindow(GetDlgItem(hDlg, cbColorSchemeDelete), bEnabled); } // Юзер выбрал в списке другую палитру if ((code == CBN_SELCHANGE) && gbLastColorsOk) // только если инициализация палитр завершилась { const ColorPalette* pPal = NULL; if (nIdx == 0) pPal = &gLastColors; else if ((pPal = gpSet->PaletteGet(nIdx-1)) == NULL) return 0; // неизвестный набор gpSetCls->ChangeCurrentPalette(pPal, false); bDoUpdate = false; } break; } // lbDefaultColors } if (bDoUpdate) gpConEmu->Update(true); return 0; } LRESULT CSetPgColors::OnEditChanged(HWND hDlg, WORD nCtrlId) { COLORREF color = 0; if (nCtrlId == tFadeLow || nCtrlId == tFadeHigh) { BOOL lbOk = FALSE; UINT nVal = GetDlgItemInt(hDlg, nCtrlId, &lbOk, FALSE); if (lbOk && nVal <= 255) { if (nCtrlId == tFadeLow) gpSet->mn_FadeLow = nVal; else gpSet->mn_FadeHigh = nVal; gpSet->ResetFadeColors(); //gpSet->mb_FadeInitialized = false; //gpSet->mn_LastFadeSrc = gpSet->mn_LastFadeDst = -1; } } else if (CSetDlgColors::GetColorById(nCtrlId - (tc0-c0), &color)) { if (CSetDlgColors::GetColorRef(hDlg, nCtrlId, &color)) { if (CSetDlgColors::SetColorById(nCtrlId - (tc0-c0), color)) { gpConEmu->InvalidateAll(); if (nCtrlId >= tc0 && nCtrlId <= tc15) gpConEmu->Update(true); InvalidateCtrl(GetDlgItem(hDlg, nCtrlId - (tc0-c0)), TRUE); } } } else { _ASSERTE(FALSE && "EditBox was not processed"); } return 0; } void CSetPgColors::ColorSchemeSaveDelete(WORD CB, BYTE uCheck) { _ASSERTE(CB==cbColorSchemeSave || CB==cbColorSchemeDelete); if (!mh_Dlg) { _ASSERTE(mh_Dlg!=NULL); return; } HWND hList = GetDlgItem(mh_Dlg, lbDefaultColors); int nLen = GetWindowTextLength(hList); if (nLen < 1) return; wchar_t* pszName = (wchar_t*)malloc((nLen+1)*sizeof(wchar_t)); GetWindowText(hList, pszName, nLen+1); if (*pszName != L'<') { if (CB == cbColorSchemeSave) gpSet->PaletteSaveAs(pszName); else gpSet->PaletteDelete(pszName); } // Set focus in list, buttons may become disabled now SetFocus(hList); HWND hCB = GetDlgItem(mh_Dlg, CB); SetWindowLongPtr(hCB, GWL_STYLE, GetWindowLongPtr(hCB, GWL_STYLE) & ~BS_DEFPUSHBUTTON); // Refresh OnInitDialog(mh_Dlg, false); SafeFree(pszName); } // cbColorSchemeSave || cbColorSchemeDelete
{ "language": "C++" }
/* * Generated by confdc --mib2yang-std * Source: mgmt/dmi/model/common/mib-source/VPN-TC-STD-MIB.mib */ /* * This YANG module has been generated by smidump 0.5.0: * * smidump -f yang VPN-TC-STD-MIB * * Do not edit. Edit the source file instead! */ module VPN-TC-STD-MIB { namespace "urn:ietf:params:xml:ns:yang:smiv2:VPN-TC-STD-MIB"; prefix VPN-TC-STD-MIB; import ietf-yang-smiv2 { prefix "smiv2"; } organization "Layer 3 Virtual Private Networks (L3VPN) Working Group."; contact "Benson Schliesser bensons@savvis.net Thomas D. Nadeau tnadeau@cisco.com This TC MIB is a product of the PPVPN http://www.ietf.org/html.charters/ppvpn-charter.html and subsequently the L3VPN http://www.ietf.org/html.charters/l3vpn-charter.html working groups. Comments and discussion should be directed to l3vpn@ietf.org"; description "This MIB contains TCs for VPNs. Copyright (C) The Internet Society (2005). This version of this MIB module is part of RFC 4265; see the RFC itself for full legal notices."; revision 2005-11-15 { description "Initial version, published as RFC 4265."; } typedef VPNId { type binary { length "7"; } description "The purpose of a VPN-ID is to uniquely identify a VPN. The Global VPN Identifier format is: 3 octet VPN Authority, Organizationally Unique Identifier followed by 4 octet VPN index identifying VPN according to OUI"; reference "Fox, B. and Gleeson, B., 'Virtual Private Networks Identifier', RFC 2685, September 1999."; } typedef VPNIdOrZero { type binary { length "0|7"; } description "This textual convention is an extension of the VPNId textual convention that defines a non-zero-length OCTET STRING to identify a physical entity. This extension permits the additional value of a zero-length OCTET STRING. The semantics of the value zero-length OCTET STRING are object-specific and must therefore be defined as part of the description of any object that uses this syntax. Examples of usage of this extension are situations where none or all VPN IDs need to be referenced."; } smiv2:alias "vpnTcMIB" { smiv2:oid "1.3.6.1.2.1.129"; } }
{ "language": "C++" }
/* * Copyright (C) 2004, 2005, 2006, 2007 Nikolas Zimmermann <zimmermann@kde.org> * Copyright (C) 2004, 2005 Rob Buis <buis@kde.org> * Copyright (C) 2005 Eric Seidel <eric@webkit.org> * Copyright (C) 2013 Google Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_COMPOSITE_H_ #define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_COMPOSITE_H_ #include "third_party/blink/renderer/platform/graphics/filters/filter_effect.h" #include "third_party/skia/include/core/SkBlendMode.h" namespace blink { enum CompositeOperationType { FECOMPOSITE_OPERATOR_UNKNOWN = 0, FECOMPOSITE_OPERATOR_OVER = 1, FECOMPOSITE_OPERATOR_IN = 2, FECOMPOSITE_OPERATOR_OUT = 3, FECOMPOSITE_OPERATOR_ATOP = 4, FECOMPOSITE_OPERATOR_XOR = 5, FECOMPOSITE_OPERATOR_ARITHMETIC = 6, FECOMPOSITE_OPERATOR_LIGHTER = 7 }; class PLATFORM_EXPORT FEComposite final : public FilterEffect { public: FEComposite(Filter*, const CompositeOperationType&, float, float, float, float); CompositeOperationType Operation() const; bool SetOperation(CompositeOperationType); float K1() const; bool SetK1(float); float K2() const; bool SetK2(float); float K3() const; bool SetK3(float); float K4() const; bool SetK4(float); WTF::TextStream& ExternalRepresentation(WTF::TextStream&, int indention) const override; protected: bool MayProduceInvalidPreMultipliedPixels() override { return type_ == FECOMPOSITE_OPERATOR_ARITHMETIC; } private: FloatRect MapInputs(const FloatRect&) const override; bool AffectsTransparentPixels() const override; sk_sp<PaintFilter> CreateImageFilter() override; sk_sp<PaintFilter> CreateImageFilterWithoutValidation() override; sk_sp<PaintFilter> CreateImageFilterInternal( bool requires_pm_color_validation); CompositeOperationType type_; float k1_; float k2_; float k3_; float k4_; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_FILTERS_FE_COMPOSITE_H_
{ "language": "C++" }
/* * replay.c * * Copyright (c) 2010-2015 Institute for System Programming * of the Russian Academy of Sciences. * * This work is licensed under the terms of the GNU GPL, version 2 or later. * See the COPYING file in the top-level directory. * */ #include "qemu/osdep.h" #include "qapi/error.h" #include "sysemu/replay.h" #include "replay-internal.h" #include "qemu/timer.h" #include "qemu/main-loop.h" #include "qemu/option.h" #include "sysemu/cpus.h" #include "sysemu/sysemu.h" #include "qemu/error-report.h" /* Current version of the replay mechanism. Increase it when file format changes. */ #define REPLAY_VERSION 0xe02007 /* Size of replay log header */ #define HEADER_SIZE (sizeof(uint32_t) + sizeof(uint64_t)) ReplayMode replay_mode = REPLAY_MODE_NONE; char *replay_snapshot; /* Name of replay file */ static char *replay_filename; ReplayState replay_state; static GSList *replay_blockers; bool replay_next_event_is(int event) { bool res = false; /* nothing to skip - not all instructions used */ if (replay_state.instructions_count != 0) { assert(replay_state.data_kind == EVENT_INSTRUCTION); return event == EVENT_INSTRUCTION; } while (true) { if (event == replay_state.data_kind) { res = true; } switch (replay_state.data_kind) { case EVENT_SHUTDOWN ... EVENT_SHUTDOWN_LAST: replay_finish_event(); qemu_system_shutdown_request(replay_state.data_kind - EVENT_SHUTDOWN); break; default: /* clock, time_t, checkpoint and other events */ return res; } } return res; } uint64_t replay_get_current_step(void) { return cpu_get_icount_raw(); } int replay_get_instructions(void) { int res = 0; replay_mutex_lock(); if (replay_next_event_is(EVENT_INSTRUCTION)) { res = replay_state.instructions_count; } replay_mutex_unlock(); return res; } void replay_account_executed_instructions(void) { if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); if (replay_state.instructions_count > 0) { int count = (int)(replay_get_current_step() - replay_state.current_step); /* Time can only go forward */ assert(count >= 0); replay_state.instructions_count -= count; replay_state.current_step += count; if (replay_state.instructions_count == 0) { assert(replay_state.data_kind == EVENT_INSTRUCTION); replay_finish_event(); /* Wake up iothread. This is required because timers will not expire until clock counters will be read from the log. */ qemu_notify_event(); } } } } bool replay_exception(void) { if (replay_mode == REPLAY_MODE_RECORD) { g_assert(replay_mutex_locked()); replay_save_instructions(); replay_put_event(EVENT_EXCEPTION); return true; } else if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); bool res = replay_has_exception(); if (res) { replay_finish_event(); } return res; } return true; } bool replay_has_exception(void) { bool res = false; if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); replay_account_executed_instructions(); res = replay_next_event_is(EVENT_EXCEPTION); } return res; } bool replay_interrupt(void) { if (replay_mode == REPLAY_MODE_RECORD) { g_assert(replay_mutex_locked()); replay_save_instructions(); replay_put_event(EVENT_INTERRUPT); return true; } else if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); bool res = replay_has_interrupt(); if (res) { replay_finish_event(); } return res; } return true; } bool replay_has_interrupt(void) { bool res = false; if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); replay_account_executed_instructions(); res = replay_next_event_is(EVENT_INTERRUPT); } return res; } void replay_shutdown_request(ShutdownCause cause) { if (replay_mode == REPLAY_MODE_RECORD) { g_assert(replay_mutex_locked()); replay_put_event(EVENT_SHUTDOWN + cause); } } bool replay_checkpoint(ReplayCheckpoint checkpoint) { bool res = false; static bool in_checkpoint; assert(EVENT_CHECKPOINT + checkpoint <= EVENT_CHECKPOINT_LAST); if (!replay_file) { return true; } if (in_checkpoint) { /* If we are already in checkpoint, then there is no need for additional synchronization. Recursion occurs when HW event modifies timers. Timer modification may invoke the checkpoint and proceed to recursion. */ return true; } in_checkpoint = true; replay_save_instructions(); if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); if (replay_next_event_is(EVENT_CHECKPOINT + checkpoint)) { replay_finish_event(); } else if (replay_state.data_kind != EVENT_ASYNC) { res = false; goto out; } replay_read_events(checkpoint); /* replay_read_events may leave some unread events. Return false if not all of the events associated with checkpoint were processed */ res = replay_state.data_kind != EVENT_ASYNC; } else if (replay_mode == REPLAY_MODE_RECORD) { g_assert(replay_mutex_locked()); replay_put_event(EVENT_CHECKPOINT + checkpoint); /* This checkpoint belongs to several threads. Processing events from different threads is non-deterministic */ if (checkpoint != CHECKPOINT_CLOCK_WARP_START /* FIXME: this is temporary fix, other checkpoints may also be invoked from the different threads someday. Asynchronous event processing should be refactored to create additional replay event kind which is nailed to the one of the threads and which processes the event queue. */ && checkpoint != CHECKPOINT_CLOCK_VIRTUAL) { replay_save_events(checkpoint); } res = true; } out: in_checkpoint = false; return res; } bool replay_has_checkpoint(void) { bool res = false; if (replay_mode == REPLAY_MODE_PLAY) { g_assert(replay_mutex_locked()); replay_account_executed_instructions(); res = EVENT_CHECKPOINT <= replay_state.data_kind && replay_state.data_kind <= EVENT_CHECKPOINT_LAST; } return res; } static void replay_enable(const char *fname, int mode) { const char *fmode = NULL; assert(!replay_file); switch (mode) { case REPLAY_MODE_RECORD: fmode = "wb"; break; case REPLAY_MODE_PLAY: fmode = "rb"; break; default: fprintf(stderr, "Replay: internal error: invalid replay mode\n"); exit(1); } atexit(replay_finish); replay_file = fopen(fname, fmode); if (replay_file == NULL) { fprintf(stderr, "Replay: open %s: %s\n", fname, strerror(errno)); exit(1); } replay_filename = g_strdup(fname); replay_mode = mode; replay_mutex_init(); replay_state.data_kind = -1; replay_state.instructions_count = 0; replay_state.current_step = 0; replay_state.has_unread_data = 0; /* skip file header for RECORD and check it for PLAY */ if (replay_mode == REPLAY_MODE_RECORD) { fseek(replay_file, HEADER_SIZE, SEEK_SET); } else if (replay_mode == REPLAY_MODE_PLAY) { unsigned int version = replay_get_dword(); if (version != REPLAY_VERSION) { fprintf(stderr, "Replay: invalid input log file version\n"); exit(1); } /* go to the beginning */ fseek(replay_file, HEADER_SIZE, SEEK_SET); replay_fetch_data_kind(); } replay_init_events(); } void replay_configure(QemuOpts *opts) { const char *fname; const char *rr; ReplayMode mode = REPLAY_MODE_NONE; Location loc; if (!opts) { return; } loc_push_none(&loc); qemu_opts_loc_restore(opts); rr = qemu_opt_get(opts, "rr"); if (!rr) { /* Just enabling icount */ goto out; } else if (!strcmp(rr, "record")) { mode = REPLAY_MODE_RECORD; } else if (!strcmp(rr, "replay")) { mode = REPLAY_MODE_PLAY; } else { error_report("Invalid icount rr option: %s", rr); exit(1); } fname = qemu_opt_get(opts, "rrfile"); if (!fname) { error_report("File name not specified for replay"); exit(1); } replay_snapshot = g_strdup(qemu_opt_get(opts, "rrsnapshot")); replay_vmstate_register(); replay_enable(fname, mode); out: loc_pop(&loc); } void replay_start(void) { if (replay_mode == REPLAY_MODE_NONE) { return; } if (replay_blockers) { error_reportf_err(replay_blockers->data, "Record/replay: "); exit(1); } if (!use_icount) { error_report("Please enable icount to use record/replay"); exit(1); } /* Timer for snapshotting will be set up here. */ replay_enable_events(); } void replay_finish(void) { if (replay_mode == REPLAY_MODE_NONE) { return; } replay_save_instructions(); /* finalize the file */ if (replay_file) { if (replay_mode == REPLAY_MODE_RECORD) { /* write end event */ replay_put_event(EVENT_END); /* write header */ fseek(replay_file, 0, SEEK_SET); replay_put_dword(REPLAY_VERSION); } fclose(replay_file); replay_file = NULL; } if (replay_filename) { g_free(replay_filename); replay_filename = NULL; } g_free(replay_snapshot); replay_snapshot = NULL; replay_finish_events(); } void replay_add_blocker(Error *reason) { replay_blockers = g_slist_prepend(replay_blockers, reason); }
{ "language": "C++" }
#include <vector> #include <set> #include <cstdio> using namespace std; int main(){ int N,L; scanf("%d%d",&N,&L); vector<int>v(N); for(int i=0;i<N;i++)scanf("%d",&v[i]); multiset<int>se; for(int i=0;i<L-1;i++)se.insert(v[i]); for(int i=L-1;i<N;i++){ se.insert(v[i]); printf(i<N-1?"%d ":"%d\n",*se.begin()); se.erase(se.find(v[i-L+1])); } }
{ "language": "C++" }
// Copyright Hugh Perkins 2014 hughperkins at gmail // // 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/. #include <iostream> #include <stdexcept> #include <cstring> #include "EasyCL.h" #include "activate/ActivationBackward.h" #include "util/StatefulTimer.h" #include "activate/ActivationFunction.h" #include "activate/ActivationBackwardCpu.h" using namespace std; #undef VIRTUAL #define VIRTUAL #undef STATIC #define STATIC ActivationBackwardCpu::ActivationBackwardCpu(EasyCL *cl, int numPlanes, int inputSize, ActivationFunction const *fn) : ActivationBackward(cl, numPlanes, inputSize, fn) { } VIRTUAL void ActivationBackwardCpu::backward(int batchSize, float *outputs, float *gradOutput, float *gradInput) { int totalLinearSize = batchSize * numPlanes * inputSize * inputSize; for(int i = 0; i < totalLinearSize; i++) { // cout << "input=" << inputs[i] << " deriv=" << fn->calcDerivative(inputs[i]) // << " error=" << errors[i]; gradInput[i] = fn->calcDerivative(outputs[i]) * gradOutput[i]; cout << " gradInput=" << gradInput[i] << endl; } } VIRTUAL void ActivationBackwardCpu::backward(int batchSize, CLWrapper *outputWrapper, CLWrapper *gradOutputWrapper, CLWrapper *gradInputWrapper) { StatefulTimer::instance()->timeCheck("ActivationBackwardCpu::backward start"); outputWrapper->copyToHost(); gradOutputWrapper->copyToHost(); float *outputs = reinterpret_cast<float *>(outputWrapper->getHostArray()); float *gradOutput = reinterpret_cast<float *>(gradOutputWrapper->getHostArray()); float *gradInput = new float[ getInputNumElements(batchSize) ]; for(int i = 0; i < 4; i++) { cout << "i=" << i << " outputs=" << outputs[i] << " gradOutput=" << gradOutput[i] << endl; } backward(batchSize, outputs, gradOutput, gradInput); float *gradInputHostArray = reinterpret_cast<float *>(gradInputWrapper->getHostArray()); memcpy(gradInputHostArray, gradInput, sizeof(float) * getInputNumElements(batchSize) ); gradInputWrapper->copyToDevice(); for(int i = 0; i < 4; i++) { cout << "i=" << i << " gradInput=" << gradInput[i] << endl; } delete[] gradInput; StatefulTimer::instance()->timeCheck("ActivationBackwardCpu::backward end"); }
{ "language": "C++" }
// 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. #ifndef CHROME_BROWSER_UI_WEBUI_WEB_UI_TEST_HANDLER_H_ #define CHROME_BROWSER_UI_WEBUI_WEB_UI_TEST_HANDLER_H_ #include "base/compiler_specific.h" #include "base/macros.h" #include "base/strings/string16.h" #include "content/public/browser/web_ui_message_handler.h" namespace base { class ListValue; class Value; } namespace content { class RenderViewHost; } // This class registers test framework specific handlers on WebUI objects. class WebUITestHandler : public content::WebUIMessageHandler { public: WebUITestHandler(); // Sends a message through |preload_host| with the |js_text| to preload at the // appropriate time before the onload call is made. void PreloadJavaScript(const base::string16& js_text, content::RenderViewHost* preload_host); // Runs |js_text| in this object's WebUI frame. Does not wait for any result. void RunJavaScript(const base::string16& js_text); // Runs |js_text| in this object's WebUI frame. Waits for result, logging an // error message on failure. Returns test pass/fail. bool RunJavaScriptTestWithResult(const base::string16& js_text); // WebUIMessageHandler overrides. // Add test handlers to the current WebUI object. void RegisterMessages() override; private: // Receives testResult messages. void HandleTestResult(const base::ListValue* test_result); // Gets the callback that Javascript execution is complete. void JavaScriptComplete(const base::Value* result); // Runs a message loop until test finishes. Returns the result of the // test. bool WaitForResult(); // Received test pass/fail; bool test_done_; // Pass fail result of current test. bool test_succeeded_; // Test code finished trying to execute. This will be set to true when the // selected tab is done with this execution request whether it was able to // parse/execute the javascript or not. bool run_test_done_; // Test code was able to execute successfully. This is *NOT* the test // pass/fail. bool run_test_succeeded_; // Waiting for a test to finish. bool is_waiting_; DISALLOW_COPY_AND_ASSIGN(WebUITestHandler); }; #endif // CHROME_BROWSER_UI_WEBUI_WEB_UI_TEST_HANDLER_H_
{ "language": "C++" }
/* Boost interval/detail/c99sub_rounding_control.hpp file * * Copyright 2000 Jens Maurer * Copyright 2002 Hervé Brönnimann, Guillaume Melquiond, Sylvain Pion * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or * copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUNDING_CONTROL_HPP #define BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUNDING_CONTROL_HPP #include <boost/detail/fenv.hpp> // ISO C 99 rounding mode control namespace boost { namespace numeric { namespace interval_lib { namespace detail { extern "C" { double rint(double); } struct c99_rounding_control { typedef int rounding_mode; static void set_rounding_mode(rounding_mode mode) { fesetround(mode); } static void get_rounding_mode(rounding_mode &mode) { mode = fegetround(); } static void downward() { set_rounding_mode(FE_DOWNWARD); } static void upward() { set_rounding_mode(FE_UPWARD); } static void to_nearest() { set_rounding_mode(FE_TONEAREST); } static void toward_zero() { set_rounding_mode(FE_TOWARDZERO); } template<class T> static T to_int(const T& r) { return rint(r); } }; } // namespace detail } // namespace interval_lib } // namespace numeric } // namespace boost #endif // BOOST_NUMERIC_INTERVAL_DETAIL_C99SUB_ROUBDING_CONTROL_HPP
{ "language": "C++" }
/*============================================================================= Copyright (c) 2011 Thomas Heller Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) ==============================================================================*/ #ifndef BOOST_PHOENIX_CORE_V2_EVAL_HPP #define BOOST_PHOENIX_CORE_V2_EVAL_HPP #include <boost/phoenix/core/limits.hpp> #include <boost/phoenix/core/environment.hpp> #include <boost/phoenix/core/is_actor.hpp> #include <boost/phoenix/core/meta_grammar.hpp> #include <boost/phoenix/core/terminal_fwd.hpp> #include <boost/phoenix/support/vector.hpp> #include <boost/proto/transform/fold.hpp> #include <boost/proto/transform/lazy.hpp> namespace boost { namespace phoenix { struct v2_eval : proto::callable { template <typename Sig> struct result; template <typename This, typename Eval, typename Env> struct result<This(Eval, Env)> : Eval::template result<typename proto::detail::uncvref<Env>::type> {}; template <typename This, typename Eval, typename Env> struct result<This(Eval &, Env)> : Eval::template result<typename proto::detail::uncvref<Env>::type> {}; template <typename This, typename Eval, typename Env> struct result<This(Eval const &, Env)> : Eval::template result<typename proto::detail::uncvref<Env>::type> {}; template <typename Eval, typename Env> typename result<v2_eval(Eval const&, Env)>::type operator()(Eval const & e, Env const & env) const { return e.eval(env); } }; }} #endif
{ "language": "C++" }
// (C) Copyright 2002-2008, Fernando Luis Cacciola Carballal. // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // 21 Ago 2002 (Created) Fernando Cacciola // 24 Dec 2007 (Refactored and worked around various compiler bugs) Fernando Cacciola, Niels Dekker // 23 May 2008 (Fixed operator= const issue, added initialized_value) Niels Dekker, Fernando Cacciola // 21 Ago 2008 (Added swap) Niels Dekker, Fernando Cacciola // 20 Feb 2009 (Fixed logical const-ness issues) Niels Dekker, Fernando Cacciola // 03 Apr 2010 (Added initialized<T>, suggested by Jeffrey Hellrung, fixing #3472) Niels Dekker // 30 May 2010 (Made memset call conditional, fixing #3869) Niels Dekker // #ifndef BOOST_UTILITY_VALUE_INIT_21AGO2002_HPP #define BOOST_UTILITY_VALUE_INIT_21AGO2002_HPP // Note: The implementation of boost::value_initialized had to deal with the // fact that various compilers haven't fully implemented value-initialization. // The constructor of boost::value_initialized<T> works around these compiler // issues, by clearing the bytes of T, before constructing the T object it // contains. More details on these issues are at libs/utility/value_init.htm #include <boost/aligned_storage.hpp> #include <boost/config.hpp> // For BOOST_NO_COMPLETE_VALUE_INITIALIZATION. #include <boost/detail/workaround.hpp> #include <boost/static_assert.hpp> #include <boost/type_traits/cv_traits.hpp> #include <boost/type_traits/alignment_of.hpp> #include <boost/swap.hpp> #include <cstring> #include <new> #ifdef BOOST_MSVC #pragma warning(push) // It is safe to ignore the following warning from MSVC 7.1 or higher: // "warning C4351: new behavior: elements of array will be default initialized" #pragma warning(disable: 4351) // It is safe to ignore the following MSVC warning, which may pop up when T is // a const type: "warning C4512: assignment operator could not be generated". #pragma warning(disable: 4512) #endif #ifdef BOOST_NO_COMPLETE_VALUE_INITIALIZATION // Implementation detail: The macro BOOST_DETAIL_VALUE_INIT_WORKAROUND_SUGGESTED // suggests that a workaround should be applied, because of compiler issues // regarding value-initialization. #define BOOST_DETAIL_VALUE_INIT_WORKAROUND_SUGGESTED #endif // Implementation detail: The macro BOOST_DETAIL_VALUE_INIT_WORKAROUND // switches the value-initialization workaround either on or off. #ifndef BOOST_DETAIL_VALUE_INIT_WORKAROUND #ifdef BOOST_DETAIL_VALUE_INIT_WORKAROUND_SUGGESTED #define BOOST_DETAIL_VALUE_INIT_WORKAROUND 1 #else #define BOOST_DETAIL_VALUE_INIT_WORKAROUND 0 #endif #endif namespace boost { template<class T> class initialized { private : struct wrapper { #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592)) typename #endif remove_const<T>::type data; BOOST_GPU_ENABLED wrapper() : data() { } BOOST_GPU_ENABLED wrapper(T const & arg) : data(arg) { } }; mutable #if !BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x592)) typename #endif aligned_storage<sizeof(wrapper), alignment_of<wrapper>::value>::type x; BOOST_GPU_ENABLED wrapper * wrapper_address() const { return static_cast<wrapper *>( static_cast<void*>(&x)); } public : BOOST_GPU_ENABLED initialized() { #if BOOST_DETAIL_VALUE_INIT_WORKAROUND std::memset(&x, 0, sizeof(x)); #endif new (wrapper_address()) wrapper(); } BOOST_GPU_ENABLED initialized(initialized const & arg) { new (wrapper_address()) wrapper( static_cast<wrapper const &>(*(arg.wrapper_address()))); } BOOST_GPU_ENABLED explicit initialized(T const & arg) { new (wrapper_address()) wrapper(arg); } BOOST_GPU_ENABLED initialized & operator=(initialized const & arg) { // Assignment is only allowed when T is non-const. BOOST_STATIC_ASSERT( ! is_const<T>::value ); *wrapper_address() = static_cast<wrapper const &>(*(arg.wrapper_address())); return *this; } BOOST_GPU_ENABLED ~initialized() { wrapper_address()->wrapper::~wrapper(); } BOOST_GPU_ENABLED T const & data() const { return wrapper_address()->data; } BOOST_GPU_ENABLED T& data() { return wrapper_address()->data; } BOOST_GPU_ENABLED void swap(initialized & arg) { ::boost::swap( this->data(), arg.data() ); } BOOST_GPU_ENABLED operator T const &() const { return wrapper_address()->data; } BOOST_GPU_ENABLED operator T&() { return wrapper_address()->data; } } ; template<class T> BOOST_GPU_ENABLED T const& get ( initialized<T> const& x ) { return x.data() ; } template<class T> BOOST_GPU_ENABLED T& get ( initialized<T>& x ) { return x.data() ; } template<class T> BOOST_GPU_ENABLED void swap ( initialized<T> & lhs, initialized<T> & rhs ) { lhs.swap(rhs) ; } template<class T> class value_initialized { private : // initialized<T> does value-initialization by default. initialized<T> m_data; public : BOOST_GPU_ENABLED value_initialized() : m_data() { } BOOST_GPU_ENABLED T const & data() const { return m_data.data(); } BOOST_GPU_ENABLED T& data() { return m_data.data(); } BOOST_GPU_ENABLED void swap(value_initialized & arg) { m_data.swap(arg.m_data); } BOOST_GPU_ENABLED operator T const &() const { return m_data; } BOOST_GPU_ENABLED operator T&() { return m_data; } } ; template<class T> BOOST_GPU_ENABLED T const& get ( value_initialized<T> const& x ) { return x.data() ; } template<class T> BOOST_GPU_ENABLED T& get ( value_initialized<T>& x ) { return x.data() ; } template<class T> BOOST_GPU_ENABLED void swap ( value_initialized<T> & lhs, value_initialized<T> & rhs ) { lhs.swap(rhs) ; } class initialized_value_t { public : template <class T> BOOST_GPU_ENABLED operator T() const { return initialized<T>().data(); } }; initialized_value_t const initialized_value = {} ; } // namespace boost #ifdef BOOST_MSVC #pragma warning(pop) #endif #endif
{ "language": "C++" }
/* This file is part of LIA_RAL which is a set of software based on ALIZE toolkit for speaker recognition. ALIZE toolkit is required to use LIA_RAL. LIA_RAL project is a development project was initiated by the computer science laboratory of Avignon / France (Laboratoire Informatique d'Avignon - LIA) [http://lia.univ-avignon.fr <http://lia.univ-avignon.fr/>]. Then it was supported by two national projects of the French Research Ministry: - TECHNOLANGUE program [http://www.technolangue.net] - MISTRAL program [http://mistral.univ-avignon.fr] LIA_RAL is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version. LIA_RAL 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 LIA_RAL. If not, see [http://www.gnu.org/licenses/]. The LIA team as well as the LIA_RAL project team wants to highlight the limits of voice authentication in a forensic context. The "Person Authentification by Voice: A Need of Caution" paper proposes a good overview of this point (cf. "Person Authentification by Voice: A Need of Caution", Bonastre J.F., Bimbot F., Boe L.J., Campbell J.P., Douglas D.A., Magrin- chagnolleau I., Eurospeech 2003, Genova]. The conclusion of the paper of the paper is proposed bellow: [Currently, it is not possible to completely determine whether the similarity between two recordings is due to the speaker or to other factors, especially when: (a) the speaker does not cooperate, (b) there is no control over recording equipment, (c) recording conditions are not known, (d) one does not know whether the voice was disguised and, to a lesser extent, (e) the linguistic content of the message is not controlled. Caution and judgment must be exercised when applying speaker recognition techniques, whether human or automatic, to account for these uncontrolled factors. Under more constrained or calibrated situations, or as an aid for investigative purposes, judicious application of these techniques may be suitable, provided they are not considered as infallible. At the present time, there is no scientific process that enables one to uniquely characterize a persones voice or to identify with absolute certainty an individual from his or her voice.] Copyright (C) 2004-2010 Laboratoire d'informatique d'Avignon [http://lia.univ-avignon.fr] LIA_RAL admin [alize@univ-avignon.fr] Jean-Francois Bonastre [jean-francois.bonastre@univ-avignon.fr] */ #include <iostream> #include "SequenceExtractor.h" int main(int argc, char* argv[]) { try { // String inputTreeFilename=config.getParam("decoderFilename"); // The complete filename for the decoder tree // String outputFilename=config.getParam("outputFilename"); // The complete output filename // String inputFilename=config.getParam("inputFilename"); // The complete input filename ConfigChecker cc; cc.addStringParam("config", false, true, "default config filename"); cc.addStringParam("decoderFilename",true,true,"filename of the decoder tree"); cc.addStringParam("inputFilename",true,true,"filename of the input symbol stream"); cc.addStringParam("outputFilename",true,true,"filename of the output symbol file"); cc.addStringParam("labelFilename",false,true,"if segment processing is needed, name of the label file"); cc.addStringParam("labelSelectedFrames",false,true,"if segment processsing is needed, label of the selected segments"); cc.addFloatParam("frameLength",false,true,"If segment processing is required, it gives the length in s of an input symbol"); cc.addBooleanParam("overlapMode",false,true,"if set to true (default=false), find overlap sequences. i.e decode one sequance by input symbol"); cc.addStringParam("ngramOutputFilename",false,true,"If set, computes the ngram on the output seq and save it in this file"); cc.addIntegerParam("ngramOutputOrder",false,true,"If output ngram is needed, gives the max order of the ngram"); CmdLine cmdLine(argc, argv); if (cmdLine.displayHelpRequired()) { cout <<"SequenceDecoder.exe"<<endl<<"This program uses in input a decoder tree and an input stream" <<endl<<"It decodes the input stream and outputs the finded sequences"<<endl<<cc.getParamList()<<endl; cout <<"HelpRequired"<<endl; return 0; } if (cmdLine.displayVersionRequired()) { cout <<"Version Beta "<<endl; } Config tmp; cmdLine.copyIntoConfig(tmp); Config config; if (tmp.existsParam("config")) config.load(tmp.getParam("config")); cmdLine.copyIntoConfig(config); cc.check(config); debug=config.getParam_debug(); if (config.existsParam("verbose")) verbose=config.getParam("verbose").toBool(); else verbose=false; sequenceDecoder(config); } catch (alize::Exception& e) { cout << e.toString() << endl; } return 0; }
{ "language": "C++" }
/** Copyright 2017 Google Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "ion/math/matrixutils.h" #include "ion/base/logging.h" #include "ion/math/utils.h" #include "ion/math/vectorutils.h" namespace ion { namespace math { namespace { //----------------------------------------------------------------------------- // Internal Cofactor helper functions. Each of these computes the signed // cofactor element for a row and column of a matrix of a certain size. // ----------------------------------------------------------------------------- // Returns true if the cofactor for a given row and column should be negated. static bool IsCofactorNegated(int row, int col) { // Negated iff (row + col) is odd. return ((row + col) & 1) != 0; } template <typename T> static T CofactorElement3(const Matrix<3, T>& m, int row, int col) { static const int index[3][2] = { {1, 2}, {0, 2}, {0, 1} }; const int i0 = index[row][0]; const int i1 = index[row][1]; const int j0 = index[col][0]; const int j1 = index[col][1]; const T cofactor = m(i0, j0) * m(i1, j1) - m(i0, j1) * m(i1, j0); return IsCofactorNegated(row, col) ? -cofactor : cofactor; } template <typename T> static T CofactorElement4(const Matrix<4, T>& m, int row, int col) { // The cofactor of element (row,col) is the determinant of the 3x3 submatrix // formed by removing that row and column. static const int index[4][3] = { {1, 2, 3}, {0, 2, 3}, {0, 1, 3}, {0, 1, 2} }; const int i0 = index[row][0]; const int i1 = index[row][1]; const int i2 = index[row][2]; const int j0 = index[col][0]; const int j1 = index[col][1]; const int j2 = index[col][2]; const T c0 = m(i0, j0) * (m(i1, j1) * m(i2, j2) - m(i1, j2) * m(i2, j1)); const T c1 = -m(i0, j1) * (m(i1, j0) * m(i2, j2) - m(i1, j2) * m(i2, j0)); const T c2 = m(i0, j2) * (m(i1, j0) * m(i2, j1) - m(i1, j1) * m(i2, j0)); const T cofactor = c0 + c1 + c2; return IsCofactorNegated(row, col) ? -cofactor : cofactor; } //----------------------------------------------------------------------------- // Internal Determinant helper functions. Each of these computes the // determinant of a matrix of a certain size. // ----------------------------------------------------------------------------- template <typename T> static T Determinant2(const Matrix<2, T>& m) { return m(0, 0) * m(1, 1) - m(0, 1) * m(1, 0); } template <typename T> static T Determinant3(const Matrix<3, T>& m) { return (m(0, 0) * CofactorElement3(m, 0, 0) + m(0, 1) * CofactorElement3(m, 0, 1) + m(0, 2) * CofactorElement3(m, 0, 2)); } template <typename T> static T Determinant4(const Matrix<4, T>& m) { return (m(0, 0) * CofactorElement4(m, 0, 0) + m(0, 1) * CofactorElement4(m, 0, 1) + m(0, 2) * CofactorElement4(m, 0, 2) + m(0, 3) * CofactorElement4(m, 0, 3)); } //----------------------------------------------------------------------------- // Internal CofactorMatrix helper functions. Each of these computes the // cofactor matrix for a matrix of a certain size. // ----------------------------------------------------------------------------- template <typename T> Matrix<2, T> CofactorMatrix2(const Matrix<2, T>& m) { return Matrix<2, T>(m(1, 1), -m(1, 0), -m(0, 1), m(0, 0)); } template <typename T> Matrix<3, T> CofactorMatrix3(const Matrix<3, T>& m) { Matrix<3, T> result; for (int row = 0; row < 3; ++row) { for (int col = 0; col < 3; ++col) result(row, col) = CofactorElement3(m, row, col); } return result; } template <typename T> Matrix<4, T> CofactorMatrix4(const Matrix<4, T>& m) { Matrix<4, T> result; for (int row = 0; row < 4; ++row) { for (int col = 0; col < 4; ++col) result(row, col) = CofactorElement4(m, row, col); } return result; } //----------------------------------------------------------------------------- // Internal Adjugate helper functions. Each of these computes the adjugate // matrix for a matrix of a certain size. // ----------------------------------------------------------------------------- template <typename T> Matrix<2, T> Adjugate2(const Matrix<2, T>& m, T* determinant) { const T m00 = m(0, 0); const T m01 = m(0, 1); const T m10 = m(1, 0); const T m11 = m(1, 1); if (determinant) *determinant = m00 * m11 - m01 * m10; return Matrix<2, T>(m11, -m01, -m10, m00); } template <typename T> Matrix<3, T> Adjugate3(const Matrix<3, T>& m, T* determinant) { const Matrix<3, T> cofactor_matrix = CofactorMatrix3(m); if (determinant) { *determinant = m(0, 0) * cofactor_matrix(0, 0) + m(0, 1) * cofactor_matrix(0, 1) + m(0, 2) * cofactor_matrix(0, 2); } return Transpose(cofactor_matrix); } template <typename T> Matrix<4, T> Adjugate4(const Matrix<4, T>& m, T* determinant) { // For 4x4 do not compute the adjugate as the transpose of the cofactor // matrix, because this results in extra work. Several calculations can be // shared across the sub-determinants. // // This approach is explained in David Eberly's Geometric Tools book, // excerpted here: // http://www.geometrictools.com/Documentation/LaplaceExpansionTheorem.pdf const T s0 = m(0, 0) * m(1, 1) - m(1, 0) * m(0, 1); const T s1 = m(0, 0) * m(1, 2) - m(1, 0) * m(0, 2); const T s2 = m(0, 0) * m(1, 3) - m(1, 0) * m(0, 3); const T s3 = m(0, 1) * m(1, 2) - m(1, 1) * m(0, 2); const T s4 = m(0, 1) * m(1, 3) - m(1, 1) * m(0, 3); const T s5 = m(0, 2) * m(1, 3) - m(1, 2) * m(0, 3); const T c0 = m(2, 0) * m(3, 1) - m(3, 0) * m(2, 1); const T c1 = m(2, 0) * m(3, 2) - m(3, 0) * m(2, 2); const T c2 = m(2, 0) * m(3, 3) - m(3, 0) * m(2, 3); const T c3 = m(2, 1) * m(3, 2) - m(3, 1) * m(2, 2); const T c4 = m(2, 1) * m(3, 3) - m(3, 1) * m(2, 3); const T c5 = m(2, 2) * m(3, 3) - m(3, 2) * m(2, 3); if (determinant) *determinant = s0 * c5 - s1 * c4 + s2 * c3 + s3 * c2 - s4 * c1 + s5 * c0; return Matrix<4, T>( m(1, 1) * c5 - m(1, 2) * c4 + m(1, 3) * c3, -m(0, 1) * c5 + m(0, 2) * c4 - m(0, 3) * c3, m(3, 1) * s5 - m(3, 2) * s4 + m(3, 3) * s3, -m(2, 1) * s5 + m(2, 2) * s4 - m(2, 3) * s3, -m(1, 0) * c5 + m(1, 2) * c2 - m(1, 3) * c1, m(0, 0) * c5 - m(0, 2) * c2 + m(0, 3) * c1, -m(3, 0) * s5 + m(3, 2) * s2 - m(3, 3) * s1, m(2, 0) * s5 - m(2, 2) * s2 + m(2, 3) * s1, m(1, 0) * c4 - m(1, 1) * c2 + m(1, 3) * c0, -m(0, 0) * c4 + m(0, 1) * c2 - m(0, 3) * c0, m(3, 0) * s4 - m(3, 1) * s2 + m(3, 3) * s0, -m(2, 0) * s4 + m(2, 1) * s2 - m(2, 3) * s0, -m(1, 0) * c3 + m(1, 1) * c1 - m(1, 2) * c0, m(0, 0) * c3 - m(0, 1) * c1 + m(0, 2) * c0, -m(3, 0) * s3 + m(3, 1) * s1 - m(3, 2) * s0, m(2, 0) * s3 - m(2, 1) * s1 + m(2, 2) * s0); } } // anonymous namespace //----------------------------------------------------------------------------- // Public functions. // // Partial specialization of template functions is not allowed in C++, so these // functions are implemented using fully-specialized functions that invoke // helper functions that operate on matrices of a specific size. // ----------------------------------------------------------------------------- // // The unspecialized versions should never be called. // template <int Dimension, typename T> T Determinant(const Matrix<Dimension, T>& m) { DCHECK(false) << "Unspecialized Matrix Determinant function used."; } template <int Dimension, typename T> Matrix<Dimension, T> CofactorMatrix(const Matrix<Dimension, T>& m) { DCHECK(false) << "Unspecialized Matrix Cofactor function used."; } template <int Dimension, typename T> Matrix<Dimension, T> AdjugateWithDeterminant( const Matrix<Dimension, T>& m, T* determinant) { DCHECK(false) << "Unspecialized Matrix Adjugate function used."; } template <int Dimension, typename T> Matrix<Dimension, T> InverseWithDeterminant( const Matrix<Dimension, T>& m, T* determinant) { // The inverse is the adjugate divided by the determinant. T det; Matrix<Dimension, T> adjugate = AdjugateWithDeterminant(m, &det); if (determinant) *determinant = det; if (det == static_cast<T>(0)) return Matrix<Dimension, T>::Zero(); else return adjugate * (static_cast<T>(1) / det); } template <int Dimension, typename T> bool MatrixAlmostOrthogonal(const Matrix<Dimension, T>& m, T tolerance) { for (int col1 = 0; col1 < Dimension; ++col1) { Vector<Dimension, T> column = Column(m, col1); // Test for pairwise orthogonality of column vectors. for (int col2 = col1 + 1; col2 < Dimension; ++col2) if (Dot(column, Column(m, col2)) > tolerance) return false; // Test for unit length. if (Abs(LengthSquared(column) - static_cast<T>(1)) > tolerance) return false; } return true; } // // Fully specialize or instantiate all of these for all supported types. // #define ION_SPECIALIZE_MATRIX_FUNCS(dim, scalar) \ template <> scalar ION_API Determinant(const Matrix<dim, scalar>& m) { \ return Determinant ## dim(m); \ } \ template <> Matrix<dim, scalar> ION_API CofactorMatrix( \ const Matrix<dim, scalar>& m) { \ return CofactorMatrix ## dim(m); \ } \ template <> Matrix<dim, scalar> ION_API AdjugateWithDeterminant( \ const Matrix<dim, scalar>& m, scalar* determinant) { \ return Adjugate ## dim(m, determinant); \ } \ \ /* Explicit instantiations. */ \ template Matrix<dim, scalar> ION_API InverseWithDeterminant( \ const Matrix<dim, scalar>& m, scalar* determinant); \ template bool ION_API MatrixAlmostOrthogonal( \ const Matrix<dim, scalar>& m, scalar tolerance) ION_SPECIALIZE_MATRIX_FUNCS(2, float); ION_SPECIALIZE_MATRIX_FUNCS(2, double); ION_SPECIALIZE_MATRIX_FUNCS(3, float); ION_SPECIALIZE_MATRIX_FUNCS(3, double); ION_SPECIALIZE_MATRIX_FUNCS(4, float); ION_SPECIALIZE_MATRIX_FUNCS(4, double); #undef ION_SPECIALIZE_MATRIX_FUNCS } // namespace math } // namespace ion
{ "language": "C++" }
/*============================================================================= Copyright (c) 2011-2019 Bolero MURAKAMI https://github.com/bolero-MURAKAMI/Sprout Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #ifndef SPROUT_LIBS_ALGORITHM_TEST_NONE_OF_EQUAL_CPP #define SPROUT_LIBS_ALGORITHM_TEST_NONE_OF_EQUAL_CPP #include <sprout/algorithm/none_of_equal.hpp> #include <sprout/array.hpp> #include <sprout/container.hpp> #include <testspr/tools.hpp> namespace testspr { static void algorithm_none_of_equal_test() { using namespace sprout; { SPROUT_STATIC_CONSTEXPR auto arr1 = array<int, 10>{{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}}; { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( sprout::begin(arr1), sprout::end(arr1), 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( sprout::begin(arr1), sprout::end(arr1), 11 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( sprout::begin(arr1), sprout::begin(arr1) + 5, 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( sprout::begin(arr1), sprout::begin(arr1) + 5, 11 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::end(arr1)), 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::end(arr1)), 11 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::begin(arr1) + 5), 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_input(sprout::begin(arr1)), testspr::reduce_input(sprout::begin(arr1) + 5), 11 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::end(arr1)), 10 ); TESTSPR_BOTH_ASSERT(!result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::end(arr1)), 11 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::begin(arr1) + 5), 10 ); TESTSPR_BOTH_ASSERT(result); } { SPROUT_STATIC_CONSTEXPR auto result = sprout::none_of_equal( testspr::reduce_random_access(sprout::begin(arr1)), testspr::reduce_random_access(sprout::begin(arr1) + 5), 11 ); TESTSPR_BOTH_ASSERT(result); } } } } // namespace testspr #ifndef TESTSPR_CPP_INCLUDE # define TESTSPR_TEST_FUNCTION testspr::algorithm_none_of_equal_test # include <testspr/include_main.hpp> #endif #endif // #ifndef SPROUT_LIBS_ALGORITHM_TEST_NONE_OF_EQUAL_CPP
{ "language": "C++" }
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // UNSUPPORTED: c++98, c++03, c++11, c++14, c++17 // <span> // tuple_element<I, span<T, N> >::type #include <span> #include "test_macros.h" int main(int, char**) { // No tuple_element for dynamic spans using T1 = typename std::tuple_element< 0, std::span<int, 0>>::type; // expected-error-re@span:* {{static_assert failed{{( due to requirement '.*')?}} "Index out of bounds in std::tuple_element<> (std::span)"}} using T2 = typename std::tuple_element< 5, std::span<int, 5>>::type; // expected-error-re@span:* {{static_assert failed{{( due to requirement '.*')?}} "Index out of bounds in std::tuple_element<> (std::span)"}} using T3 = typename std::tuple_element<20, std::span<int, 10>>::type; // expected-error-re@span:* {{static_assert failed{{( due to requirement '.*')?}} "Index out of bounds in std::tuple_element<> (std::span)"}} return 0; }
{ "language": "C++" }
/* Copyright 2019 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #ifndef TENSORFLOW_CORE_PROFILER_CONVERT_OP_METRICS_TO_RECORD_H_ #define TENSORFLOW_CORE_PROFILER_CONVERT_OP_METRICS_TO_RECORD_H_ #include <vector> #include "tensorflow/core/profiler/protobuf/op_metrics.pb.h" #include "tensorflow/core/profiler/utils/math_utils.h" #include "tensorflow/core/profiler/utils/time_utils.h" namespace tensorflow { namespace profiler { std::vector<const OpMetrics*> SortedOpMetricsDb(const OpMetricsDb& metrics_db, int max_records = -1); template <typename Record> inline void SetExecutionTimes(const OpMetrics& metrics, Record* record) { record->set_occurrences(metrics.occurrences()); record->set_total_time_in_us(PicosToMicros(metrics.time_ps())); record->set_avg_time_in_us( SafeDivide(record->total_time_in_us(), metrics.occurrences())); record->set_total_self_time_in_us(PicosToMicros(metrics.self_time_ps())); record->set_avg_self_time_in_us( SafeDivide(record->total_self_time_in_us(), metrics.occurrences())); } template <typename Record> inline void SetTpuUnitFractions(const OpMetrics& metrics, Record* record) { record->set_dma_stall_fraction( SafeDivide(metrics.dma_stall_ps(), metrics.time_ps())); } template <typename Record> inline void SetRankAndTimeFractions(double total_time_us, const Record& prev_record, Record* record) { record->set_rank(prev_record.rank() + 1); record->set_total_self_time_as_fraction( SafeDivide(record->total_self_time_in_us(), total_time_us)); record->set_cumulative_total_self_time_as_fraction( prev_record.cumulative_total_self_time_as_fraction() + record->total_self_time_as_fraction()); } template <typename Record> inline void SetRankAndDeviceTimeFractions(double total_time_us, const Record& prev_record, Record* record) { record->set_rank(prev_record.rank() + 1); record->set_device_total_self_time_as_fraction( SafeDivide(record->total_self_time_in_us(), total_time_us)); record->set_device_cumulative_total_self_time_as_fraction( prev_record.device_cumulative_total_self_time_as_fraction() + record->device_total_self_time_as_fraction()); } template <typename Record> inline void SetRankAndHostTimeFractions(double total_time_us, const Record& prev_record, Record* record) { record->set_rank(prev_record.rank() + 1); record->set_host_total_self_time_as_fraction( SafeDivide(record->total_self_time_in_us(), total_time_us)); record->set_host_cumulative_total_self_time_as_fraction( prev_record.host_cumulative_total_self_time_as_fraction() + record->host_total_self_time_as_fraction()); } template <typename Record> inline void SetRooflineMetrics(const OpMetrics& metrics, double ridge_point_operational_intensity, Record* record) { using ::tensorflow::profiler::PicosToNanos; record->set_measured_flop_rate( SafeDivide(metrics.flops(), PicosToNanos(metrics.time_ps()))); record->set_measured_memory_bw( SafeDivide(metrics.bytes_accessed(), PicosToNanos(metrics.time_ps()))); record->set_operational_intensity( SafeDivide(metrics.flops(), metrics.bytes_accessed())); record->set_bound_by((metrics.bytes_accessed() != 0) ? ((record->operational_intensity() >= ridge_point_operational_intensity) ? "Compute" : "Memory") : ((metrics.flops() != 0) ? "Compute" : "Unknown")); } } // namespace profiler } // namespace tensorflow #endif // TENSORFLOW_CORE_PROFILER_CONVERT_OP_METRICS_TO_RECORD_H_
{ "language": "C++" }
/* * Copyright 2017-2020 Leonid Yuriev <leo@yuriev.ru> * and other libmdbx authors: please see AUTHORS file. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted only as authorized by the OpenLDAP * Public License. * * A copy of this license is available in the file LICENSE in the * top-level directory of the distribution or, alternatively, at * <http://www.OpenLDAP.org/license.html>. */ #include "test.h" bool testcase_append::run() { int err = db_open__begin__table_create_open_clean(dbi); if (unlikely(err != MDBX_SUCCESS)) { log_notice("append: bailout-prepare due '%s'", mdbx_strerror(err)); return true; } keyvalue_maker.setup(config.params, config.actor_id, 0 /* thread_number */); /* LY: тест наполнения таблиц в append-режиме, * при котором записи добавляются строго в конец (в порядке сортировки) */ const unsigned flags = (config.params.table_flags & MDBX_DUPSORT) ? MDBX_APPEND | MDBX_APPENDDUP : MDBX_APPEND; keyvalue_maker.make_ordered(); key = keygen::alloc(config.params.keylen_max); data = keygen::alloc(config.params.datalen_max); keygen::buffer last_key = keygen::alloc(config.params.keylen_max); keygen::buffer last_data = keygen::alloc(config.params.datalen_max); last_key->value.iov_base = last_key->bytes; last_key->value.iov_len = 0; last_data->value.iov_base = last_data->bytes; last_data->value.iov_len = 0; simple_checksum inserted_checksum; uint64_t inserted_number = 0; uint64_t serial_count = 0; unsigned txn_nops = 0; uint64_t commited_inserted_number = inserted_number; simple_checksum commited_inserted_checksum = inserted_checksum; while (should_continue()) { const keygen::serial_t serial = serial_count; if (!keyvalue_maker.increment(serial_count, 1)) { // дошли до границы пространства ключей break; } log_trace("append: append-a %" PRIu64, serial); generate_pair(serial); int cmp = inserted_number ? mdbx_cmp(txn_guard.get(), dbi, &key->value, &last_key->value) : 1; if (cmp == 0 && (config.params.table_flags & MDBX_DUPSORT)) cmp = mdbx_dcmp(txn_guard.get(), dbi, &data->value, &last_data->value); err = mdbx_put(txn_guard.get(), dbi, &key->value, &data->value, flags); if (err == MDBX_MAP_FULL && config.params.ignore_dbfull) { log_notice("append: bailout-insert due '%s'", mdbx_strerror(err)); txn_end(true); inserted_number = commited_inserted_number; inserted_checksum = commited_inserted_checksum; break; } if (cmp > 0) { if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_put(appenda-a)", err); memcpy(last_key->value.iov_base, key->value.iov_base, last_key->value.iov_len = key->value.iov_len); memcpy(last_data->value.iov_base, data->value.iov_base, last_data->value.iov_len = data->value.iov_len); ++inserted_number; inserted_checksum.push((uint32_t)inserted_number, key->value); inserted_checksum.push(10639, data->value); } else { if (unlikely(err != MDBX_EKEYMISMATCH)) failure_perror("mdbx_put(appenda-a) != MDBX_EKEYMISMATCH", err); } if (++txn_nops >= config.params.batch_write) { err = breakable_restart(); if (unlikely(err != MDBX_SUCCESS)) { log_notice("append: bailout-commit due '%s'", mdbx_strerror(err)); inserted_number = commited_inserted_number; inserted_checksum = commited_inserted_checksum; break; } commited_inserted_number = inserted_number; commited_inserted_checksum = inserted_checksum; txn_nops = 0; } report(1); } if (txn_guard) { err = breakable_commit(); if (unlikely(err != MDBX_SUCCESS)) { log_notice("append: bailout-commit due '%s'", mdbx_strerror(err)); inserted_number = commited_inserted_number; inserted_checksum = commited_inserted_checksum; } } //---------------------------------------------------------------------------- txn_begin(true); cursor_open(dbi); MDBX_val check_key, check_data; err = mdbx_cursor_get(cursor_guard.get(), &check_key, &check_data, MDBX_FIRST); if (likely(inserted_number)) { if (unlikely(err != MDBX_SUCCESS)) failure_perror("mdbx_cursor_get(MDBX_FIRST)", err); } simple_checksum read_checksum; uint64_t read_count = 0; while (err == MDBX_SUCCESS) { ++read_count; read_checksum.push((uint32_t)read_count, check_key); read_checksum.push(10639, check_data); err = mdbx_cursor_get(cursor_guard.get(), &check_key, &check_data, MDBX_NEXT); } if (unlikely(err != MDBX_NOTFOUND)) failure_perror("mdbx_cursor_get(MDBX_NEXT) != EOF", err); if (unlikely(read_count != inserted_number)) failure("read_count(%" PRIu64 ") != inserted_number(%" PRIu64 ")", read_count, inserted_number); if (unlikely(read_checksum.value != inserted_checksum.value)) failure("read_checksum(0x%016" PRIu64 ") " "!= inserted_checksum(0x%016" PRIu64 ")", read_checksum.value, inserted_checksum.value); cursor_close(); txn_end(true); //---------------------------------------------------------------------------- if (dbi) { if (config.params.drop_table && !mode_readonly()) { txn_begin(false); db_table_drop(dbi); err = breakable_commit(); if (unlikely(err != MDBX_SUCCESS)) { log_notice("append: bailout-clean due '%s'", mdbx_strerror(err)); return true; } } else db_table_close(dbi); } return true; }
{ "language": "C++" }
// This is mul/mbl/tests/test_stochastic_data_collector.cxx #include <iostream> #include <string> #include "testlib/testlib_test.h" //: // \file // \author Ian Scott // \brief test vpdfl_pc_gaussian, building, sampling, saving etc. #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif #include "vpl/vpl.h" // vpl_unlink() #include "vsl/vsl_binary_loader.h" #include <vnl/io/vnl_io_vector.h> #include "vul/vul_printf.h" #include <mbl/mbl_stochastic_data_collector.h> #ifndef LEAVE_FILES_BEHIND #define LEAVE_FILES_BEHIND 0 #endif //======================================================================= void configure() { vsl_add_to_binary_loader(mbl_stochastic_data_collector<vnl_vector<double> >()); } //======================================================================= //: The main control program void test_stochastic_data_collector() { std::cout << "***************************************\n" << " Testing mbl_stochastic_data_collector\n" << "***************************************\n"; configure(); mbl_stochastic_data_collector<vnl_vector<double> > collector(100); collector.reseed(14545); std::cout << "===========Generate data\n"; std::vector<unsigned> hist(10, 0u); constexpr int n_expts = 50; for (int i=0;i<n_expts;++i) { vnl_vector<double> v(1); collector.clear(); for (v(0) = 0.0; v(0) < 5000.0; v(0) += 1.0) { if (collector.store_next()) collector.force_record(v); } // collector.record(v); mbl_data_wrapper<vnl_vector<double> > &data = collector.data_wrapper(); data.reset(); do { v = data.current(); hist[((int)(v(0))) / 500] ++; } while (data.next()); } std::cout << "Histogram output, over " << n_expts << "experiments\n"; for (int i=0; i < 10; i++) vul_printf(std::cout, "From %4d to %4d there were on average %4f items stored.\n", i * 500, i*500 + 499, ((double)hist[i])/((double)n_expts)) ; unsigned correct_hist[] = {501, 543, 499, 495, 461, 539, 490, 515, 460, 497}; TEST("Found correct values", vnl_c_vector<unsigned>::euclid_dist_sq(&hist[0], correct_hist, 10), 0); std::cout << "=========Testing IO\n"; mbl_stochastic_data_collector<vnl_vector<double> > collector2; mbl_data_collector_base *collector3=nullptr; std::string path = "test_stochastic_data_collector.bvl.tmp"; std::cout<<"Saving : "<<collector<<'\n'; vsl_b_ofstream bfs_out(path); TEST(("Opened " + path + " for writing").c_str(), (!bfs_out ), false); vsl_b_write(bfs_out,collector); vsl_b_write(bfs_out,(mbl_data_collector_base*)&collector); bfs_out.close(); vsl_b_ifstream bfs_in(path); TEST(("Opened " + path + " for reading").c_str(), (!bfs_in ), false); vsl_b_read(bfs_in,collector2); vsl_b_read(bfs_in,collector3); TEST("Finished reading file successfully", (!bfs_in), false); bfs_in.close(); #if !LEAVE_FILES_BEHIND vpl_unlink(path.c_str()); #endif std::cout << "Loaded : " << collector2 << '\n'; TEST("Loaded collector size = saved collector size", collector.data_wrapper().size(), collector2.data_wrapper().size()); mbl_data_wrapper<vnl_vector<double> > &w1 = collector.data_wrapper(); mbl_data_wrapper<vnl_vector<double> > &w2 = collector2.data_wrapper(); w1.reset(); w2.reset(); bool test_res = true; do { if (w1.current() != w2.current()) test_res = false; w1.next(); } while (w2.next()); TEST("Loaded collector = saved collector", test_res, true); std::cout << "Loaded by pointer: "<<collector3<<'\n'; delete collector3; vsl_delete_all_loaders(); } TESTMAIN(test_stochastic_data_collector);
{ "language": "C++" }
// ============================================================================= // PROJECT CHRONO - http://projectchrono.org // // Copyright (c) 2014 projectchrono.org // All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found // in the LICENSE file at the top level of the distribution and at // http://projectchrono.org/license-chrono.txt. // // ============================================================================= // Authors: Radu Serban // ============================================================================= #ifndef CH_LINK_ROTSPRING_CB_H #define CH_LINK_ROTSPRING_CB_H #include "chrono/physics/ChLinkMarkers.h" namespace chrono { /// Class for rotational spring-damper elements with the torque specified through a callback object. /// The torque is applied in the current direction of the relative axis of rotation. /// While a rotational spring-damper can be associated with any pair of bodies in the system, it is /// typically used in cases where the mechanism kinematics are such that the two bodies have a single /// relative rotational degree of freedom (e.g, between two bodies connected through a revolute, /// cylindrical, or screw joint). class ChApi ChLinkRotSpringCB : public ChLinkMarkers { public: ChLinkRotSpringCB(); ChLinkRotSpringCB(const ChLinkRotSpringCB& other); virtual ~ChLinkRotSpringCB() {} /// "Virtual" copy constructor (covariant return type). virtual ChLinkRotSpringCB* Clone() const override { return new ChLinkRotSpringCB(*this); } /// Get the current rotation angle about the relative rotation axis. double GetRotSpringAngle() const { return relAngle; } /// Get the current relative axis of rotation. const ChVector<>& GetRotSpringAxis() const { return relAxis; } /// Get the current relative angular speed about the common rotation axis. double GetRotSpringSpeed() const { return Vdot(relWvel, relAxis); } /// Get the current generated torque. double GetRotSpringTorque() const { return m_torque; } /// Class to be used as a callback interface for calculating the general spring-damper torque. /// A derived class must implement the virtual operator(). class ChApi TorqueFunctor { public: virtual ~TorqueFunctor() {} /// Calculate and return the general spring-damper torque at the specified configuration. virtual double operator()(double time, ///< current time double angle, ///< relative angle of rotation double vel, ///< relative angular speed ChLinkRotSpringCB* link ///< back-pointer to associated link ) = 0; }; /// Specify the callback object for calculating the torque. void RegisterTorqueFunctor(std::shared_ptr<TorqueFunctor> functor) { m_torque_fun = functor; } /// Method to allow serialization of transient data to archives. virtual void ArchiveOUT(ChArchiveOut& marchive) override; /// Method to allow deserialization of transient data from archives. virtual void ArchiveIN(ChArchiveIn& marchive) override; protected: /// Include the rotational spring-damper custom torque. virtual void UpdateForces(double time) override; std::shared_ptr<TorqueFunctor> m_torque_fun; ///< functor for torque calculation double m_torque; ///< resulting torque along relative axis of rotation }; CH_CLASS_VERSION(ChLinkRotSpringCB, 0) } // end namespace chrono #endif
{ "language": "C++" }
//! \example tutorial-autothreshold.cpp #include <cstdlib> #include <iostream> #include <visp3/core/vpImage.h> #include <visp3/gui/vpDisplayGDI.h> #include <visp3/gui/vpDisplayOpenCV.h> #include <visp3/gui/vpDisplayX.h> #include <visp3/io/vpImageIo.h> #if defined(VISP_HAVE_MODULE_IMGPROC) //! [Include] #include <visp3/imgproc/vpImgproc.h> //! [Include] #endif int main(int argc, const char **argv) { //! [Macro defined] #if defined(VISP_HAVE_MODULE_IMGPROC) && (defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV)) //! [Macro defined] //! std::string input_filename = "grid36-03.pgm"; for (int i = 1; i < argc; i++) { if (std::string(argv[i]) == "--input" && i + 1 < argc) { input_filename = std::string(argv[i + 1]); } else if (std::string(argv[i]) == "--help" || std::string(argv[i]) == "-h") { std::cout << "Usage: " << argv[0] << " [--input <input image>] [--help]" << std::endl; return EXIT_SUCCESS; } } vpImage<unsigned char> I; vpImageIo::read(I, input_filename); vpImage<unsigned char> I_res(3 * I.getHeight(), 3 * I.getWidth()); I_res.insert(I, vpImagePoint(I.getHeight(), I.getWidth())); #ifdef VISP_HAVE_X11 vpDisplayX d; #elif defined(VISP_HAVE_GDI) vpDisplayGDI d; #elif defined(VISP_HAVE_OPENCV) vpDisplayOpenCV d; #endif d.setDownScalingFactor(vpDisplay::SCALE_2); d.init(I_res); //! [Huang] vpImage<unsigned char> I_huang = I; vp::autoThreshold(I_huang, vp::AUTO_THRESHOLD_HUANG); //! [Huang] I_res.insert(I_huang, vpImagePoint()); //! [Intermodes] vpImage<unsigned char> I_intermodes = I; vp::autoThreshold(I_intermodes, vp::AUTO_THRESHOLD_INTERMODES); //! [Intermodes] I_res.insert(I_intermodes, vpImagePoint(0, I.getWidth())); //! [IsoData] vpImage<unsigned char> I_isodata = I; vp::autoThreshold(I_isodata, vp::AUTO_THRESHOLD_ISODATA); //! [IsoData] I_res.insert(I_isodata, vpImagePoint(0, 2 * I.getWidth())); //! [Mean] vpImage<unsigned char> I_mean = I; vp::autoThreshold(I_mean, vp::AUTO_THRESHOLD_MEAN); //! [Mean] I_res.insert(I_mean, vpImagePoint(I.getHeight(), 0)); //! [Otsu] vpImage<unsigned char> I_otsu = I; vp::autoThreshold(I_otsu, vp::AUTO_THRESHOLD_OTSU); //! [Otsu] I_res.insert(I_otsu, vpImagePoint(I.getHeight(), 2 * I.getWidth())); //! [Triangle] vpImage<unsigned char> I_triangle = I; vp::autoThreshold(I_triangle, vp::AUTO_THRESHOLD_TRIANGLE); //! [Triangle] I_res.insert(I_triangle, vpImagePoint(2 * I.getHeight(), 0)); vpDisplay::display(I_res); vpDisplay::displayText(I_res, 30, 20, "Huang", vpColor::red); vpDisplay::displayText(I_res, 30, 20 + I.getWidth(), "Intermodes", vpColor::red); vpDisplay::displayText(I_res, 30, 20 + 2 * I.getWidth(), "IsoData", vpColor::red); vpDisplay::displayText(I_res, 30 + I.getHeight(), 20, "Mean", vpColor::red); vpDisplay::displayText(I_res, 30 + I.getHeight(), 20 + I.getWidth(), "Original", vpColor::red); vpDisplay::displayText(I_res, 30 + I.getHeight(), 20 + 2 * I.getWidth(), "Otsu", vpColor::red); vpDisplay::displayText(I_res, 30 + 2 * I.getHeight(), 20, "Triangle", vpColor::red); vpDisplay::flush(I_res); vpDisplay::getClick(I_res); return EXIT_SUCCESS; #else (void)argc; (void)argv; return 0; #endif }
{ "language": "C++" }
/** * ============================================================================= * Source Python * Copyright (C) 2012-2015 Source Python Development Team. All rights reserved. * ============================================================================= * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, version 3.0, as published by the * Free Software Foundation. * * 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, see <http://www.gnu.org/licenses/>. * * As a special exception, the Source Python Team gives you permission * to link the code of this program (as well as its derivative works) to * "Half-Life 2," the "Source Engine," and any Game MODs that run on software * by the Valve Corporation. You must obey the GNU General Public License in * all respects for all other code used. Additionally, the Source.Python * Development Team grants this exception to all derivative works. */ #ifndef _MATHLIB_H #define _MATHLIB_H //----------------------------------------------------------------------------- // Includes. //----------------------------------------------------------------------------- #include "mathlib/vector.h" //----------------------------------------------------------------------------- // Vector extension class. //----------------------------------------------------------------------------- class VectorExt { public: static bool IsWithinBox(Vector& point, Vector& corner1, Vector& corner2) { return point.WithinAABox(corner1.Min(corner2), corner2.Max(corner1)); } static void SetLength(Vector& vec, float fLength) { vec.NormalizeInPlace(); vec *= fLength; } static inline float GetLength(Vector& vec) { // Workaround for https://github.com/Source-Python-Dev-Team/Source.Python/issues/150 #ifdef __linux__ return sqrt(vec.LengthSqr()); #else return vec.Length(); #endif } static inline float GetLength2D(Vector& vec) { // Workaround for https://github.com/Source-Python-Dev-Team/Source.Python/issues/150 #ifdef __linux__ return sqrt(vec.Length2DSqr()); #else return vec.Length2D(); #endif } static str __repr__(Vector* pVector) { return str("Vector" + str(tuple(pVector))); } static Vector Copy(Vector* pVec) { return *pVec; } static Vector Normalized(Vector* pVec) { Vector copy = *pVec; copy.NormalizeInPlace(); return copy; } static inline Vector __add__(Vector vecCopy, float val) { vecCopy += val; return vecCopy; } static inline Vector __sub__(Vector vecCopy, float val) { vecCopy -= val; return vecCopy; } static inline Vector __neg__(Vector vecCopy) { vecCopy.Negate(); return vecCopy; } }; //----------------------------------------------------------------------------- // QAngle extension class. //----------------------------------------------------------------------------- class QAngleExt { public: static str __repr__(QAngle* pQAngle) { return str("QAngle" + str(tuple(pQAngle))); } }; //----------------------------------------------------------------------------- // Quaternion extension class. //----------------------------------------------------------------------------- class QuaternionExt { public: static str __repr__(Quaternion* pQuaternion) { return str("Quaternion" + str(tuple(pQuaternion))); } }; //----------------------------------------------------------------------------- // RadianEuler extension class. //----------------------------------------------------------------------------- class RadianEulerExt { public: static str __repr__(RadianEuler* pRadianEuler) { return str("RadianEuler" + str(tuple(pRadianEuler))); } }; //----------------------------------------------------------------------------- // matrix3x4_t extension class. //----------------------------------------------------------------------------- class Matrix3x4Row { public: Matrix3x4Row(float* row) { m_row = row; } float& operator[](unsigned int index) { return m_row[index]; } str __repr__() { return str(tuple(*this)); } public: float* m_row; }; class matrix3x4_tExt { public: static Matrix3x4Row* __getitem__(matrix3x4_t& matrix, unsigned int index) { if (index >= 3) { BOOST_RAISE_EXCEPTION(PyExc_IndexError, "Index out of range (%d)", index) } return new Matrix3x4Row(matrix[index]); } static str __repr__(matrix3x4_t& matrix) { return str("[" + str(__getitem__(matrix, 0)) + ",\n" + str(__getitem__(matrix, 1)) + ",\n" + str(__getitem__(matrix, 2)) + "]"); } static Vector* get_position(matrix3x4_t& matrix) { Vector* result = new Vector(); MatrixPosition(matrix, *result); return result; } static QAngle* get_angles(matrix3x4_t& matrix) { QAngle* result = new QAngle(); MatrixAngles(matrix, *result); return result; } }; #endif // _MATHLIB_H
{ "language": "C++" }
#include "MinimalValueType.h" std::atomic<int> MinimalValueType::instances(0);
{ "language": "C++" }
// Copyright 2017 the V8 project 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 "src/builtins/builtins-string-gen.h" #include "src/builtins/builtins-regexp-gen.h" #include "src/builtins/builtins-utils-gen.h" #include "src/builtins/builtins.h" #include "src/code-factory.h" #include "src/objects.h" namespace v8 { namespace internal { typedef CodeStubAssembler::RelationalComparisonMode RelationalComparisonMode; typedef compiler::Node Node; template <class A> using TNode = compiler::TNode<A>; Node* StringBuiltinsAssembler::DirectStringData(Node* string, Node* string_instance_type) { // Compute the effective offset of the first character. VARIABLE(var_data, MachineType::PointerRepresentation()); Label if_sequential(this), if_external(this), if_join(this); Branch(Word32Equal(Word32And(string_instance_type, Int32Constant(kStringRepresentationMask)), Int32Constant(kSeqStringTag)), &if_sequential, &if_external); BIND(&if_sequential); { var_data.Bind(IntPtrAdd( IntPtrConstant(SeqOneByteString::kHeaderSize - kHeapObjectTag), BitcastTaggedToWord(string))); Goto(&if_join); } BIND(&if_external); { // This is only valid for ExternalStrings where the resource data // pointer is cached (i.e. no short external strings). CSA_ASSERT( this, Word32NotEqual(Word32And(string_instance_type, Int32Constant(kShortExternalStringMask)), Int32Constant(kShortExternalStringTag))); var_data.Bind(LoadObjectField(string, ExternalString::kResourceDataOffset, MachineType::Pointer())); Goto(&if_join); } BIND(&if_join); return var_data.value(); } void StringBuiltinsAssembler::DispatchOnStringEncodings( Node* const lhs_instance_type, Node* const rhs_instance_type, Label* if_one_one, Label* if_one_two, Label* if_two_one, Label* if_two_two) { STATIC_ASSERT(kStringEncodingMask == 0x8); STATIC_ASSERT(kTwoByteStringTag == 0x0); STATIC_ASSERT(kOneByteStringTag == 0x8); // First combine the encodings. Node* const encoding_mask = Int32Constant(kStringEncodingMask); Node* const lhs_encoding = Word32And(lhs_instance_type, encoding_mask); Node* const rhs_encoding = Word32And(rhs_instance_type, encoding_mask); Node* const combined_encodings = Word32Or(lhs_encoding, Word32Shr(rhs_encoding, 1)); // Then dispatch on the combined encoding. Label unreachable(this, Label::kDeferred); int32_t values[] = { kOneByteStringTag | (kOneByteStringTag >> 1), kOneByteStringTag | (kTwoByteStringTag >> 1), kTwoByteStringTag | (kOneByteStringTag >> 1), kTwoByteStringTag | (kTwoByteStringTag >> 1), }; Label* labels[] = { if_one_one, if_one_two, if_two_one, if_two_two, }; STATIC_ASSERT(arraysize(values) == arraysize(labels)); Switch(combined_encodings, &unreachable, values, labels, arraysize(values)); BIND(&unreachable); Unreachable(); } template <typename SubjectChar, typename PatternChar> Node* StringBuiltinsAssembler::CallSearchStringRaw(Node* const subject_ptr, Node* const subject_length, Node* const search_ptr, Node* const search_length, Node* const start_position) { Node* const function_addr = ExternalConstant( ExternalReference::search_string_raw<SubjectChar, PatternChar>( isolate())); Node* const isolate_ptr = ExternalConstant(ExternalReference::isolate_address(isolate())); MachineType type_ptr = MachineType::Pointer(); MachineType type_intptr = MachineType::IntPtr(); Node* const result = CallCFunction6( type_intptr, type_ptr, type_ptr, type_intptr, type_ptr, type_intptr, type_intptr, function_addr, isolate_ptr, subject_ptr, subject_length, search_ptr, search_length, start_position); return result; } Node* StringBuiltinsAssembler::PointerToStringDataAtIndex( Node* const string_data, Node* const index, String::Encoding encoding) { const ElementsKind kind = (encoding == String::ONE_BYTE_ENCODING) ? UINT8_ELEMENTS : UINT16_ELEMENTS; Node* const offset_in_bytes = ElementOffsetFromIndex(index, kind, INTPTR_PARAMETERS); return IntPtrAdd(string_data, offset_in_bytes); } void StringBuiltinsAssembler::ConvertAndBoundsCheckStartArgument( Node* context, Variable* var_start, Node* start, Node* string_length) { TNode<Object> const start_int = ToInteger(context, start, CodeStubAssembler::kTruncateMinusZero); TNode<Smi> const zero = SmiConstant(0); Label done(this); Label if_issmi(this), if_isheapnumber(this, Label::kDeferred); Branch(TaggedIsSmi(start_int), &if_issmi, &if_isheapnumber); BIND(&if_issmi); { TNode<Smi> const start_int_smi = CAST(start_int); var_start->Bind(Select( SmiLessThan(start_int_smi, zero), [&] { return SmiMax(SmiAdd(string_length, start_int_smi), zero); }, [&] { return start_int_smi; }, MachineRepresentation::kTagged)); Goto(&done); } BIND(&if_isheapnumber); { // If {start} is a heap number, it is definitely out of bounds. If it is // negative, {start} = max({string_length} + {start}),0) = 0'. If it is // positive, set {start} to {string_length} which ultimately results in // returning an empty string. TNode<HeapNumber> const start_int_hn = CAST(start_int); TNode<Float64T> const float_zero = Float64Constant(0.); TNode<Float64T> const start_float = LoadHeapNumberValue(start_int_hn); var_start->Bind(SelectTaggedConstant<Smi>( Float64LessThan(start_float, float_zero), zero, string_length)); Goto(&done); } BIND(&done); } void StringBuiltinsAssembler::GenerateStringEqual(Node* context, Node* left, Node* right) { // Here's pseudo-code for the algorithm below: // // if (lhs->length() != rhs->length()) return false; // restart: // if (lhs == rhs) return true; // if (lhs->IsInternalizedString() && rhs->IsInternalizedString()) { // return false; // } // if (lhs->IsSeqOneByteString() && rhs->IsSeqOneByteString()) { // for (i = 0; i != lhs->length(); ++i) { // if (lhs[i] != rhs[i]) return false; // } // return true; // } // if (lhs and/or rhs are indirect strings) { // unwrap them and restart from the "restart:" label; // } // return %StringEqual(lhs, rhs); VARIABLE(var_left, MachineRepresentation::kTagged, left); VARIABLE(var_right, MachineRepresentation::kTagged, right); Variable* input_vars[2] = {&var_left, &var_right}; Label if_equal(this), if_notequal(this), if_notbothdirectonebytestrings(this), restart(this, 2, input_vars); Node* lhs_length = LoadStringLength(left); Node* rhs_length = LoadStringLength(right); // Strings with different lengths cannot be equal. GotoIf(WordNotEqual(lhs_length, rhs_length), &if_notequal); Goto(&restart); BIND(&restart); Node* lhs = var_left.value(); Node* rhs = var_right.value(); Node* lhs_instance_type = LoadInstanceType(lhs); Node* rhs_instance_type = LoadInstanceType(rhs); StringEqual_Core(context, lhs, lhs_instance_type, lhs_length, rhs, rhs_instance_type, &if_equal, &if_notequal, &if_notbothdirectonebytestrings); BIND(&if_notbothdirectonebytestrings); { // Try to unwrap indirect strings, restart the above attempt on success. MaybeDerefIndirectStrings(&var_left, lhs_instance_type, &var_right, rhs_instance_type, &restart); // TODO(bmeurer): Add support for two byte string equality checks. TailCallRuntime(Runtime::kStringEqual, context, lhs, rhs); } BIND(&if_equal); Return(TrueConstant()); BIND(&if_notequal); Return(FalseConstant()); } void StringBuiltinsAssembler::StringEqual_Core( Node* context, Node* lhs, Node* lhs_instance_type, Node* lhs_length, Node* rhs, Node* rhs_instance_type, Label* if_equal, Label* if_not_equal, Label* if_notbothdirectonebyte) { CSA_ASSERT(this, IsString(lhs)); CSA_ASSERT(this, IsString(rhs)); CSA_ASSERT(this, WordEqual(LoadStringLength(lhs), lhs_length)); CSA_ASSERT(this, WordEqual(LoadStringLength(rhs), lhs_length)); // Fast check to see if {lhs} and {rhs} refer to the same String object. GotoIf(WordEqual(lhs, rhs), if_equal); // Combine the instance types into a single 16-bit value, so we can check // both of them at once. Node* both_instance_types = Word32Or( lhs_instance_type, Word32Shl(rhs_instance_type, Int32Constant(8))); // Check if both {lhs} and {rhs} are internalized. Since we already know // that they're not the same object, they're not equal in that case. int const kBothInternalizedMask = kIsNotInternalizedMask | (kIsNotInternalizedMask << 8); int const kBothInternalizedTag = kInternalizedTag | (kInternalizedTag << 8); GotoIf(Word32Equal(Word32And(both_instance_types, Int32Constant(kBothInternalizedMask)), Int32Constant(kBothInternalizedTag)), if_not_equal); // Check that both {lhs} and {rhs} are flat one-byte strings, and that // in case of ExternalStrings the data pointer is cached.. STATIC_ASSERT(kShortExternalStringTag != 0); int const kBothDirectOneByteStringMask = kStringEncodingMask | kIsIndirectStringMask | kShortExternalStringMask | ((kStringEncodingMask | kIsIndirectStringMask | kShortExternalStringMask) << 8); int const kBothDirectOneByteStringTag = kOneByteStringTag | (kOneByteStringTag << 8); GotoIfNot(Word32Equal(Word32And(both_instance_types, Int32Constant(kBothDirectOneByteStringMask)), Int32Constant(kBothDirectOneByteStringTag)), if_notbothdirectonebyte); // At this point we know that we have two direct one-byte strings. // Compute the effective offset of the first character. Node* lhs_data = DirectStringData(lhs, lhs_instance_type); Node* rhs_data = DirectStringData(rhs, rhs_instance_type); // Compute the first offset after the string from the length. Node* length = SmiUntag(lhs_length); // Loop over the {lhs} and {rhs} strings to see if they are equal. VARIABLE(var_offset, MachineType::PointerRepresentation()); Label loop(this, &var_offset); var_offset.Bind(IntPtrConstant(0)); Goto(&loop); BIND(&loop); { // If {offset} equals {end}, no difference was found, so the // strings are equal. Node* offset = var_offset.value(); GotoIf(WordEqual(offset, length), if_equal); // Load the next characters from {lhs} and {rhs}. Node* lhs_value = Load(MachineType::Uint8(), lhs_data, offset); Node* rhs_value = Load(MachineType::Uint8(), rhs_data, offset); // Check if the characters match. GotoIf(Word32NotEqual(lhs_value, rhs_value), if_not_equal); // Advance to next character. var_offset.Bind(IntPtrAdd(offset, IntPtrConstant(1))); Goto(&loop); } } void StringBuiltinsAssembler::GenerateStringRelationalComparison( Node* context, Node* left, Node* right, RelationalComparisonMode mode) { VARIABLE(var_left, MachineRepresentation::kTagged, left); VARIABLE(var_right, MachineRepresentation::kTagged, right); Variable* input_vars[2] = {&var_left, &var_right}; Label if_less(this), if_equal(this), if_greater(this); Label restart(this, 2, input_vars); Goto(&restart); BIND(&restart); Node* lhs = var_left.value(); Node* rhs = var_right.value(); // Fast check to see if {lhs} and {rhs} refer to the same String object. GotoIf(WordEqual(lhs, rhs), &if_equal); // Load instance types of {lhs} and {rhs}. Node* lhs_instance_type = LoadInstanceType(lhs); Node* rhs_instance_type = LoadInstanceType(rhs); // Combine the instance types into a single 16-bit value, so we can check // both of them at once. Node* both_instance_types = Word32Or( lhs_instance_type, Word32Shl(rhs_instance_type, Int32Constant(8))); // Check that both {lhs} and {rhs} are flat one-byte strings. int const kBothSeqOneByteStringMask = kStringEncodingMask | kStringRepresentationMask | ((kStringEncodingMask | kStringRepresentationMask) << 8); int const kBothSeqOneByteStringTag = kOneByteStringTag | kSeqStringTag | ((kOneByteStringTag | kSeqStringTag) << 8); Label if_bothonebyteseqstrings(this), if_notbothonebyteseqstrings(this); Branch(Word32Equal(Word32And(both_instance_types, Int32Constant(kBothSeqOneByteStringMask)), Int32Constant(kBothSeqOneByteStringTag)), &if_bothonebyteseqstrings, &if_notbothonebyteseqstrings); BIND(&if_bothonebyteseqstrings); { // Load the length of {lhs} and {rhs}. Node* lhs_length = LoadStringLength(lhs); Node* rhs_length = LoadStringLength(rhs); // Determine the minimum length. Node* length = SmiMin(lhs_length, rhs_length); // Compute the effective offset of the first character. Node* begin = IntPtrConstant(SeqOneByteString::kHeaderSize - kHeapObjectTag); // Compute the first offset after the string from the length. Node* end = IntPtrAdd(begin, SmiUntag(length)); // Loop over the {lhs} and {rhs} strings to see if they are equal. VARIABLE(var_offset, MachineType::PointerRepresentation()); Label loop(this, &var_offset); var_offset.Bind(begin); Goto(&loop); BIND(&loop); { // Check if {offset} equals {end}. Node* offset = var_offset.value(); Label if_done(this), if_notdone(this); Branch(WordEqual(offset, end), &if_done, &if_notdone); BIND(&if_notdone); { // Load the next characters from {lhs} and {rhs}. Node* lhs_value = Load(MachineType::Uint8(), lhs, offset); Node* rhs_value = Load(MachineType::Uint8(), rhs, offset); // Check if the characters match. Label if_valueissame(this), if_valueisnotsame(this); Branch(Word32Equal(lhs_value, rhs_value), &if_valueissame, &if_valueisnotsame); BIND(&if_valueissame); { // Advance to next character. var_offset.Bind(IntPtrAdd(offset, IntPtrConstant(1))); } Goto(&loop); BIND(&if_valueisnotsame); Branch(Uint32LessThan(lhs_value, rhs_value), &if_less, &if_greater); } BIND(&if_done); { // All characters up to the min length are equal, decide based on // string length. GotoIf(SmiEqual(lhs_length, rhs_length), &if_equal); BranchIfSmiLessThan(lhs_length, rhs_length, &if_less, &if_greater); } } } BIND(&if_notbothonebyteseqstrings); { // Try to unwrap indirect strings, restart the above attempt on success. MaybeDerefIndirectStrings(&var_left, lhs_instance_type, &var_right, rhs_instance_type, &restart); // TODO(bmeurer): Add support for two byte string relational comparisons. switch (mode) { case RelationalComparisonMode::kLessThan: TailCallRuntime(Runtime::kStringLessThan, context, lhs, rhs); break; case RelationalComparisonMode::kLessThanOrEqual: TailCallRuntime(Runtime::kStringLessThanOrEqual, context, lhs, rhs); break; case RelationalComparisonMode::kGreaterThan: TailCallRuntime(Runtime::kStringGreaterThan, context, lhs, rhs); break; case RelationalComparisonMode::kGreaterThanOrEqual: TailCallRuntime(Runtime::kStringGreaterThanOrEqual, context, lhs, rhs); break; } } BIND(&if_less); switch (mode) { case RelationalComparisonMode::kLessThan: case RelationalComparisonMode::kLessThanOrEqual: Return(BooleanConstant(true)); break; case RelationalComparisonMode::kGreaterThan: case RelationalComparisonMode::kGreaterThanOrEqual: Return(BooleanConstant(false)); break; } BIND(&if_equal); switch (mode) { case RelationalComparisonMode::kLessThan: case RelationalComparisonMode::kGreaterThan: Return(BooleanConstant(false)); break; case RelationalComparisonMode::kLessThanOrEqual: case RelationalComparisonMode::kGreaterThanOrEqual: Return(BooleanConstant(true)); break; } BIND(&if_greater); switch (mode) { case RelationalComparisonMode::kLessThan: case RelationalComparisonMode::kLessThanOrEqual: Return(BooleanConstant(false)); break; case RelationalComparisonMode::kGreaterThan: case RelationalComparisonMode::kGreaterThanOrEqual: Return(BooleanConstant(true)); break; } } TF_BUILTIN(StringEqual, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* left = Parameter(Descriptor::kLeft); Node* right = Parameter(Descriptor::kRight); GenerateStringEqual(context, left, right); } TF_BUILTIN(StringLessThan, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* left = Parameter(Descriptor::kLeft); Node* right = Parameter(Descriptor::kRight); GenerateStringRelationalComparison(context, left, right, RelationalComparisonMode::kLessThan); } TF_BUILTIN(StringLessThanOrEqual, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* left = Parameter(Descriptor::kLeft); Node* right = Parameter(Descriptor::kRight); GenerateStringRelationalComparison( context, left, right, RelationalComparisonMode::kLessThanOrEqual); } TF_BUILTIN(StringGreaterThan, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* left = Parameter(Descriptor::kLeft); Node* right = Parameter(Descriptor::kRight); GenerateStringRelationalComparison(context, left, right, RelationalComparisonMode::kGreaterThan); } TF_BUILTIN(StringGreaterThanOrEqual, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* left = Parameter(Descriptor::kLeft); Node* right = Parameter(Descriptor::kRight); GenerateStringRelationalComparison( context, left, right, RelationalComparisonMode::kGreaterThanOrEqual); } TF_BUILTIN(StringCharAt, CodeStubAssembler) { Node* receiver = Parameter(Descriptor::kReceiver); Node* position = Parameter(Descriptor::kPosition); // Load the character code at the {position} from the {receiver}. Node* code = StringCharCodeAt(receiver, position, INTPTR_PARAMETERS); // And return the single character string with only that {code} Node* result = StringFromCharCode(code); Return(result); } TF_BUILTIN(StringCharCodeAt, CodeStubAssembler) { Node* receiver = Parameter(Descriptor::kReceiver); Node* position = Parameter(Descriptor::kPosition); // Load the character code at the {position} from the {receiver}. Node* code = StringCharCodeAt(receiver, position, INTPTR_PARAMETERS); // And return it as TaggedSigned value. // TODO(turbofan): Allow builtins to return values untagged. Node* result = SmiFromWord32(code); Return(result); } // ----------------------------------------------------------------------------- // ES6 section 21.1 String Objects // ES6 #sec-string.fromcharcode TF_BUILTIN(StringFromCharCode, CodeStubAssembler) { // TODO(ishell): use constants from Descriptor once the JSFunction linkage // arguments are reordered. Node* argc = Parameter(BuiltinDescriptor::kArgumentsCount); Node* context = Parameter(BuiltinDescriptor::kContext); CodeStubArguments arguments(this, ChangeInt32ToIntPtr(argc)); // From now on use word-size argc value. argc = arguments.GetLength(); // Check if we have exactly one argument (plus the implicit receiver), i.e. // if the parent frame is not an arguments adaptor frame. Label if_oneargument(this), if_notoneargument(this); Branch(WordEqual(argc, IntPtrConstant(1)), &if_oneargument, &if_notoneargument); BIND(&if_oneargument); { // Single argument case, perform fast single character string cache lookup // for one-byte code units, or fall back to creating a single character // string on the fly otherwise. Node* code = arguments.AtIndex(0); Node* code32 = TruncateTaggedToWord32(context, code); Node* code16 = Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit)); Node* result = StringFromCharCode(code16); arguments.PopAndReturn(result); } Node* code16 = nullptr; BIND(&if_notoneargument); { Label two_byte(this); // Assume that the resulting string contains only one-byte characters. Node* one_byte_result = AllocateSeqOneByteString(context, argc); VARIABLE(max_index, MachineType::PointerRepresentation()); max_index.Bind(IntPtrConstant(0)); // Iterate over the incoming arguments, converting them to 8-bit character // codes. Stop if any of the conversions generates a code that doesn't fit // in 8 bits. CodeStubAssembler::VariableList vars({&max_index}, zone()); arguments.ForEach(vars, [this, context, &two_byte, &max_index, &code16, one_byte_result](Node* arg) { Node* code32 = TruncateTaggedToWord32(context, arg); code16 = Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit)); GotoIf( Int32GreaterThan(code16, Int32Constant(String::kMaxOneByteCharCode)), &two_byte); // The {code16} fits into the SeqOneByteString {one_byte_result}. Node* offset = ElementOffsetFromIndex( max_index.value(), UINT8_ELEMENTS, CodeStubAssembler::INTPTR_PARAMETERS, SeqOneByteString::kHeaderSize - kHeapObjectTag); StoreNoWriteBarrier(MachineRepresentation::kWord8, one_byte_result, offset, code16); max_index.Bind(IntPtrAdd(max_index.value(), IntPtrConstant(1))); }); arguments.PopAndReturn(one_byte_result); BIND(&two_byte); // At least one of the characters in the string requires a 16-bit // representation. Allocate a SeqTwoByteString to hold the resulting // string. Node* two_byte_result = AllocateSeqTwoByteString(context, argc); // Copy the characters that have already been put in the 8-bit string into // their corresponding positions in the new 16-bit string. Node* zero = IntPtrConstant(0); CopyStringCharacters(one_byte_result, two_byte_result, zero, zero, max_index.value(), String::ONE_BYTE_ENCODING, String::TWO_BYTE_ENCODING, CodeStubAssembler::INTPTR_PARAMETERS); // Write the character that caused the 8-bit to 16-bit fault. Node* max_index_offset = ElementOffsetFromIndex(max_index.value(), UINT16_ELEMENTS, CodeStubAssembler::INTPTR_PARAMETERS, SeqTwoByteString::kHeaderSize - kHeapObjectTag); StoreNoWriteBarrier(MachineRepresentation::kWord16, two_byte_result, max_index_offset, code16); max_index.Bind(IntPtrAdd(max_index.value(), IntPtrConstant(1))); // Resume copying the passed-in arguments from the same place where the // 8-bit copy stopped, but this time copying over all of the characters // using a 16-bit representation. arguments.ForEach( vars, [this, context, two_byte_result, &max_index](Node* arg) { Node* code32 = TruncateTaggedToWord32(context, arg); Node* code16 = Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit)); Node* offset = ElementOffsetFromIndex( max_index.value(), UINT16_ELEMENTS, CodeStubAssembler::INTPTR_PARAMETERS, SeqTwoByteString::kHeaderSize - kHeapObjectTag); StoreNoWriteBarrier(MachineRepresentation::kWord16, two_byte_result, offset, code16); max_index.Bind(IntPtrAdd(max_index.value(), IntPtrConstant(1))); }, max_index.value()); arguments.PopAndReturn(two_byte_result); } } // ES6 #sec-string.prototype.charat TF_BUILTIN(StringPrototypeCharAt, CodeStubAssembler) { Node* receiver = Parameter(Descriptor::kReceiver); Node* position = Parameter(Descriptor::kPosition); Node* context = Parameter(Descriptor::kContext); // Check that {receiver} is coercible to Object and convert it to a String. receiver = ToThisString(context, receiver, "String.prototype.charAt"); // Convert the {position} to a Smi and check that it's in bounds of the // {receiver}. { Label return_emptystring(this, Label::kDeferred); position = ToInteger(context, position, CodeStubAssembler::kTruncateMinusZero); GotoIfNot(TaggedIsSmi(position), &return_emptystring); // Determine the actual length of the {receiver} String. Node* receiver_length = LoadObjectField(receiver, String::kLengthOffset); // Return "" if the Smi {position} is outside the bounds of the {receiver}. Label if_positioninbounds(this); Branch(SmiAboveOrEqual(position, receiver_length), &return_emptystring, &if_positioninbounds); BIND(&return_emptystring); Return(EmptyStringConstant()); BIND(&if_positioninbounds); } // Load the character code at the {position} from the {receiver}. Node* code = StringCharCodeAt(receiver, position); // And return the single character string with only that {code}. Node* result = StringFromCharCode(code); Return(result); } // ES6 #sec-string.prototype.charcodeat TF_BUILTIN(StringPrototypeCharCodeAt, CodeStubAssembler) { Node* receiver = Parameter(Descriptor::kReceiver); Node* position = Parameter(Descriptor::kPosition); Node* context = Parameter(Descriptor::kContext); // Check that {receiver} is coercible to Object and convert it to a String. receiver = ToThisString(context, receiver, "String.prototype.charCodeAt"); // Convert the {position} to a Smi and check that it's in bounds of the // {receiver}. { Label return_nan(this, Label::kDeferred); position = ToInteger(context, position, CodeStubAssembler::kTruncateMinusZero); GotoIfNot(TaggedIsSmi(position), &return_nan); // Determine the actual length of the {receiver} String. Node* receiver_length = LoadObjectField(receiver, String::kLengthOffset); // Return NaN if the Smi {position} is outside the bounds of the {receiver}. Label if_positioninbounds(this); Branch(SmiAboveOrEqual(position, receiver_length), &return_nan, &if_positioninbounds); BIND(&return_nan); Return(NaNConstant()); BIND(&if_positioninbounds); } // Load the character at the {position} from the {receiver}. Node* value = StringCharCodeAt(receiver, position); Node* result = SmiFromWord32(value); Return(result); } // ES6 #sec-string.prototype.codepointat TF_BUILTIN(StringPrototypeCodePointAt, StringBuiltinsAssembler) { Node* context = Parameter(Descriptor::kContext); Node* receiver = Parameter(Descriptor::kReceiver); Node* position = Parameter(Descriptor::kPosition); // Check that {receiver} is coercible to Object and convert it to a String. receiver = ToThisString(context, receiver, "String.prototype.codePointAt"); // Convert the {position} to a Smi and check that it's in bounds of the // {receiver}. Label if_inbounds(this), if_outofbounds(this, Label::kDeferred); position = ToInteger(context, position, CodeStubAssembler::kTruncateMinusZero); GotoIfNot(TaggedIsSmi(position), &if_outofbounds); Node* receiver_length = LoadObjectField(receiver, String::kLengthOffset); Branch(SmiBelow(position, receiver_length), &if_inbounds, &if_outofbounds); BIND(&if_inbounds); { Node* value = LoadSurrogatePairAt(receiver, receiver_length, position, UnicodeEncoding::UTF32); Node* result = SmiFromWord32(value); Return(result); } BIND(&if_outofbounds); Return(UndefinedConstant()); } // ES6 String.prototype.concat(...args) // ES6 #sec-string.prototype.concat TF_BUILTIN(StringPrototypeConcat, CodeStubAssembler) { // TODO(ishell): use constants from Descriptor once the JSFunction linkage // arguments are reordered. CodeStubArguments arguments( this, ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount))); Node* receiver = arguments.GetReceiver(); Node* context = Parameter(BuiltinDescriptor::kContext); // Check that {receiver} is coercible to Object and convert it to a String. receiver = ToThisString(context, receiver, "String.prototype.concat"); // Concatenate all the arguments passed to this builtin. VARIABLE(var_result, MachineRepresentation::kTagged); var_result.Bind(receiver); arguments.ForEach( CodeStubAssembler::VariableList({&var_result}, zone()), [this, context, &var_result](Node* arg) { arg = ToString_Inline(context, arg); var_result.Bind(CallStub(CodeFactory::StringAdd(isolate()), context, var_result.value(), arg)); }); arguments.PopAndReturn(var_result.value()); } void StringBuiltinsAssembler::StringIndexOf( Node* const subject_string, Node* const search_string, Node* const position, std::function<void(Node*)> f_return) { CSA_ASSERT(this, IsString(subject_string)); CSA_ASSERT(this, IsString(search_string)); CSA_ASSERT(this, TaggedIsSmi(position)); Node* const int_zero = IntPtrConstant(0); VARIABLE(var_needle_byte, MachineType::PointerRepresentation(), int_zero); VARIABLE(var_string_addr, MachineType::PointerRepresentation(), int_zero); Node* const search_length = SmiUntag(LoadStringLength(search_string)); Node* const subject_length = SmiUntag(LoadStringLength(subject_string)); Node* const start_position = IntPtrMax(SmiUntag(position), int_zero); Label zero_length_needle(this), return_minus_1(this); { GotoIf(IntPtrEqual(int_zero, search_length), &zero_length_needle); // Check that the needle fits in the start position. GotoIfNot(IntPtrLessThanOrEqual(search_length, IntPtrSub(subject_length, start_position)), &return_minus_1); } // If the string pointers are identical, we can just return 0. Note that this // implies {start_position} == 0 since we've passed the check above. Label return_zero(this); GotoIf(WordEqual(subject_string, search_string), &return_zero); // Try to unpack subject and search strings. Bail to runtime if either needs // to be flattened. ToDirectStringAssembler subject_to_direct(state(), subject_string); ToDirectStringAssembler search_to_direct(state(), search_string); Label call_runtime_unchecked(this, Label::kDeferred); subject_to_direct.TryToDirect(&call_runtime_unchecked); search_to_direct.TryToDirect(&call_runtime_unchecked); // Load pointers to string data. Node* const subject_ptr = subject_to_direct.PointerToData(&call_runtime_unchecked); Node* const search_ptr = search_to_direct.PointerToData(&call_runtime_unchecked); Node* const subject_offset = subject_to_direct.offset(); Node* const search_offset = search_to_direct.offset(); // Like String::IndexOf, the actual matching is done by the optimized // SearchString method in string-search.h. Dispatch based on string instance // types, then call straight into C++ for matching. CSA_ASSERT(this, IntPtrGreaterThan(search_length, int_zero)); CSA_ASSERT(this, IntPtrGreaterThanOrEqual(start_position, int_zero)); CSA_ASSERT(this, IntPtrGreaterThanOrEqual(subject_length, start_position)); CSA_ASSERT(this, IntPtrLessThanOrEqual(search_length, IntPtrSub(subject_length, start_position))); Label one_one(this), one_two(this), two_one(this), two_two(this); DispatchOnStringEncodings(subject_to_direct.instance_type(), search_to_direct.instance_type(), &one_one, &one_two, &two_one, &two_two); typedef const uint8_t onebyte_t; typedef const uc16 twobyte_t; BIND(&one_one); { Node* const adjusted_subject_ptr = PointerToStringDataAtIndex( subject_ptr, subject_offset, String::ONE_BYTE_ENCODING); Node* const adjusted_search_ptr = PointerToStringDataAtIndex( search_ptr, search_offset, String::ONE_BYTE_ENCODING); Label direct_memchr_call(this), generic_fast_path(this); Branch(IntPtrEqual(search_length, IntPtrConstant(1)), &direct_memchr_call, &generic_fast_path); // An additional fast path that calls directly into memchr for 1-length // search strings. BIND(&direct_memchr_call); { Node* const string_addr = IntPtrAdd(adjusted_subject_ptr, start_position); Node* const search_length = IntPtrSub(subject_length, start_position); Node* const search_byte = ChangeInt32ToIntPtr(Load(MachineType::Uint8(), adjusted_search_ptr)); Node* const memchr = ExternalConstant(ExternalReference::libc_memchr_function(isolate())); Node* const result_address = CallCFunction3(MachineType::Pointer(), MachineType::Pointer(), MachineType::IntPtr(), MachineType::UintPtr(), memchr, string_addr, search_byte, search_length); GotoIf(WordEqual(result_address, int_zero), &return_minus_1); Node* const result_index = IntPtrAdd(IntPtrSub(result_address, string_addr), start_position); f_return(SmiTag(result_index)); } BIND(&generic_fast_path); { Node* const result = CallSearchStringRaw<onebyte_t, onebyte_t>( adjusted_subject_ptr, subject_length, adjusted_search_ptr, search_length, start_position); f_return(SmiTag(result)); } } BIND(&one_two); { Node* const adjusted_subject_ptr = PointerToStringDataAtIndex( subject_ptr, subject_offset, String::ONE_BYTE_ENCODING); Node* const adjusted_search_ptr = PointerToStringDataAtIndex( search_ptr, search_offset, String::TWO_BYTE_ENCODING); Node* const result = CallSearchStringRaw<onebyte_t, twobyte_t>( adjusted_subject_ptr, subject_length, adjusted_search_ptr, search_length, start_position); f_return(SmiTag(result)); } BIND(&two_one); { Node* const adjusted_subject_ptr = PointerToStringDataAtIndex( subject_ptr, subject_offset, String::TWO_BYTE_ENCODING); Node* const adjusted_search_ptr = PointerToStringDataAtIndex( search_ptr, search_offset, String::ONE_BYTE_ENCODING); Node* const result = CallSearchStringRaw<twobyte_t, onebyte_t>( adjusted_subject_ptr, subject_length, adjusted_search_ptr, search_length, start_position); f_return(SmiTag(result)); } BIND(&two_two); { Node* const adjusted_subject_ptr = PointerToStringDataAtIndex( subject_ptr, subject_offset, String::TWO_BYTE_ENCODING); Node* const adjusted_search_ptr = PointerToStringDataAtIndex( search_ptr, search_offset, String::TWO_BYTE_ENCODING); Node* const result = CallSearchStringRaw<twobyte_t, twobyte_t>( adjusted_subject_ptr, subject_length, adjusted_search_ptr, search_length, start_position); f_return(SmiTag(result)); } BIND(&return_minus_1); f_return(SmiConstant(-1)); BIND(&return_zero); f_return(SmiConstant(0)); BIND(&zero_length_needle); { Comment("0-length search_string"); f_return(SmiTag(IntPtrMin(subject_length, start_position))); } BIND(&call_runtime_unchecked); { // Simplified version of the runtime call where the types of the arguments // are already known due to type checks in this stub. Comment("Call Runtime Unchecked"); Node* result = CallRuntime(Runtime::kStringIndexOfUnchecked, NoContextConstant(), subject_string, search_string, position); f_return(result); } } // ES6 String.prototype.indexOf(searchString [, position]) // #sec-string.prototype.indexof // Unchecked helper for builtins lowering. TF_BUILTIN(StringIndexOf, StringBuiltinsAssembler) { Node* receiver = Parameter(Descriptor::kReceiver); Node* search_string = Parameter(Descriptor::kSearchString); Node* position = Parameter(Descriptor::kPosition); StringIndexOf(receiver, search_string, position, [this](Node* result) { this->Return(result); }); } // ES6 String.prototype.includes(searchString [, position]) // #sec-string.prototype.includes TF_BUILTIN(StringPrototypeIncludes, StringIncludesIndexOfAssembler) { Generate(kIncludes); } // ES6 String.prototype.indexOf(searchString [, position]) // #sec-string.prototype.indexof TF_BUILTIN(StringPrototypeIndexOf, StringIncludesIndexOfAssembler) { Generate(kIndexOf); } void StringIncludesIndexOfAssembler::Generate(SearchVariant variant) { // TODO(ishell): use constants from Descriptor once the JSFunction linkage // arguments are reordered. Node* argc = Parameter(BuiltinDescriptor::kArgumentsCount); Node* const context = Parameter(BuiltinDescriptor::kContext); CodeStubArguments arguments(this, ChangeInt32ToIntPtr(argc)); Node* const receiver = arguments.GetReceiver(); // From now on use word-size argc value. argc = arguments.GetLength(); VARIABLE(var_search_string, MachineRepresentation::kTagged); VARIABLE(var_position, MachineRepresentation::kTagged); Label argc_1(this), argc_2(this), call_runtime(this, Label::kDeferred), fast_path(this); GotoIf(IntPtrEqual(argc, IntPtrConstant(1)), &argc_1); GotoIf(IntPtrGreaterThan(argc, IntPtrConstant(1)), &argc_2); { Comment("0 Argument case"); CSA_ASSERT(this, IntPtrEqual(argc, IntPtrConstant(0))); Node* const undefined = UndefinedConstant(); var_search_string.Bind(undefined); var_position.Bind(undefined); Goto(&call_runtime); } BIND(&argc_1); { Comment("1 Argument case"); var_search_string.Bind(arguments.AtIndex(0)); var_position.Bind(SmiConstant(0)); Goto(&fast_path); } BIND(&argc_2); { Comment("2 Argument case"); var_search_string.Bind(arguments.AtIndex(0)); var_position.Bind(arguments.AtIndex(1)); GotoIfNot(TaggedIsSmi(var_position.value()), &call_runtime); Goto(&fast_path); } BIND(&fast_path); { Comment("Fast Path"); Node* const search = var_search_string.value(); Node* const position = var_position.value(); GotoIf(TaggedIsSmi(receiver), &call_runtime); GotoIf(TaggedIsSmi(search), &call_runtime); GotoIfNot(IsString(receiver), &call_runtime); GotoIfNot(IsString(search), &call_runtime); StringIndexOf(receiver, search, position, [&](Node* result) { CSA_ASSERT(this, TaggedIsSmi(result)); arguments.PopAndReturn((variant == kIndexOf) ? result : SelectBooleanConstant(SmiGreaterThanOrEqual( result, SmiConstant(0)))); }); } BIND(&call_runtime); { Comment("Call Runtime"); Runtime::FunctionId runtime = variant == kIndexOf ? Runtime::kStringIndexOf : Runtime::kStringIncludes; Node* const result = CallRuntime(runtime, context, receiver, var_search_string.value(), var_position.value()); arguments.PopAndReturn(result); } } compiler::Node* StringBuiltinsAssembler::IsNullOrUndefined(Node* const value) { return Word32Or(IsUndefined(value), IsNull(value)); } void StringBuiltinsAssembler::RequireObjectCoercible(Node* const context, Node* const value, const char* method_name) { Label out(this), throw_exception(this, Label::kDeferred); Branch(IsNullOrUndefined(value), &throw_exception, &out); BIND(&throw_exception); TailCallRuntime(Runtime::kThrowCalledOnNullOrUndefined, context, StringConstant(method_name)); BIND(&out); } void StringBuiltinsAssembler::MaybeCallFunctionAtSymbol( Node* const context, Node* const object, Node* const maybe_string, Handle<Symbol> symbol, const NodeFunction0& regexp_call, const NodeFunction1& generic_call, CodeStubArguments* args) { Label out(this); // Smis definitely don't have an attached symbol. GotoIf(TaggedIsSmi(object), &out); Node* const object_map = LoadMap(object); // Skip the slow lookup for Strings. { Label next(this); GotoIfNot(IsStringInstanceType(LoadMapInstanceType(object_map)), &next); Node* const native_context = LoadNativeContext(context); Node* const initial_proto_initial_map = LoadContextElement( native_context, Context::STRING_FUNCTION_PROTOTYPE_MAP_INDEX); Node* const string_fun = LoadContextElement(native_context, Context::STRING_FUNCTION_INDEX); Node* const initial_map = LoadObjectField(string_fun, JSFunction::kPrototypeOrInitialMapOffset); Node* const proto_map = LoadMap(CAST(LoadMapPrototype(initial_map))); Branch(WordEqual(proto_map, initial_proto_initial_map), &out, &next); BIND(&next); } // Take the fast path for RegExps. // There's two conditions: {object} needs to be a fast regexp, and // {maybe_string} must be a string (we can't call ToString on the fast path // since it may mutate {object}). { Label stub_call(this), slow_lookup(this); GotoIf(TaggedIsSmi(maybe_string), &slow_lookup); GotoIfNot(IsString(maybe_string), &slow_lookup); RegExpBuiltinsAssembler regexp_asm(state()); regexp_asm.BranchIfFastRegExp(context, object, object_map, &stub_call, &slow_lookup); BIND(&stub_call); // TODO(jgruber): Add a no-JS scope once it exists. Node* const result = regexp_call(); if (args == nullptr) { Return(result); } else { args->PopAndReturn(result); } BIND(&slow_lookup); } GotoIf(IsNullOrUndefined(object), &out); // Fall back to a slow lookup of {object[symbol]}. // // The spec uses GetMethod({object}, {symbol}), which has a few quirks: // * null values are turned into undefined, and // * an exception is thrown if the value is not undefined, null, or callable. // We handle the former by jumping to {out} for null values as well, while // the latter is already handled by the Call({maybe_func}) operation. Node* const maybe_func = GetProperty(context, object, symbol); GotoIf(IsUndefined(maybe_func), &out); GotoIf(IsNull(maybe_func), &out); // Attempt to call the function. Node* const result = generic_call(maybe_func); if (args == nullptr) { Return(result); } else { args->PopAndReturn(result); } BIND(&out); } compiler::Node* StringBuiltinsAssembler::IndexOfDollarChar(Node* const context, Node* const string) { CSA_ASSERT(this, IsString(string)); Node* const dollar_string = HeapConstant( isolate()->factory()->LookupSingleCharacterStringFromCode('$')); Node* const dollar_ix = CallBuiltin(Builtins::kStringIndexOf, context, string, dollar_string, SmiConstant(0)); CSA_ASSERT(this, TaggedIsSmi(dollar_ix)); return dollar_ix; } compiler::Node* StringBuiltinsAssembler::GetSubstitution( Node* context, Node* subject_string, Node* match_start_index, Node* match_end_index, Node* replace_string) { CSA_ASSERT(this, IsString(subject_string)); CSA_ASSERT(this, IsString(replace_string)); CSA_ASSERT(this, TaggedIsPositiveSmi(match_start_index)); CSA_ASSERT(this, TaggedIsPositiveSmi(match_end_index)); VARIABLE(var_result, MachineRepresentation::kTagged, replace_string); Label runtime(this), out(this); // In this primitive implementation we simply look for the next '$' char in // {replace_string}. If it doesn't exist, we can simply return // {replace_string} itself. If it does, then we delegate to // String::GetSubstitution, passing in the index of the first '$' to avoid // repeated scanning work. // TODO(jgruber): Possibly extend this in the future to handle more complex // cases without runtime calls. Node* const dollar_index = IndexOfDollarChar(context, replace_string); Branch(SmiIsNegative(dollar_index), &out, &runtime); BIND(&runtime); { CSA_ASSERT(this, TaggedIsPositiveSmi(dollar_index)); Callable substring_callable = CodeFactory::SubString(isolate()); Node* const matched = CallStub(substring_callable, context, subject_string, match_start_index, match_end_index); Node* const replacement_string = CallRuntime(Runtime::kGetSubstitution, context, matched, subject_string, match_start_index, replace_string, dollar_index); var_result.Bind(replacement_string); Goto(&out); } BIND(&out); return var_result.value(); } // ES6 #sec-string.prototype.replace TF_BUILTIN(StringPrototypeReplace, StringBuiltinsAssembler) { Label out(this); Node* const receiver = Parameter(Descriptor::kReceiver); Node* const search = Parameter(Descriptor::kSearch); Node* const replace = Parameter(Descriptor::kReplace); Node* const context = Parameter(Descriptor::kContext); Node* const smi_zero = SmiConstant(0); RequireObjectCoercible(context, receiver, "String.prototype.replace"); // Redirect to replacer method if {search[@@replace]} is not undefined. MaybeCallFunctionAtSymbol( context, search, receiver, isolate()->factory()->replace_symbol(), [=]() { return CallBuiltin(Builtins::kRegExpReplace, context, search, receiver, replace); }, [=](Node* fn) { Callable call_callable = CodeFactory::Call(isolate()); return CallJS(call_callable, context, fn, search, receiver, replace); }); // Convert {receiver} and {search} to strings. Node* const subject_string = ToString_Inline(context, receiver); Node* const search_string = ToString_Inline(context, search); Node* const subject_length = LoadStringLength(subject_string); Node* const search_length = LoadStringLength(search_string); // Fast-path single-char {search}, long cons {receiver}, and simple string // {replace}. { Label next(this); GotoIfNot(SmiEqual(search_length, SmiConstant(1)), &next); GotoIfNot(SmiGreaterThan(subject_length, SmiConstant(0xFF)), &next); GotoIf(TaggedIsSmi(replace), &next); GotoIfNot(IsString(replace), &next); Node* const subject_instance_type = LoadInstanceType(subject_string); GotoIfNot(IsConsStringInstanceType(subject_instance_type), &next); GotoIf(TaggedIsPositiveSmi(IndexOfDollarChar(context, replace)), &next); // Searching by traversing a cons string tree and replace with cons of // slices works only when the replaced string is a single character, being // replaced by a simple string and only pays off for long strings. // TODO(jgruber): Reevaluate if this is still beneficial. // TODO(jgruber): TailCallRuntime when it correctly handles adapter frames. Return(CallRuntime(Runtime::kStringReplaceOneCharWithString, context, subject_string, search_string, replace)); BIND(&next); } // TODO(jgruber): Extend StringIndexOf to handle two-byte strings and // longer substrings - we can handle up to 8 chars (one-byte) / 4 chars // (2-byte). Node* const match_start_index = CallBuiltin(Builtins::kStringIndexOf, context, subject_string, search_string, smi_zero); CSA_ASSERT(this, TaggedIsSmi(match_start_index)); // Early exit if no match found. { Label next(this), return_subject(this); GotoIfNot(SmiIsNegative(match_start_index), &next); // The spec requires to perform ToString(replace) if the {replace} is not // callable even if we are going to exit here. // Since ToString() being applied to Smi does not have side effects for // numbers we can skip it. GotoIf(TaggedIsSmi(replace), &return_subject); GotoIf(IsCallableMap(LoadMap(replace)), &return_subject); // TODO(jgruber): Could introduce ToStringSideeffectsStub which only // performs observable parts of ToString. ToString_Inline(context, replace); Goto(&return_subject); BIND(&return_subject); Return(subject_string); BIND(&next); } Node* const match_end_index = SmiAdd(match_start_index, search_length); Callable substring_callable = CodeFactory::SubString(isolate()); Callable stringadd_callable = CodeFactory::StringAdd(isolate(), STRING_ADD_CHECK_NONE, NOT_TENURED); VARIABLE(var_result, MachineRepresentation::kTagged, EmptyStringConstant()); // Compute the prefix. { Label next(this); GotoIf(SmiEqual(match_start_index, smi_zero), &next); Node* const prefix = CallStub(substring_callable, context, subject_string, smi_zero, match_start_index); var_result.Bind(prefix); Goto(&next); BIND(&next); } // Compute the string to replace with. Label if_iscallablereplace(this), if_notcallablereplace(this); GotoIf(TaggedIsSmi(replace), &if_notcallablereplace); Branch(IsCallableMap(LoadMap(replace)), &if_iscallablereplace, &if_notcallablereplace); BIND(&if_iscallablereplace); { Callable call_callable = CodeFactory::Call(isolate()); Node* const replacement = CallJS(call_callable, context, replace, UndefinedConstant(), search_string, match_start_index, subject_string); Node* const replacement_string = ToString_Inline(context, replacement); var_result.Bind(CallStub(stringadd_callable, context, var_result.value(), replacement_string)); Goto(&out); } BIND(&if_notcallablereplace); { Node* const replace_string = ToString_Inline(context, replace); Node* const replacement = GetSubstitution(context, subject_string, match_start_index, match_end_index, replace_string); var_result.Bind( CallStub(stringadd_callable, context, var_result.value(), replacement)); Goto(&out); } BIND(&out); { Node* const suffix = CallStub(substring_callable, context, subject_string, match_end_index, subject_length); Node* const result = CallStub(stringadd_callable, context, var_result.value(), suffix); Return(result); } } // ES6 section 21.1.3.18 String.prototype.slice ( start, end ) TF_BUILTIN(StringPrototypeSlice, StringBuiltinsAssembler) { Label out(this); VARIABLE(var_start, MachineRepresentation::kTagged); VARIABLE(var_end, MachineRepresentation::kTagged); const int kStart = 0; const int kEnd = 1; Node* argc = ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount)); CodeStubArguments args(this, argc); Node* const receiver = args.GetReceiver(); Node* const start = args.GetOptionalArgumentValue(kStart); Node* const end = args.GetOptionalArgumentValue(kEnd); Node* const context = Parameter(BuiltinDescriptor::kContext); TNode<Smi> const smi_zero = SmiConstant(0); // 1. Let O be ? RequireObjectCoercible(this value). RequireObjectCoercible(context, receiver, "String.prototype.slice"); // 2. Let S be ? ToString(O). Node* const subject_string = CallBuiltin(Builtins::kToString, context, receiver); // 3. Let len be the number of elements in S. Node* const length = LoadStringLength(subject_string); // Conversions and bounds-checks for {start}. ConvertAndBoundsCheckStartArgument(context, &var_start, start, length); // 5. If end is undefined, let intEnd be len; var_end.Bind(length); GotoIf(WordEqual(end, UndefinedConstant()), &out); // else let intEnd be ? ToInteger(end). Node* const end_int = ToInteger(context, end, CodeStubAssembler::kTruncateMinusZero); // 7. If intEnd < 0, let to be max(len + intEnd, 0); // otherwise let to be min(intEnd, len). Label if_issmi(this), if_isheapnumber(this, Label::kDeferred); Branch(TaggedIsSmi(end_int), &if_issmi, &if_isheapnumber); BIND(&if_issmi); { Node* const length_plus_end = SmiAdd(length, end_int); var_end.Bind(Select(SmiLessThan(end_int, smi_zero), [&] { return SmiMax(length_plus_end, smi_zero); }, [&] { return SmiMin(length, end_int); }, MachineRepresentation::kTagged)); Goto(&out); } BIND(&if_isheapnumber); { // If {end} is a heap number, it is definitely out of bounds. If it is // negative, {int_end} = max({length} + {int_end}),0) = 0'. If it is // positive, set {int_end} to {length} which ultimately results in // returning an empty string. Node* const float_zero = Float64Constant(0.); Node* const end_float = LoadHeapNumberValue(end_int); var_end.Bind(SelectTaggedConstant<Smi>( Float64LessThan(end_float, float_zero), smi_zero, length)); Goto(&out); } Label return_emptystring(this); BIND(&out); { GotoIf(SmiLessThanOrEqual(var_end.value(), var_start.value()), &return_emptystring); Node* const result = SubString(context, subject_string, var_start.value(), var_end.value(), SubStringFlags::FROM_TO_ARE_BOUNDED); args.PopAndReturn(result); } BIND(&return_emptystring); args.PopAndReturn(EmptyStringConstant()); } // ES6 section 21.1.3.19 String.prototype.split ( separator, limit ) TF_BUILTIN(StringPrototypeSplit, StringBuiltinsAssembler) { const int kSeparatorArg = 0; const int kLimitArg = 1; Node* const argc = ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount)); CodeStubArguments args(this, argc); Node* const receiver = args.GetReceiver(); Node* const separator = args.GetOptionalArgumentValue(kSeparatorArg); Node* const limit = args.GetOptionalArgumentValue(kLimitArg); Node* const context = Parameter(BuiltinDescriptor::kContext); Node* const smi_zero = SmiConstant(0); RequireObjectCoercible(context, receiver, "String.prototype.split"); // Redirect to splitter method if {separator[@@split]} is not undefined. MaybeCallFunctionAtSymbol( context, separator, receiver, isolate()->factory()->split_symbol(), [=]() { return CallBuiltin(Builtins::kRegExpSplit, context, separator, receiver, limit); }, [=](Node* fn) { Callable call_callable = CodeFactory::Call(isolate()); return CallJS(call_callable, context, fn, separator, receiver, limit); }, &args); // String and integer conversions. Node* const subject_string = ToString_Inline(context, receiver); Node* const limit_number = Select(IsUndefined(limit), [=]() { return NumberConstant(kMaxUInt32); }, [=]() { return ToUint32(context, limit); }, MachineRepresentation::kTagged); Node* const separator_string = ToString_Inline(context, separator); // Shortcut for {limit} == 0. { Label next(this); GotoIfNot(SmiEqual(limit_number, smi_zero), &next); const ElementsKind kind = PACKED_ELEMENTS; Node* const native_context = LoadNativeContext(context); Node* const array_map = LoadJSArrayElementsMap(kind, native_context); Node* const length = smi_zero; Node* const capacity = IntPtrConstant(0); Node* const result = AllocateJSArray(kind, array_map, capacity, length); args.PopAndReturn(result); BIND(&next); } // ECMA-262 says that if {separator} is undefined, the result should // be an array of size 1 containing the entire string. { Label next(this); GotoIfNot(IsUndefined(separator), &next); const ElementsKind kind = PACKED_ELEMENTS; Node* const native_context = LoadNativeContext(context); Node* const array_map = LoadJSArrayElementsMap(kind, native_context); Node* const length = SmiConstant(1); Node* const capacity = IntPtrConstant(1); Node* const result = AllocateJSArray(kind, array_map, capacity, length); Node* const fixed_array = LoadElements(result); StoreFixedArrayElement(fixed_array, 0, subject_string); args.PopAndReturn(result); BIND(&next); } // If the separator string is empty then return the elements in the subject. { Label next(this); GotoIfNot(SmiEqual(LoadStringLength(separator_string), smi_zero), &next); Node* const result = CallRuntime(Runtime::kStringToArray, context, subject_string, limit_number); args.PopAndReturn(result); BIND(&next); } Node* const result = CallRuntime(Runtime::kStringSplit, context, subject_string, separator_string, limit_number); args.PopAndReturn(result); } // ES6 #sec-string.prototype.substr TF_BUILTIN(StringPrototypeSubstr, StringBuiltinsAssembler) { const int kStartArg = 0; const int kLengthArg = 1; Node* const argc = ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount)); CodeStubArguments args(this, argc); Node* const receiver = args.GetReceiver(); Node* const start = args.GetOptionalArgumentValue(kStartArg); Node* const length = args.GetOptionalArgumentValue(kLengthArg); Node* const context = Parameter(BuiltinDescriptor::kContext); Label out(this); VARIABLE(var_start, MachineRepresentation::kTagged); VARIABLE(var_length, MachineRepresentation::kTagged); Node* const zero = SmiConstant(0); // Check that {receiver} is coercible to Object and convert it to a String. Node* const string = ToThisString(context, receiver, "String.prototype.substr"); Node* const string_length = LoadStringLength(string); // Conversions and bounds-checks for {start}. ConvertAndBoundsCheckStartArgument(context, &var_start, start, string_length); // Conversions and bounds-checks for {length}. Label if_issmi(this), if_isheapnumber(this, Label::kDeferred); // Default to {string_length} if {length} is undefined. { Label if_isundefined(this, Label::kDeferred), if_isnotundefined(this); Branch(WordEqual(length, UndefinedConstant()), &if_isundefined, &if_isnotundefined); BIND(&if_isundefined); var_length.Bind(string_length); Goto(&if_issmi); BIND(&if_isnotundefined); var_length.Bind( ToInteger(context, length, CodeStubAssembler::kTruncateMinusZero)); } Branch(TaggedIsSmi(var_length.value()), &if_issmi, &if_isheapnumber); // Set {length} to min(max({length}, 0), {string_length} - {start} BIND(&if_issmi); { Node* const positive_length = SmiMax(var_length.value(), zero); Node* const minimal_length = SmiSub(string_length, var_start.value()); var_length.Bind(SmiMin(positive_length, minimal_length)); GotoIfNot(SmiLessThanOrEqual(var_length.value(), zero), &out); args.PopAndReturn(EmptyStringConstant()); } BIND(&if_isheapnumber); { // If {length} is a heap number, it is definitely out of bounds. There are // two cases according to the spec: if it is negative, "" is returned; if // it is positive, then length is set to {string_length} - {start}. CSA_ASSERT(this, IsHeapNumber(var_length.value())); Label if_isnegative(this), if_ispositive(this); Node* const float_zero = Float64Constant(0.); Node* const length_float = LoadHeapNumberValue(var_length.value()); Branch(Float64LessThan(length_float, float_zero), &if_isnegative, &if_ispositive); BIND(&if_isnegative); args.PopAndReturn(EmptyStringConstant()); BIND(&if_ispositive); { var_length.Bind(SmiSub(string_length, var_start.value())); GotoIfNot(SmiLessThanOrEqual(var_length.value(), zero), &out); args.PopAndReturn(EmptyStringConstant()); } } BIND(&out); { Node* const end = SmiAdd(var_start.value(), var_length.value()); Node* const result = SubString(context, string, var_start.value(), end); args.PopAndReturn(result); } } TNode<Smi> StringBuiltinsAssembler::ToSmiBetweenZeroAnd( SloppyTNode<Context> context, SloppyTNode<Object> value, SloppyTNode<Smi> limit) { Label out(this); TVARIABLE(Smi, var_result); TNode<Object> const value_int = this->ToInteger(context, value, CodeStubAssembler::kTruncateMinusZero); Label if_issmi(this), if_isnotsmi(this, Label::kDeferred); Branch(TaggedIsSmi(value_int), &if_issmi, &if_isnotsmi); BIND(&if_issmi); { Label if_isinbounds(this), if_isoutofbounds(this, Label::kDeferred); Branch(SmiAbove(value_int, limit), &if_isoutofbounds, &if_isinbounds); BIND(&if_isinbounds); { var_result = CAST(value_int); Goto(&out); } BIND(&if_isoutofbounds); { TNode<Smi> const zero = SmiConstant(0); var_result = SelectTaggedConstant(SmiLessThan(value_int, zero), zero, limit); Goto(&out); } } BIND(&if_isnotsmi); { // {value} is a heap number - in this case, it is definitely out of bounds. TNode<HeapNumber> value_int_hn = CAST(value_int); TNode<Float64T> const float_zero = Float64Constant(0.); TNode<Smi> const smi_zero = SmiConstant(0); TNode<Float64T> const value_float = LoadHeapNumberValue(value_int_hn); var_result = SelectTaggedConstant(Float64LessThan(value_float, float_zero), smi_zero, limit); Goto(&out); } BIND(&out); return var_result; } // ES6 #sec-string.prototype.substring TF_BUILTIN(StringPrototypeSubstring, StringBuiltinsAssembler) { const int kStartArg = 0; const int kEndArg = 1; Node* const argc = ChangeInt32ToIntPtr(Parameter(BuiltinDescriptor::kArgumentsCount)); CodeStubArguments args(this, argc); Node* const receiver = args.GetReceiver(); Node* const start = args.GetOptionalArgumentValue(kStartArg); Node* const end = args.GetOptionalArgumentValue(kEndArg); Node* const context = Parameter(BuiltinDescriptor::kContext); Label out(this); VARIABLE(var_start, MachineRepresentation::kTagged); VARIABLE(var_end, MachineRepresentation::kTagged); // Check that {receiver} is coercible to Object and convert it to a String. Node* const string = ToThisString(context, receiver, "String.prototype.substring"); Node* const length = LoadStringLength(string); // Conversion and bounds-checks for {start}. var_start.Bind(ToSmiBetweenZeroAnd(context, start, length)); // Conversion and bounds-checks for {end}. { var_end.Bind(length); GotoIf(WordEqual(end, UndefinedConstant()), &out); var_end.Bind(ToSmiBetweenZeroAnd(context, end, length)); Label if_endislessthanstart(this); Branch(SmiLessThan(var_end.value(), var_start.value()), &if_endislessthanstart, &out); BIND(&if_endislessthanstart); { Node* const tmp = var_end.value(); var_end.Bind(var_start.value()); var_start.Bind(tmp); Goto(&out); } } BIND(&out); { Node* result = SubString(context, string, var_start.value(), var_end.value()); args.PopAndReturn(result); } } // ES6 #sec-string.prototype.tostring TF_BUILTIN(StringPrototypeToString, CodeStubAssembler) { Node* context = Parameter(Descriptor::kContext); Node* receiver = Parameter(Descriptor::kReceiver); Node* result = ToThisValue(context, receiver, PrimitiveType::kString, "String.prototype.toString"); Return(result); } // ES6 #sec-string.prototype.valueof TF_BUILTIN(StringPrototypeValueOf, CodeStubAssembler) { Node* context = Parameter(Descriptor::kContext); Node* receiver = Parameter(Descriptor::kReceiver); Node* result = ToThisValue(context, receiver, PrimitiveType::kString, "String.prototype.valueOf"); Return(result); } TF_BUILTIN(StringPrototypeIterator, CodeStubAssembler) { Node* context = Parameter(Descriptor::kContext); Node* receiver = Parameter(Descriptor::kReceiver); Node* string = ToThisString(context, receiver, "String.prototype[Symbol.iterator]"); Node* native_context = LoadNativeContext(context); Node* map = LoadContextElement(native_context, Context::STRING_ITERATOR_MAP_INDEX); Node* iterator = Allocate(JSStringIterator::kSize); StoreMapNoWriteBarrier(iterator, map); StoreObjectFieldRoot(iterator, JSValue::kPropertiesOrHashOffset, Heap::kEmptyFixedArrayRootIndex); StoreObjectFieldRoot(iterator, JSObject::kElementsOffset, Heap::kEmptyFixedArrayRootIndex); StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kStringOffset, string); Node* index = SmiConstant(0); StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kNextIndexOffset, index); Return(iterator); } // Return the |word32| codepoint at {index}. Supports SeqStrings and // ExternalStrings. TNode<Uint32T> StringBuiltinsAssembler::LoadSurrogatePairAt( SloppyTNode<String> string, SloppyTNode<Smi> length, SloppyTNode<Smi> index, UnicodeEncoding encoding) { Label handle_surrogate_pair(this), return_result(this); TVARIABLE(Uint32T, var_result); TVARIABLE(Uint32T, var_trail); var_result = StringCharCodeAt(string, index); var_trail = Unsigned(Int32Constant(0)); GotoIf(Word32NotEqual(Word32And(var_result, Int32Constant(0xFC00)), Int32Constant(0xD800)), &return_result); TNode<Smi> next_index = SmiAdd(index, SmiConstant(1)); GotoIfNot(SmiLessThan(next_index, length), &return_result); var_trail = StringCharCodeAt(string, next_index); Branch(Word32Equal(Word32And(var_trail, Int32Constant(0xFC00)), Int32Constant(0xDC00)), &handle_surrogate_pair, &return_result); BIND(&handle_surrogate_pair); { TNode<Uint32T> lead = var_result; TNode<Uint32T> trail = var_trail; // Check that this path is only taken if a surrogate pair is found CSA_SLOW_ASSERT(this, Uint32GreaterThanOrEqual(lead, Int32Constant(0xD800))); CSA_SLOW_ASSERT(this, Uint32LessThan(lead, Int32Constant(0xDC00))); CSA_SLOW_ASSERT(this, Uint32GreaterThanOrEqual(trail, Int32Constant(0xDC00))); CSA_SLOW_ASSERT(this, Uint32LessThan(trail, Int32Constant(0xE000))); switch (encoding) { case UnicodeEncoding::UTF16: var_result = Unsigned(Word32Or( // Need to swap the order for big-endian platforms #if V8_TARGET_BIG_ENDIAN Word32Shl(lead, Int32Constant(16)), trail)); #else Word32Shl(trail, Int32Constant(16)), lead)); #endif break; case UnicodeEncoding::UTF32: { // Convert UTF16 surrogate pair into |word32| code point, encoded as // UTF32. TNode<Int32T> surrogate_offset = Int32Constant(0x10000 - (0xD800 << 10) - 0xDC00); // (lead << 10) + trail + SURROGATE_OFFSET var_result = Unsigned(Int32Add(Word32Shl(lead, Int32Constant(10)), Int32Add(trail, surrogate_offset))); break; } } Goto(&return_result); } BIND(&return_result); return var_result; } // ES6 #sec-%stringiteratorprototype%.next TF_BUILTIN(StringIteratorPrototypeNext, StringBuiltinsAssembler) { VARIABLE(var_value, MachineRepresentation::kTagged); VARIABLE(var_done, MachineRepresentation::kTagged); var_value.Bind(UndefinedConstant()); var_done.Bind(BooleanConstant(true)); Label throw_bad_receiver(this), next_codepoint(this), return_result(this); Node* context = Parameter(Descriptor::kContext); Node* iterator = Parameter(Descriptor::kReceiver); GotoIf(TaggedIsSmi(iterator), &throw_bad_receiver); GotoIfNot(Word32Equal(LoadInstanceType(iterator), Int32Constant(JS_STRING_ITERATOR_TYPE)), &throw_bad_receiver); Node* string = LoadObjectField(iterator, JSStringIterator::kStringOffset); Node* position = LoadObjectField(iterator, JSStringIterator::kNextIndexOffset); Node* length = LoadObjectField(string, String::kLengthOffset); Branch(SmiLessThan(position, length), &next_codepoint, &return_result); BIND(&next_codepoint); { UnicodeEncoding encoding = UnicodeEncoding::UTF16; Node* ch = LoadSurrogatePairAt(string, length, position, encoding); Node* value = StringFromCodePoint(ch, encoding); var_value.Bind(value); Node* length = LoadObjectField(value, String::kLengthOffset); StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kNextIndexOffset, SmiAdd(position, length)); var_done.Bind(BooleanConstant(false)); Goto(&return_result); } BIND(&return_result); { Node* result = AllocateJSIteratorResult(context, var_value.value(), var_done.value()); Return(result); } BIND(&throw_bad_receiver); { // The {receiver} is not a valid JSGeneratorObject. CallRuntime(Runtime::kThrowIncompatibleMethodReceiver, context, StringConstant("String Iterator.prototype.next"), iterator); Unreachable(); } } } // namespace internal } // namespace v8
{ "language": "C++" }
// 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 "media/base/stream_parser_buffer.h" #include "base/logging.h" #include "media/base/buffers.h" namespace media { static bool HasNestedFadeOutPreroll( const std::vector<scoped_refptr<StreamParserBuffer> >& fade_out_preroll) { for (size_t i = 0; i < fade_out_preroll.size(); ++i) { if (!fade_out_preroll[i]->GetFadeOutPreroll().empty()) return true; } return false; } scoped_refptr<StreamParserBuffer> StreamParserBuffer::CreateEOSBuffer() { return make_scoped_refptr(new StreamParserBuffer(NULL, 0, NULL, 0, false, DemuxerStream::UNKNOWN, 0)); } scoped_refptr<StreamParserBuffer> StreamParserBuffer::CopyFrom( const uint8* data, int data_size, bool is_keyframe, Type type, TrackId track_id) { return make_scoped_refptr( new StreamParserBuffer(data, data_size, NULL, 0, is_keyframe, type, track_id)); } scoped_refptr<StreamParserBuffer> StreamParserBuffer::CopyFrom( const uint8* data, int data_size, const uint8* side_data, int side_data_size, bool is_keyframe, Type type, TrackId track_id) { return make_scoped_refptr( new StreamParserBuffer(data, data_size, side_data, side_data_size, is_keyframe, type, track_id)); } base::TimeDelta StreamParserBuffer::GetDecodeTimestamp() const { if (decode_timestamp_ == kNoTimestamp()) return timestamp(); return decode_timestamp_; } void StreamParserBuffer::SetDecodeTimestamp(const base::TimeDelta& timestamp) { decode_timestamp_ = timestamp; } StreamParserBuffer::StreamParserBuffer(const uint8* data, int data_size, const uint8* side_data, int side_data_size, bool is_keyframe, Type type, TrackId track_id) : DecoderBuffer(data, data_size, side_data, side_data_size), is_keyframe_(is_keyframe), decode_timestamp_(kNoTimestamp()), config_id_(kInvalidConfigId), type_(type), track_id_(track_id) { // TODO(scherkus): Should DataBuffer constructor accept a timestamp and // duration to force clients to set them? Today they end up being zero which // is both a common and valid value and could lead to bugs. if (data) { set_duration(kNoTimestamp()); } } StreamParserBuffer::~StreamParserBuffer() { } int StreamParserBuffer::GetConfigId() const { return config_id_; } void StreamParserBuffer::SetConfigId(int config_id) { config_id_ = config_id; } const std::vector<scoped_refptr<StreamParserBuffer> >& StreamParserBuffer::GetFadeOutPreroll() const { return fade_out_preroll_; } void StreamParserBuffer::SetFadeOutPreroll( const std::vector<scoped_refptr<StreamParserBuffer> >& fade_out_preroll) { DCHECK(!HasNestedFadeOutPreroll(fade_out_preroll)); fade_out_preroll_ = fade_out_preroll; } } // namespace media
{ "language": "C++" }
//===- ToyCombine.cpp - Toy High Level Optimizer --------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file implements a set of simple combiners for optimizing operations in // the Toy dialect. // //===----------------------------------------------------------------------===// #include "mlir/IR/Matchers.h" #include "mlir/IR/PatternMatch.h" #include "toy/Dialect.h" #include <numeric> using namespace mlir; using namespace toy; namespace { /// Include the patterns defined in the Declarative Rewrite framework. #include "ToyCombine.inc" } // end anonymous namespace /// Fold simple cast operations that return the same type as the input. OpFoldResult CastOp::fold(ArrayRef<Attribute> operands) { return mlir::impl::foldCastOp(*this); } /// Fold constants. OpFoldResult ConstantOp::fold(ArrayRef<Attribute> operands) { return value(); } /// Fold struct constants. OpFoldResult StructConstantOp::fold(ArrayRef<Attribute> operands) { return value(); } /// Fold simple struct access operations that access into a constant. OpFoldResult StructAccessOp::fold(ArrayRef<Attribute> operands) { auto structAttr = operands.front().dyn_cast_or_null<mlir::ArrayAttr>(); if (!structAttr) return nullptr; size_t elementIndex = index(); return structAttr[elementIndex]; } /// This is an example of a c++ rewrite pattern for the TransposeOp. It /// optimizes the following scenario: transpose(transpose(x)) -> x struct SimplifyRedundantTranspose : public mlir::OpRewritePattern<TransposeOp> { /// We register this pattern to match every toy.transpose in the IR. /// The "benefit" is used by the framework to order the patterns and process /// them in order of profitability. SimplifyRedundantTranspose(mlir::MLIRContext *context) : OpRewritePattern<TransposeOp>(context, /*benefit=*/1) {} /// This method attempts to match a pattern and rewrite it. The rewriter /// argument is the orchestrator of the sequence of rewrites. The pattern is /// expected to interact with it to perform any changes to the IR from here. mlir::LogicalResult matchAndRewrite(TransposeOp op, mlir::PatternRewriter &rewriter) const override { // Look through the input of the current transpose. mlir::Value transposeInput = op.getOperand(); TransposeOp transposeInputOp = transposeInput.getDefiningOp<TransposeOp>(); // Input defined by another transpose? If not, no match. if (!transposeInputOp) return failure(); // Otherwise, we have a redundant transpose. Use the rewriter. rewriter.replaceOp(op, {transposeInputOp.getOperand()}); return success(); } }; /// Register our patterns as "canonicalization" patterns on the TransposeOp so /// that they can be picked up by the Canonicalization framework. void TransposeOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<SimplifyRedundantTranspose>(context); } /// Register our patterns as "canonicalization" patterns on the ReshapeOp so /// that they can be picked up by the Canonicalization framework. void ReshapeOp::getCanonicalizationPatterns(OwningRewritePatternList &results, MLIRContext *context) { results.insert<ReshapeReshapeOptPattern, RedundantReshapeOptPattern, FoldConstantReshapeOptPattern>(context); }
{ "language": "C++" }
// Copyright 2013 the V8 project 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 "src/libplatform/default-platform.h" #include <algorithm> #include <queue> #include "include/libplatform/libplatform.h" #include "src/base/debug/stack_trace.h" #include "src/base/logging.h" #include "src/base/page-allocator.h" #include "src/base/platform/platform.h" #include "src/base/platform/time.h" #include "src/base/sys-info.h" #include "src/libplatform/default-foreground-task-runner.h" #include "src/libplatform/default-job.h" #include "src/libplatform/default-worker-threads-task-runner.h" namespace v8 { namespace platform { namespace { void PrintStackTrace() { v8::base::debug::StackTrace trace; trace.Print(); // Avoid dumping duplicate stack trace on abort signal. v8::base::debug::DisableSignalStackDump(); } } // namespace std::unique_ptr<v8::Platform> NewDefaultPlatform( int thread_pool_size, IdleTaskSupport idle_task_support, InProcessStackDumping in_process_stack_dumping, std::unique_ptr<v8::TracingController> tracing_controller) { if (in_process_stack_dumping == InProcessStackDumping::kEnabled) { v8::base::debug::EnableInProcessStackDumping(); } auto platform = std::make_unique<DefaultPlatform>( thread_pool_size, idle_task_support, std::move(tracing_controller)); platform->EnsureBackgroundTaskRunnerInitialized(); return platform; } V8_PLATFORM_EXPORT std::unique_ptr<JobHandle> NewDefaultJobHandle( Platform* platform, TaskPriority priority, std::unique_ptr<JobTask> job_task, size_t num_worker_threads) { return std::make_unique<DefaultJobHandle>(std::make_shared<DefaultJobState>( platform, std::move(job_task), priority, num_worker_threads)); } bool PumpMessageLoop(v8::Platform* platform, v8::Isolate* isolate, MessageLoopBehavior behavior) { return static_cast<DefaultPlatform*>(platform)->PumpMessageLoop(isolate, behavior); } void RunIdleTasks(v8::Platform* platform, v8::Isolate* isolate, double idle_time_in_seconds) { static_cast<DefaultPlatform*>(platform)->RunIdleTasks(isolate, idle_time_in_seconds); } void SetTracingController( v8::Platform* platform, v8::platform::tracing::TracingController* tracing_controller) { static_cast<DefaultPlatform*>(platform)->SetTracingController( std::unique_ptr<v8::TracingController>(tracing_controller)); } void NotifyIsolateShutdown(v8::Platform* platform, Isolate* isolate) { static_cast<DefaultPlatform*>(platform)->NotifyIsolateShutdown(isolate); } namespace { constexpr int kMaxThreadPoolSize = 16; int GetActualThreadPoolSize(int thread_pool_size) { DCHECK_GE(thread_pool_size, 0); if (thread_pool_size < 1) { thread_pool_size = base::SysInfo::NumberOfProcessors() - 1; } return std::max(std::min(thread_pool_size, kMaxThreadPoolSize), 1); } } // namespace DefaultPlatform::DefaultPlatform( int thread_pool_size, IdleTaskSupport idle_task_support, std::unique_ptr<v8::TracingController> tracing_controller) : thread_pool_size_(GetActualThreadPoolSize(thread_pool_size)), idle_task_support_(idle_task_support), tracing_controller_(std::move(tracing_controller)), page_allocator_(std::make_unique<v8::base::PageAllocator>()) { if (!tracing_controller_) { tracing::TracingController* controller = new tracing::TracingController(); #if !defined(V8_USE_PERFETTO) controller->Initialize(nullptr); #endif tracing_controller_.reset(controller); } } DefaultPlatform::~DefaultPlatform() { base::MutexGuard guard(&lock_); if (worker_threads_task_runner_) worker_threads_task_runner_->Terminate(); for (const auto& it : foreground_task_runner_map_) { it.second->Terminate(); } } namespace { double DefaultTimeFunction() { return base::TimeTicks::HighResolutionNow().ToInternalValue() / static_cast<double>(base::Time::kMicrosecondsPerSecond); } } // namespace void DefaultPlatform::EnsureBackgroundTaskRunnerInitialized() { base::MutexGuard guard(&lock_); if (!worker_threads_task_runner_) { worker_threads_task_runner_ = std::make_shared<DefaultWorkerThreadsTaskRunner>( thread_pool_size_, time_function_for_testing_ ? time_function_for_testing_ : DefaultTimeFunction); } } void DefaultPlatform::SetTimeFunctionForTesting( DefaultPlatform::TimeFunction time_function) { base::MutexGuard guard(&lock_); time_function_for_testing_ = time_function; // The time function has to be right after the construction of the platform. DCHECK(foreground_task_runner_map_.empty()); } bool DefaultPlatform::PumpMessageLoop(v8::Isolate* isolate, MessageLoopBehavior wait_for_work) { bool failed_result = wait_for_work == MessageLoopBehavior::kWaitForWork; std::shared_ptr<DefaultForegroundTaskRunner> task_runner; { base::MutexGuard guard(&lock_); auto it = foreground_task_runner_map_.find(isolate); if (it == foreground_task_runner_map_.end()) return failed_result; task_runner = it->second; } std::unique_ptr<Task> task = task_runner->PopTaskFromQueue(wait_for_work); if (!task) return failed_result; DefaultForegroundTaskRunner::RunTaskScope scope(task_runner); task->Run(); return true; } void DefaultPlatform::RunIdleTasks(v8::Isolate* isolate, double idle_time_in_seconds) { DCHECK_EQ(IdleTaskSupport::kEnabled, idle_task_support_); std::shared_ptr<DefaultForegroundTaskRunner> task_runner; { base::MutexGuard guard(&lock_); if (foreground_task_runner_map_.find(isolate) == foreground_task_runner_map_.end()) { return; } task_runner = foreground_task_runner_map_[isolate]; } double deadline_in_seconds = MonotonicallyIncreasingTime() + idle_time_in_seconds; while (deadline_in_seconds > MonotonicallyIncreasingTime()) { std::unique_ptr<IdleTask> task = task_runner->PopTaskFromIdleQueue(); if (!task) return; DefaultForegroundTaskRunner::RunTaskScope scope(task_runner); task->Run(deadline_in_seconds); } } std::shared_ptr<TaskRunner> DefaultPlatform::GetForegroundTaskRunner( v8::Isolate* isolate) { base::MutexGuard guard(&lock_); if (foreground_task_runner_map_.find(isolate) == foreground_task_runner_map_.end()) { foreground_task_runner_map_.insert(std::make_pair( isolate, std::make_shared<DefaultForegroundTaskRunner>( idle_task_support_, time_function_for_testing_ ? time_function_for_testing_ : DefaultTimeFunction))); } return foreground_task_runner_map_[isolate]; } void DefaultPlatform::CallOnWorkerThread(std::unique_ptr<Task> task) { EnsureBackgroundTaskRunnerInitialized(); worker_threads_task_runner_->PostTask(std::move(task)); } void DefaultPlatform::CallDelayedOnWorkerThread(std::unique_ptr<Task> task, double delay_in_seconds) { EnsureBackgroundTaskRunnerInitialized(); worker_threads_task_runner_->PostDelayedTask(std::move(task), delay_in_seconds); } bool DefaultPlatform::IdleTasksEnabled(Isolate* isolate) { return idle_task_support_ == IdleTaskSupport::kEnabled; } std::unique_ptr<JobHandle> DefaultPlatform::PostJob( TaskPriority priority, std::unique_ptr<JobTask> job_task) { size_t num_worker_threads = NumberOfWorkerThreads(); if (priority == TaskPriority::kBestEffort && num_worker_threads > 2) { num_worker_threads = 2; } return NewDefaultJobHandle(this, priority, std::move(job_task), num_worker_threads); } double DefaultPlatform::MonotonicallyIncreasingTime() { if (time_function_for_testing_) return time_function_for_testing_(); return DefaultTimeFunction(); } double DefaultPlatform::CurrentClockTimeMillis() { return base::OS::TimeCurrentMillis(); } TracingController* DefaultPlatform::GetTracingController() { return tracing_controller_.get(); } void DefaultPlatform::SetTracingController( std::unique_ptr<v8::TracingController> tracing_controller) { DCHECK_NOT_NULL(tracing_controller.get()); tracing_controller_ = std::move(tracing_controller); } int DefaultPlatform::NumberOfWorkerThreads() { return thread_pool_size_; } Platform::StackTracePrinter DefaultPlatform::GetStackTracePrinter() { return PrintStackTrace; } v8::PageAllocator* DefaultPlatform::GetPageAllocator() { return page_allocator_.get(); } void DefaultPlatform::NotifyIsolateShutdown(Isolate* isolate) { base::MutexGuard guard(&lock_); auto it = foreground_task_runner_map_.find(isolate); if (it != foreground_task_runner_map_.end()) { it->second->Terminate(); foreground_task_runner_map_.erase(it); } } } // namespace platform } // namespace v8
{ "language": "C++" }
/* * Copyright (c) [2019-2020] Huawei Technologies Co.,Ltd.All rights reserved. * * OpenArkCompiler is licensed under the Mulan PSL v1. * You can use this software according to the terms and conditions of the Mulan PSL v1. * You may obtain a copy of Mulan PSL v1 at: * * http://license.coscl.org.cn/MulanPSL * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR * FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v1 for more details. */ #include "ver_symbol.h" #include "bb.h" #include "me_ssa.h" #include "ssa_mir_nodes.h" namespace maple { VersionSt VersionStTable::dummyVST(0, 0, nullptr); void VersionSt::DumpDefStmt(const MIRModule*) const { if (version <= 0) { return; } switch (defType) { case kAssign: defStmt.assign->Dump(0); return; case kPhi: defStmt.phi->Dump(); return; case kMayDef: defStmt.mayDef->Dump(); return; case kMustDef: defStmt.mustDef->Dump(); return; default: ASSERT(false, "not yet implement"); } } VersionSt *VersionStTable::CreateVersionSt(OriginalSt *ost, size_t version) { ASSERT(ost != nullptr, "nullptr check"); ASSERT(ost->GetVersionsIndex().size() == version, "ssa version need to be created incrementally!"); auto *vst = vstAlloc.GetMemPool()->New<VersionSt>(versionStVector.size(), version, ost); versionStVector.push_back(vst); ost->PushbackVersionIndex(vst->GetIndex()); if (version == kInitVersion) { ost->SetZeroVersionIndex(vst->GetIndex()); } vst->SetOrigSt(ost); return vst; } VersionSt *VersionStTable::FindOrCreateVersionSt(OriginalSt *ost, size_t version) { // this version already exists... ASSERT(ost != nullptr, "nullptr check"); if (ost->GetVersionsIndex().size() > version) { size_t versionIndex = ost->GetVersionIndex(version); ASSERT(versionStVector.size() > versionIndex, "versionStVector out of range"); return versionStVector.at(versionIndex); } return CreateVersionSt(ost, version); } void VersionStTable::Dump(const MIRModule *mod) const { ASSERT(mod != nullptr, "nullptr check"); LogInfo::MapleLogger() << "=======version st table entries=======\n"; for (size_t i = 1; i < versionStVector.size(); ++i) { const VersionSt *vst = versionStVector[i]; vst->Dump(); if (vst->GetVersion() > 0) { LogInfo::MapleLogger() << " defined BB" << vst->GetDefBB()->GetBBId() << ": "; vst->DumpDefStmt(mod); } else { LogInfo::MapleLogger() << '\n'; } } mod->GetOut() << "=======end version st table===========\n"; } } // namespace maple
{ "language": "C++" }
#ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <iterator> #else #include <stdarg.h> #endif #include <algorithm> #include "myx_sql_tree_item.h" #include "myx_lex_helpers.h" #include <functional> #include <assert.h> #ifdef _WIN32 #ifndef strcasecmp #define strcasecmp _stricmp #define strncasecmp strnicmp #endif #endif namespace mysql_parser { const char* find_cstr_in_array_ci(const char *arr[], size_t arr_size, const char* str) { for (size_t n= 0; n < arr_size; ++n) if (are_cstrings_eq_ci(arr[n], str)) return arr[n]; return NULL; } const char* find_str_in_array_ci(const char *arr[], size_t arr_size, const std::string &str) { return find_cstr_in_array_ci(arr, arr_size, str.c_str()); } bool are_cstrings_eq(const char *str1, const char *str2, bool case_sensitive) { if (case_sensitive) return ((str1 == str2) || ( ((NULL != str1) && (NULL != str2)) && (strlen(str1) == strlen(str2)) && (0 == strcmp(str1, str2)) )); else return are_cstrings_eq_ci(str1, str2); } bool are_strings_eq(const std::string &str1, const std::string &str2, bool case_sensitive) { return are_cstrings_eq(str1.c_str(), str2.c_str(), case_sensitive); } bool are_cstrings_eq_ci(const char *str1, const char *str2) { return ((str1 == str2) || ( ((NULL != str1) && (NULL != str2)) && (toupper(str1[0]) == toupper(str2[0])) && (strlen(str1) == strlen(str2)) && (0 == strncasecmp(str1, str2, strlen(str1))) )); } bool are_strings_eq_ci(const std::string &str1, const std::string &str2) { return are_cstrings_eq_ci(str1.c_str(), str2.c_str()); } MYX_PUBLIC_FUNC std::ostream& operator << (std::ostream& os, const SqlAstNode& item) { if (item.value()[0] != '\0') { sql::symbol item_name= item.name(); std::string item_value= item.value(); os << "<elem name='" << (item_name ? sql::symbol_names[item_name] : "") << "' value='" << item_value.c_str() << "'>"; } else os << "<elem name='" << item.name() << "'>"; { SqlAstNode::SubItemList *subitems= item.subitems(); if (subitems) for (SqlAstNode::SubItemList::const_iterator i= subitems->begin(), i_end= subitems->end(); i != i_end; ++i) os << *i; } os << "</elem>"; return os; } std::list<SqlAstNode *> SqlAstStatics::_ast_nodes; const SqlAstNode * SqlAstStatics::_tree= NULL; const char * SqlAstStatics::_sql_statement= NULL; bool SqlAstStatics::is_ast_generation_enabled= true; static std::shared_ptr<SqlAstTerminalNode> _last_terminal_node; static std::shared_ptr<SqlAstTerminalNode> _first_terminal_node; void SqlAstStatics::tree(const SqlAstNode *tree) { _tree= tree; mysql_parser::tree= _tree; } void SqlAstStatics::cleanup_ast_nodes() { for (std::list<SqlAstNode*>::iterator i= _ast_nodes.begin(), i_end= _ast_nodes.end(); i != i_end; ++i) delete *i; _ast_nodes.clear(); _tree= NULL; //_sql_statement= NULL; } std::shared_ptr<SqlAstTerminalNode> SqlAstStatics::first_terminal_node() { if (_first_terminal_node == NULL) first_terminal_node(std::shared_ptr<SqlAstTerminalNode>(new SqlAstTerminalNode)); return _first_terminal_node; } std::shared_ptr<SqlAstTerminalNode> SqlAstStatics::last_terminal_node() { if (_last_terminal_node == NULL) last_terminal_node(std::shared_ptr<SqlAstTerminalNode>(new SqlAstTerminalNode)); return _last_terminal_node; } void SqlAstStatics::first_terminal_node(std::shared_ptr<SqlAstTerminalNode> value) { _first_terminal_node = value; } void SqlAstStatics::last_terminal_node(std::shared_ptr<SqlAstTerminalNode> value) { _last_terminal_node = value; } SqlAstNode::SqlAstNode(sql::symbol name, const char *value, int value_length, int stmt_lineno, int stmt_boffset, int stmt_eoffset, SubItemList *items) : _name(name), _value((value) ? new std::string(value) : NULL), _value_length(value_length), _stmt_lineno(stmt_lineno), _stmt_boffset(stmt_boffset), _stmt_eoffset(stmt_eoffset), _subitems(items) { if (-1 != _stmt_eoffset && (_stmt_boffset + _value_length) > _stmt_eoffset) _stmt_eoffset= _stmt_boffset + _value_length; } SqlAstNode::~SqlAstNode() { } std::string SqlAstNode::value() const { if (_value.get()) return *_value; else if (_value_length) return std::string(SqlAstStatics::sql_statement() + _stmt_boffset, _value_length); else return ""; } const SqlAstNode * SqlAstNode::left_most_subitem() const { return (_subitems) ? (*_subitems->begin())->left_most_subitem() : this; } const SqlAstNode * SqlAstNode::right_most_subitem() const { return (_subitems) ? (*_subitems->rend())->right_most_subitem() : this; } int SqlAstNode::stmt_lineno() const { if ((-1 == _stmt_lineno) && _subitems) return (*_subitems->begin())->stmt_lineno(); return _stmt_lineno; } int SqlAstNode::stmt_boffset() const { if ((-1 == _stmt_boffset) && _subitems) return (*_subitems->begin())->stmt_boffset(); return _stmt_boffset; } int SqlAstNode::stmt_eoffset() const { if ((-1 == _stmt_eoffset) && _subitems) return (*_subitems->rbegin())->stmt_eoffset(); return _stmt_eoffset; } /* Tries to find sequence of items begining from subitem (if specified, otherwise from 1st subitem). Returns last item from found sequence. */ const SqlAstNode * SqlAstNode::subseq__(const SqlAstNode *subitem, sql::symbol name, va_list args) const { SqlAstNode::SubItemList::iterator i= _subitems->begin(); SqlAstNode::SubItemList::iterator i_end= _subitems->end(); // skip some elements if start subitem is specified if (subitem) i= std::find(i, i_end, subitem); for (; i != i_end; ++i) { subitem= *i; if (!subitem->name_equals(name)) return NULL; #ifdef __GNUC__ name= (sql::symbol)va_arg(args, int); #else name= va_arg(args, sql::symbol); #endif if (!name) return subitem; // return last item from found sequence } return NULL; } const SqlAstNode * SqlAstNode::subseq_(sql::symbol name, ...) const { va_list args; va_start(args, name); const SqlAstNode * subitem= subseq__(NULL, name, args); va_end(args); return subitem; } const SqlAstNode * SqlAstNode::subseq_(const SqlAstNode *subitem, sql::symbol name, ...) const { va_list args; va_start(args, name); subitem= subseq__(subitem, name, args); va_end(args); return subitem; } /* Tries to find sequence within whole range of children items starting from 'subitem' (if specified, otherwise from 1st subitem). Returns last item from found sequence. */ const SqlAstNode * SqlAstNode::find_subseq__(const SqlAstNode *subitem, sql::symbol name, va_list args) const { SqlAstNode::SubItemList::iterator i= _subitems->begin(); SqlAstNode::SubItemList::iterator i_end= _subitems->end(); // skip some elements if start subitem is specified if (subitem) i= std::find(i, i_end, subitem); for (; i != i_end; ++i) { subitem= *i; if (subitem->name_equals(name) && (subitem= subseq__(subitem, name, args))) return subitem; // return last item from found sequence } return NULL; } const SqlAstNode * SqlAstNode::find_subseq_(sql::symbol name, ...) const { va_list args; va_start(args, name); const SqlAstNode * subitem= find_subseq__(NULL, name, args); va_end(args); return subitem; } const SqlAstNode * SqlAstNode::find_subseq_(const SqlAstNode *subitem, sql::symbol name, ...) const { va_list args; va_start(args, name); subitem= find_subseq__(subitem, name, args); va_end(args); return subitem; } /* Tries to find sequence of items begining from subitem (if specified, otherwise from 1st subitem). Returns last item from found sequence. */ const SqlAstNode * SqlAstNode::check_words(sql::symbol words[], size_t words_count, const SqlAstNode *start_item) const { const SqlAstNode *result= NULL; if (NULL != _subitems) { SqlAstNode::SubItemList::iterator i= _subitems->begin(); SqlAstNode::SubItemList::iterator i_end= _subitems->end(); // skip some elements if needed if (NULL != start_item) for (; (*i != start_item) && (i != i_end); ++i); // now check given sequence size_t n= 0; for (; n != words_count && i != i_end; ++i, ++n) { result= *i; if (!result->name_equals(words[n])) return NULL; } if (n < words_count) return NULL; } return result; } /* Tries to find sequence within whole range of children items starting from 'subitem' (if specified, otherwise from 1st subitem). Returns last item from found sequence. */ const SqlAstNode * SqlAstNode::find_words(sql::symbol words[], size_t words_count, const SqlAstNode *start_item) const { SqlAstNode::SubItemList::iterator i= _subitems->begin(); SqlAstNode::SubItemList::iterator i_end= _subitems->end(); // skip some elements if needed if (NULL != start_item) for (; (*i != start_item) && (i != i_end); ++i); // now try to find given sequence const SqlAstNode *item= NULL; size_t n= 0; for (; i != i_end; ++i) { item= *i; if (item->name_equals(words[n])) { if (words_count == ++n) break; } else n= 0; } return (words_count == n) ? item : NULL; } const SqlAstNode * SqlAstNode::search_by_names(sql::symbol names[], size_t path_count) const { const SqlAstNode *result= NULL; for (size_t n= 0; n < path_count; ++n) if ((result= subitem_by_name(names[n]))) break; return result; } const SqlAstNode * SqlAstNode::search_by_paths(sql::symbol * paths[], size_t path_count) const { const SqlAstNode *result= NULL; for (size_t n= 0; n < path_count; ++n) if ((result= subitem_by_path(paths[n]))) break; return result; } std::string SqlAstNode::restore_sql_text(const std::string &sql_statement, const SqlAstNode *first_subitem, const SqlAstNode *last_subitem) const { int boffset= first_subitem ? first_subitem->_stmt_boffset : -1; int eoffset= last_subitem ? last_subitem->_stmt_eoffset : -1; restore_sql_text(boffset, eoffset, first_subitem, last_subitem); if (-1 != boffset && -1 != eoffset) { std::string sql_text; sql_text.reserve(eoffset - boffset); std::copy(sql_statement.begin()+boffset, sql_statement.begin()+eoffset, std::back_inserter(sql_text)); return sql_text; } return std::string(); } void SqlAstNode::restore_sql_text(int &boffset, int &eoffset, const SqlAstNode *first_subitem, const SqlAstNode *last_subitem) const { if (-1 == boffset || (boffset > _stmt_boffset && -1 != _stmt_boffset)) boffset= _stmt_boffset; if (-1 == eoffset || (eoffset < _stmt_eoffset && -1 != _stmt_eoffset)) eoffset= _stmt_eoffset; if (NULL != _subitems) { SqlAstNode::SubItemList::const_iterator i= _subitems->begin(); const SqlAstNode::SubItemList::const_iterator i_end= _subitems->end(); if (first_subitem) for (; (i_end != i) && (*i != first_subitem); ++i); for (; (i != i_end) && (*i != last_subitem); ++i) (*i)->restore_sql_text(boffset, eoffset, NULL, NULL); } } // warning this sql has incorrect syntax void SqlAstNode::build_sql(std::string &sql_text) const { if (_value_length) { sql_text.append(value()); const char *nl_keywords[]= {"begin", "end", ";"}; std::string item_value= value(); if (find_cstr_in_array_ci(nl_keywords, ARR_CAPACITY(nl_keywords), item_value.c_str())) sql_text.append("\n"); else sql_text.append(" "); } if (NULL != _subitems) for (SqlAstNode::SubItemList::const_iterator i= _subitems->begin(), i_end= _subitems->end(); i != i_end; ++i) (*i)->build_sql(sql_text); } const SqlAstNode * SqlAstNode::subitem_(sql::symbol name, ...) const { va_list args; va_start(args, name); const SqlAstNode *item= subitem__(name, args); va_end(args); return item; } const SqlAstNode *SqlAstNode::subitem__(sql::symbol name, va_list args) const { const SqlAstNode *item= this; while (name && item) { item= item->subitem_by_name(name); assert(sizeof(int) == sizeof(sql::symbol)); #ifdef __GNUC__ name= (sql::symbol)va_arg(args, int); #else name= va_arg(args, sql::symbol); #endif } return item; } const SqlAstNode * SqlAstNode::subitem_(int position, ...) const { if ((0 <= position) && (_subitems->size() > (size_t)position)) { SqlAstNode::SubItemList::const_iterator i= _subitems->begin(); for (; 0 < position; --position) ++i; return *i; } return NULL; } const SqlAstNode *SqlAstNode::subitem_by_name(sql::symbol name, const SqlAstNode *start_item) const { if (!(_subitems)) return NULL; SqlAstNode::SubItemList::const_iterator i= _subitems->begin(); SqlAstNode::SubItemList::const_iterator i_end= _subitems->end(); if (start_item) i= find(i, i_end, start_item); for (; i != i_end; ++i) if ((*i)->name_equals(name)) return *i; return NULL; } const SqlAstNode * SqlAstNode::subitem_by_name(sql::symbol name, size_t position) const { if (!(_subitems)) return NULL; if (_subitems->size() > position) { SqlAstNode::SubItemList::const_iterator i= _subitems->begin(); SqlAstNode::SubItemList::const_iterator i_end= _subitems->end(); for (; 0 < position; --position) ++i; for (; i != i_end; ++i) if ((*i)->name_equals(name)) return *i; } return NULL; } const SqlAstNode *SqlAstNode::rsubitem_by_name(sql::symbol name, size_t position) const { if (_subitems->size() > position) { SqlAstNode::SubItemList::const_reverse_iterator i= _subitems->rbegin(); SqlAstNode::SubItemList::const_reverse_iterator i_end= _subitems->rend(); for (; 0 < position; --position) ++i; for (; i != i_end; ++i) if ((*i)->name_equals(name)) return *i; } return NULL; } const SqlAstNode * SqlAstNode::subitem_by_path(sql::symbol path[]) const { const SqlAstNode *item= this; sql::symbol *name= path; while ((item) && *name) item= item->subitem_by_name(*name++); return item; } char * SqlAstNode::subitems_as_string(const char *delim) const { std::string to; if (_subitems) { const char *current_delim= ""; for (SqlAstNode::SubItemList::const_iterator i= _subitems->begin(), i_end= _subitems->end(); i != i_end; ++i) { SqlAstNode *subitem= *i; if (subitem->subitems()->size() > 0) { char *s= subitem->subitems_as_string(delim); to += current_delim; current_delim= delim; to += s; delete[] s; } else { to += current_delim; current_delim= delim; to += subitem->value(); } } } return strcpy(new char[to.length()+1], to.c_str()); } SqlAstNonTerminalNode::~SqlAstNonTerminalNode() { // no need in this code after flat list of all allocated ast nodes was introduced, see SqlAstStatics::_ast_nodes //for (SubItemList::iterator i= _subitems.begin(), end= _subitems.end(); i != end; ++i) // delete *i; } //extern "C" //{ extern void * new_ast_node(sql::symbol name) { SqlAstNode *node= SqlAstStatics::add_ast_node(new SqlAstNonTerminalNode(name)); return node; } extern void * reuse_ast_node(void *node_, sql::symbol name) { return (node_) ? set_ast_node_name(node_, name) : new_ast_node(name); } extern void * set_ast_node_name(void *node_, sql::symbol name) { if (!node_) return node_; static_cast<SqlAstNode *>(node_)->set_name(name); return node_; } extern void add_ast_child_node(void *parent_node_, void *child_node_) { if (!parent_node_ || !child_node_) return; SqlAstNode *child_node= static_cast<SqlAstNode *>(child_node_); SqlAstNode *parent_node= static_cast<SqlAstNode *>(parent_node_); parent_node->subitems()->push_back(child_node); } extern void merge_ast_child_nodes(void *dest_node_, void *src_node_) { if (!dest_node_ || !src_node_) return; SqlAstNode::SubItemList *dest_list= static_cast<SqlAstNode *>(dest_node_)->subitems(); SqlAstNode::SubItemList *src_list= static_cast<SqlAstNode *>(src_node_)->subitems(); dest_list->splice(dest_list->end(), *src_list); } extern void tree_item_dump_xml_to_file(const void *tree_item, const char *filename) { const SqlAstNode* item= static_cast<const SqlAstNode *>(tree_item); std::ofstream os(filename); os << *item; } //} // extern "C" } // namespace mysql_parser
{ "language": "C++" }
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2009 Gael Guennebaud <gael.guennebaud@inria.fr> // // 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/. #ifndef EIGEN_STABLENORM_H #define EIGEN_STABLENORM_H namespace Eigen { namespace internal { template<typename ExpressionType, typename Scalar> inline void stable_norm_kernel(const ExpressionType& bl, Scalar& ssq, Scalar& scale, Scalar& invScale) { using std::max; Scalar maxCoeff = bl.cwiseAbs().maxCoeff(); if (maxCoeff>scale) { ssq = ssq * numext::abs2(scale/maxCoeff); Scalar tmp = Scalar(1)/maxCoeff; if(tmp > NumTraits<Scalar>::highest()) { invScale = NumTraits<Scalar>::highest(); scale = Scalar(1)/invScale; } else { scale = maxCoeff; invScale = tmp; } } // TODO if the maxCoeff is much much smaller than the current scale, // then we can neglect this sub vector if(scale>Scalar(0)) // if scale==0, then bl is 0 ssq += (bl*invScale).squaredNorm(); } template<typename Derived> inline typename NumTraits<typename traits<Derived>::Scalar>::Real blueNorm_impl(const EigenBase<Derived>& _vec) { typedef typename Derived::RealScalar RealScalar; typedef typename Derived::Index Index; using std::pow; using std::min; using std::max; using std::sqrt; using std::abs; const Derived& vec(_vec.derived()); static bool initialized = false; static RealScalar b1, b2, s1m, s2m, overfl, rbig, relerr; if(!initialized) { int ibeta, it, iemin, iemax, iexp; RealScalar eps; // This program calculates the machine-dependent constants // bl, b2, slm, s2m, relerr overfl // from the "basic" machine-dependent numbers // nbig, ibeta, it, iemin, iemax, rbig. // The following define the basic machine-dependent constants. // For portability, the PORT subprograms "ilmaeh" and "rlmach" // are used. For any specific computer, each of the assignment // statements can be replaced ibeta = std::numeric_limits<RealScalar>::radix; // base for floating-point numbers it = std::numeric_limits<RealScalar>::digits; // number of base-beta digits in mantissa iemin = std::numeric_limits<RealScalar>::min_exponent; // minimum exponent iemax = std::numeric_limits<RealScalar>::max_exponent; // maximum exponent rbig = (std::numeric_limits<RealScalar>::max)(); // largest floating-point number iexp = -((1-iemin)/2); b1 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // lower boundary of midrange iexp = (iemax + 1 - it)/2; b2 = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // upper boundary of midrange iexp = (2-iemin)/2; s1m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for lower range iexp = - ((iemax+it)/2); s2m = RealScalar(pow(RealScalar(ibeta),RealScalar(iexp))); // scaling factor for upper range overfl = rbig*s2m; // overflow boundary for abig eps = RealScalar(pow(double(ibeta), 1-it)); relerr = sqrt(eps); // tolerance for neglecting asml initialized = true; } Index n = vec.size(); RealScalar ab2 = b2 / RealScalar(n); RealScalar asml = RealScalar(0); RealScalar amed = RealScalar(0); RealScalar abig = RealScalar(0); for(typename Derived::InnerIterator it(vec, 0); it; ++it) { RealScalar ax = abs(it.value()); if(ax > ab2) abig += numext::abs2(ax*s2m); else if(ax < b1) asml += numext::abs2(ax*s1m); else amed += numext::abs2(ax); } if(abig > RealScalar(0)) { abig = sqrt(abig); if(abig > overfl) { return rbig; } if(amed > RealScalar(0)) { abig = abig/s2m; amed = sqrt(amed); } else return abig/s2m; } else if(asml > RealScalar(0)) { if (amed > RealScalar(0)) { abig = sqrt(amed); amed = sqrt(asml) / s1m; } else return sqrt(asml)/s1m; } else return sqrt(amed); asml = (min)(abig, amed); abig = (max)(abig, amed); if(asml <= abig*relerr) return abig; else return abig * sqrt(RealScalar(1) + numext::abs2(asml/abig)); } } // end namespace internal /** \returns the \em l2 norm of \c *this avoiding underflow and overflow. * This version use a blockwise two passes algorithm: * 1 - find the absolute largest coefficient \c s * 2 - compute \f$ s \Vert \frac{*this}{s} \Vert \f$ in a standard way * * For architecture/scalar types supporting vectorization, this version * is faster than blueNorm(). Otherwise the blueNorm() is much faster. * * \sa norm(), blueNorm(), hypotNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::stableNorm() const { using std::min; using std::sqrt; const Index blockSize = 4096; RealScalar scale(0); RealScalar invScale(1); RealScalar ssq(0); // sum of square enum { Alignment = (int(Flags)&DirectAccessBit) || (int(Flags)&AlignedBit) ? 1 : 0 }; Index n = size(); Index bi = internal::first_aligned(derived()); if (bi>0) internal::stable_norm_kernel(this->head(bi), ssq, scale, invScale); for (; bi<n; bi+=blockSize) internal::stable_norm_kernel(this->segment(bi,(min)(blockSize, n - bi)).template forceAlignedAccessIf<Alignment>(), ssq, scale, invScale); return scale * sqrt(ssq); } /** \returns the \em l2 norm of \c *this using the Blue's algorithm. * A Portable Fortran Program to Find the Euclidean Norm of a Vector, * ACM TOMS, Vol 4, Issue 1, 1978. * * For architecture/scalar types without vectorization, this version * is much faster than stableNorm(). Otherwise the stableNorm() is faster. * * \sa norm(), stableNorm(), hypotNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::blueNorm() const { return internal::blueNorm_impl(*this); } /** \returns the \em l2 norm of \c *this avoiding undeflow and overflow. * This version use a concatenation of hypot() calls, and it is very slow. * * \sa norm(), stableNorm() */ template<typename Derived> inline typename NumTraits<typename internal::traits<Derived>::Scalar>::Real MatrixBase<Derived>::hypotNorm() const { return this->cwiseAbs().redux(internal::scalar_hypot_op<RealScalar>()); } } // end namespace Eigen #endif // EIGEN_STABLENORM_H
{ "language": "C++" }
////////////////////////////////////////////////////////////////////////////// // // (C) Copyright Ion Gaztanaga 2005-2012. Distributed under the Boost // Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.lslboost.org/LICENSE_1_0.txt) // // See http://www.lslboost.org/libs/container for documentation. // ////////////////////////////////////////////////////////////////////////////// #ifndef BOOST_CONTAINER_FLAT_SET_HPP #define BOOST_CONTAINER_FLAT_SET_HPP #if defined(_MSC_VER) # pragma once #endif #include <lslboost/container/detail/config_begin.hpp> #include <lslboost/container/detail/workaround.hpp> #include <lslboost/container/container_fwd.hpp> #include <utility> #include <functional> #include <memory> #include <lslboost/container/detail/flat_tree.hpp> #include <lslboost/container/detail/mpl.hpp> #include <lslboost/container/allocator_traits.hpp> #include <lslboost/move/utility.hpp> #include <lslboost/move/detail/move_helpers.hpp> namespace lslboost { namespace container { /// @cond // Forward declarations of operators < and ==, needed for friend declaration. #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template <class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > #else template <class Key, class Compare, class Allocator> #endif class flat_set; template <class Key, class Compare, class Allocator> inline bool operator==(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y); template <class Key, class Compare, class Allocator> inline bool operator<(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y); /// @endcond //! flat_set is a Sorted Associative Container that stores objects of type Key. //! It is also a Unique Associative Container, meaning that no two elements are the same. //! //! flat_set is similar to std::set but it's implemented like an ordered vector. //! This means that inserting a new element into a flat_set invalidates //! previous iterators and references //! //! Erasing an element of a flat_set invalidates iterators and references //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template <class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > #else template <class Key, class Compare, class Allocator> #endif class flat_set { /// @cond private: BOOST_COPYABLE_AND_MOVABLE(flat_set) typedef container_detail::flat_tree<Key, Key, container_detail::identity<Key>, Compare, Allocator> tree_t; tree_t m_flat_tree; // flat tree representing flat_set /// @endcond public: ////////////////////////////////////////////// // // types // ////////////////////////////////////////////// typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef typename ::lslboost::container::allocator_traits<Allocator>::pointer pointer; typedef typename ::lslboost::container::allocator_traits<Allocator>::const_pointer const_pointer; typedef typename ::lslboost::container::allocator_traits<Allocator>::reference reference; typedef typename ::lslboost::container::allocator_traits<Allocator>::const_reference const_reference; typedef typename ::lslboost::container::allocator_traits<Allocator>::size_type size_type; typedef typename ::lslboost::container::allocator_traits<Allocator>::difference_type difference_type; typedef Allocator allocator_type; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; public: ////////////////////////////////////////////// // // construct/copy/destroy // ////////////////////////////////////////////// //! <b>Effects</b>: Default constructs an empty flat_set. //! //! <b>Complexity</b>: Constant. explicit flat_set() : m_flat_tree() {} //! <b>Effects</b>: Constructs an empty flat_set using the specified //! comparison object and allocator. //! //! <b>Complexity</b>: Constant. explicit flat_set(const Compare& comp, const allocator_type& a = allocator_type()) : m_flat_tree(comp, a) {} //! <b>Effects</b>: Constructs an empty flat_set using the specified allocator. //! //! <b>Complexity</b>: Constant. explicit flat_set(const allocator_type& a) : m_flat_tree(a) {} //! <b>Effects</b>: Constructs an empty set using the specified comparison object and //! allocator, and inserts elements from the range [first ,last ). //! //! <b>Complexity</b>: Linear in N if the range [first ,last ) is already sorted using //! comp and otherwise N logN, where N is last - first. template <class InputIterator> flat_set(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(true, first, last, comp, a) {} //! <b>Effects</b>: Constructs an empty flat_set using the specified comparison object and //! allocator, and inserts elements from the ordered unique range [first ,last). This function //! is more efficient than the normal range creation for ordered ranges. //! //! <b>Requires</b>: [first ,last) must be ordered according to the predicate and must be //! unique values. //! //! <b>Complexity</b>: Linear in N. //! //! <b>Note</b>: Non-standard extension. template <class InputIterator> flat_set(ordered_unique_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(ordered_range, first, last, comp, a) {} //! <b>Effects</b>: Copy constructs a set. //! //! <b>Complexity</b>: Linear in x.size(). flat_set(const flat_set& x) : m_flat_tree(x.m_flat_tree) {} //! <b>Effects</b>: Move constructs a set. Constructs *this using x's resources. //! //! <b>Complexity</b>: Constant. //! //! <b>Postcondition</b>: x is emptied. flat_set(BOOST_RV_REF(flat_set) mx) : m_flat_tree(lslboost::move(mx.m_flat_tree)) {} //! <b>Effects</b>: Copy constructs a set using the specified allocator. //! //! <b>Complexity</b>: Linear in x.size(). flat_set(const flat_set& x, const allocator_type &a) : m_flat_tree(x.m_flat_tree, a) {} //! <b>Effects</b>: Move constructs a set using the specified allocator. //! Constructs *this using x's resources. //! //! <b>Complexity</b>: Constant if a == mx.get_allocator(), linear otherwise flat_set(BOOST_RV_REF(flat_set) mx, const allocator_type &a) : m_flat_tree(lslboost::move(mx.m_flat_tree), a) {} //! <b>Effects</b>: Makes *this a copy of x. //! //! <b>Complexity</b>: Linear in x.size(). flat_set& operator=(BOOST_COPY_ASSIGN_REF(flat_set) x) { m_flat_tree = x.m_flat_tree; return *this; } //! <b>Effects</b>: Makes *this a copy of the previous value of xx. //! //! <b>Complexity</b>: Linear in x.size(). flat_set& operator=(BOOST_RV_REF(flat_set) mx) { m_flat_tree = lslboost::move(mx.m_flat_tree); return *this; } //! <b>Effects</b>: Returns a copy of the Allocator that //! was passed to the object's constructor. //! //! <b>Complexity</b>: Constant. allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_allocator(); } //! <b>Effects</b>: Returns a reference to the internal allocator. //! //! <b>Throws</b>: Nothing //! //! <b>Complexity</b>: Constant. //! //! <b>Note</b>: Non-standard extension. stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_stored_allocator(); } //! <b>Effects</b>: Returns a reference to the internal allocator. //! //! <b>Throws</b>: Nothing //! //! <b>Complexity</b>: Constant. //! //! <b>Note</b>: Non-standard extension. const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_stored_allocator(); } ////////////////////////////////////////////// // // iterators // ////////////////////////////////////////////// //! <b>Effects</b>: Returns an iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. iterator begin() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.begin(); } //! <b>Effects</b>: Returns a const_iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator begin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.begin(); } //! <b>Effects</b>: Returns an iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. iterator end() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.end(); } //! <b>Effects</b>: Returns a const_iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator end() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.end(); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rbegin(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rbegin(); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rend(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rend(); } //! <b>Effects</b>: Returns a const_iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.cbegin(); } //! <b>Effects</b>: Returns a const_iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator cend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.cend(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.crbegin(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.crend(); } ////////////////////////////////////////////// // // capacity // ////////////////////////////////////////////// //! <b>Effects</b>: Returns true if the container contains no elements. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. bool empty() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.empty(); } //! <b>Effects</b>: Returns the number of the elements contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type size() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.size(); } //! <b>Effects</b>: Returns the largest possible size of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type max_size() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.max_size(); } //! <b>Effects</b>: Number of elements for which memory has been allocated. //! capacity() is always greater than or equal to size(). //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type capacity() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.capacity(); } //! <b>Effects</b>: If n is less than or equal to capacity(), this call has no //! effect. Otherwise, it is a request for allocation of additional memory. //! If the request is successful, then capacity() is greater than or equal to //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. //! //! <b>Throws</b>: If memory allocation allocation throws or Key's copy constructor throws. //! //! <b>Note</b>: If capacity() is less than "cnt", iterators and references to //! to values might be invalidated. void reserve(size_type cnt) { m_flat_tree.reserve(cnt); } //! <b>Effects</b>: Tries to deallocate the excess of memory created // with previous allocations. The size of the vector is unchanged //! //! <b>Throws</b>: If memory allocation throws, or Key's copy constructor throws. //! //! <b>Complexity</b>: Linear to size(). void shrink_to_fit() { m_flat_tree.shrink_to_fit(); } ////////////////////////////////////////////// // // modifiers // ////////////////////////////////////////////// #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts an object x of type Key constructed with //! std::forward<Args>(args)... if and only if there is no element in the container //! with key equivalent to the key of x. //! //! <b>Returns</b>: The bool component of the returned pair is true if and only //! if the insertion takes place, and the iterator component of the pair //! points to the element with key equivalent to the key of x. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class... Args> std::pair<iterator,bool> emplace(Args&&... args) { return m_flat_tree.emplace_unique(lslboost::forward<Args>(args)...); } //! <b>Effects</b>: Inserts an object of type Key constructed with //! std::forward<Args>(args)... in the container if and only if there is //! no element in the container with key equivalent to the key of x. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent //! to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class... Args> iterator emplace_hint(const_iterator hint, Args&&... args) { return m_flat_tree.emplace_hint_unique(hint, lslboost::forward<Args>(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ std::pair<iterator,bool> emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ { return m_flat_tree.emplace_unique(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ { return m_flat_tree.emplace_hint_unique \ (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) #include BOOST_PP_LOCAL_ITERATE() #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts x if and only if there is no element in the container //! with key equivalent to the key of x. //! //! <b>Returns</b>: The bool component of the returned pair is true if and only //! if the insertion takes place, and the iterator component of the pair //! points to the element with key equivalent to the key of x. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. std::pair<iterator, bool> insert(const value_type &x); //! <b>Effects</b>: Inserts a new value_type move constructed from the pair if and //! only if there is no element in the container with key equivalent to the key of x. //! //! <b>Returns</b>: The bool component of the returned pair is true if and only //! if the insertion takes place, and the iterator component of the pair //! points to the element with key equivalent to the key of x. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. std::pair<iterator, bool> insert(value_type &&x); #else private: typedef std::pair<iterator, bool> insert_return_pair; public: BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, insert_return_pair, this->priv_insert) #endif #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts a copy of x in the container if and only if there is //! no element in the container with key equivalent to the key of x. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent //! to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(const_iterator p, const value_type &x); //! <b>Effects</b>: Inserts an element move constructed from x in the container. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(const_iterator position, value_type &&x); #else BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) #endif //! <b>Requires</b>: first, last are not iterators into *this. //! //! <b>Effects</b>: inserts each element from the range [first,last) if and only //! if there is no element with key equivalent to the key of that element. //! //! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last) //! search time plus N*size() insertion time. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class InputIterator> void insert(InputIterator first, InputIterator last) { m_flat_tree.insert_unique(first, last); } //! <b>Requires</b>: first, last are not iterators into *this and //! must be ordered according to the predicate and must be //! unique values. //! //! <b>Effects</b>: inserts each element from the range [first,last) .This function //! is more efficient than the normal range creation for ordered ranges. //! //! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last) //! search time plus N*size() insertion time. //! //! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements. template <class InputIterator> void insert(ordered_unique_range_t, InputIterator first, InputIterator last) { m_flat_tree.insert_unique(ordered_unique_range, first, last); } //! <b>Effects</b>: Erases the element pointed to by position. //! //! <b>Returns</b>: Returns an iterator pointing to the element immediately //! following q prior to the element being erased. If no such element exists, //! returns end(). //! //! <b>Complexity</b>: Linear to the elements with keys bigger than position //! //! <b>Note</b>: Invalidates elements with keys //! not less than the erased element. iterator erase(const_iterator position) { return m_flat_tree.erase(position); } //! <b>Effects</b>: Erases all elements in the container with key equivalent to x. //! //! <b>Returns</b>: Returns the number of erased elements. //! //! <b>Complexity</b>: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. size_type erase(const key_type& x) { return m_flat_tree.erase(x); } //! <b>Effects</b>: Erases all the elements in the range [first, last). //! //! <b>Returns</b>: Returns last. //! //! <b>Complexity</b>: size()*N where N is the distance from first to last. //! //! <b>Complexity</b>: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. iterator erase(const_iterator first, const_iterator last) { return m_flat_tree.erase(first, last); } //! <b>Effects</b>: Swaps the contents of *this and x. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. void swap(flat_set& x) { m_flat_tree.swap(x.m_flat_tree); } //! <b>Effects</b>: erase(a.begin(),a.end()). //! //! <b>Postcondition</b>: size() == 0. //! //! <b>Complexity</b>: linear in size(). void clear() BOOST_CONTAINER_NOEXCEPT { m_flat_tree.clear(); } ////////////////////////////////////////////// // // observers // ////////////////////////////////////////////// //! <b>Effects</b>: Returns the comparison object out //! of which a was constructed. //! //! <b>Complexity</b>: Constant. key_compare key_comp() const { return m_flat_tree.key_comp(); } //! <b>Effects</b>: Returns an object of value_compare constructed out //! of the comparison object. //! //! <b>Complexity</b>: Constant. value_compare value_comp() const { return m_flat_tree.key_comp(); } ////////////////////////////////////////////// // // set operations // ////////////////////////////////////////////// //! <b>Returns</b>: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic. iterator find(const key_type& x) { return m_flat_tree.find(x); } //! <b>Returns</b>: Allocator const_iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic.s const_iterator find(const key_type& x) const { return m_flat_tree.find(x); } //! <b>Returns</b>: The number of elements with key equivalent to x. //! //! <b>Complexity</b>: log(size())+count(k) size_type count(const key_type& x) const { return static_cast<size_type>(m_flat_tree.find(x) != m_flat_tree.end()); } //! <b>Returns</b>: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic iterator lower_bound(const key_type& x) { return m_flat_tree.lower_bound(x); } //! <b>Returns</b>: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic const_iterator lower_bound(const key_type& x) const { return m_flat_tree.lower_bound(x); } //! <b>Returns</b>: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic iterator upper_bound(const key_type& x) { return m_flat_tree.upper_bound(x); } //! <b>Returns</b>: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic const_iterator upper_bound(const key_type& x) const { return m_flat_tree.upper_bound(x); } //! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! <b>Complexity</b>: Logarithmic std::pair<const_iterator, const_iterator> equal_range(const key_type& x) const { return m_flat_tree.equal_range(x); } //! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! <b>Complexity</b>: Logarithmic std::pair<iterator,iterator> equal_range(const key_type& x) { return m_flat_tree.equal_range(x); } /// @cond template <class K1, class C1, class A1> friend bool operator== (const flat_set<K1,C1,A1>&, const flat_set<K1,C1,A1>&); template <class K1, class C1, class A1> friend bool operator< (const flat_set<K1,C1,A1>&, const flat_set<K1,C1,A1>&); private: template<class KeyType> std::pair<iterator, bool> priv_insert(BOOST_FWD_REF(KeyType) x) { return m_flat_tree.insert_unique(::lslboost::forward<KeyType>(x)); } template<class KeyType> iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) { return m_flat_tree.insert_unique(p, ::lslboost::forward<KeyType>(x)); } /// @endcond }; template <class Key, class Compare, class Allocator> inline bool operator==(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return x.m_flat_tree == y.m_flat_tree; } template <class Key, class Compare, class Allocator> inline bool operator<(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return x.m_flat_tree < y.m_flat_tree; } template <class Key, class Compare, class Allocator> inline bool operator!=(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return !(x == y); } template <class Key, class Compare, class Allocator> inline bool operator>(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return y < x; } template <class Key, class Compare, class Allocator> inline bool operator<=(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return !(y < x); } template <class Key, class Compare, class Allocator> inline bool operator>=(const flat_set<Key,Compare,Allocator>& x, const flat_set<Key,Compare,Allocator>& y) { return !(x < y); } template <class Key, class Compare, class Allocator> inline void swap(flat_set<Key,Compare,Allocator>& x, flat_set<Key,Compare,Allocator>& y) { x.swap(y); } /// @cond } //namespace container { //!has_trivial_destructor_after_move<> == true_type //!specialization for optimizations template <class Key, class C, class Allocator> struct has_trivial_destructor_after_move<lslboost::container::flat_set<Key, C, Allocator> > { static const bool value = has_trivial_destructor_after_move<Allocator>::value &&has_trivial_destructor_after_move<C>::value; }; namespace container { // Forward declaration of operators < and ==, needed for friend declaration. #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template <class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > #else template <class Key, class Compare, class Allocator> #endif class flat_multiset; template <class Key, class Compare, class Allocator> inline bool operator==(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y); template <class Key, class Compare, class Allocator> inline bool operator<(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y); /// @endcond //! flat_multiset is a Sorted Associative Container that stores objects of type Key. //! //! flat_multiset can store multiple copies of the same key value. //! //! flat_multiset is similar to std::multiset but it's implemented like an ordered vector. //! This means that inserting a new element into a flat_multiset invalidates //! previous iterators and references //! //! Erasing an element invalidates iterators and references //! pointing to elements that come after (their keys are bigger) the erased element. //! //! This container provides random-access iterators. #ifdef BOOST_CONTAINER_DOXYGEN_INVOKED template <class Key, class Compare = std::less<Key>, class Allocator = std::allocator<Key> > #else template <class Key, class Compare, class Allocator> #endif class flat_multiset { /// @cond private: BOOST_COPYABLE_AND_MOVABLE(flat_multiset) typedef container_detail::flat_tree<Key, Key, container_detail::identity<Key>, Compare, Allocator> tree_t; tree_t m_flat_tree; // flat tree representing flat_multiset /// @endcond public: ////////////////////////////////////////////// // // types // ////////////////////////////////////////////// typedef Key key_type; typedef Key value_type; typedef Compare key_compare; typedef Compare value_compare; typedef typename ::lslboost::container::allocator_traits<Allocator>::pointer pointer; typedef typename ::lslboost::container::allocator_traits<Allocator>::const_pointer const_pointer; typedef typename ::lslboost::container::allocator_traits<Allocator>::reference reference; typedef typename ::lslboost::container::allocator_traits<Allocator>::const_reference const_reference; typedef typename ::lslboost::container::allocator_traits<Allocator>::size_type size_type; typedef typename ::lslboost::container::allocator_traits<Allocator>::difference_type difference_type; typedef Allocator allocator_type; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::stored_allocator_type) stored_allocator_type; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::iterator) iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_iterator) const_iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::reverse_iterator) reverse_iterator; typedef typename BOOST_CONTAINER_IMPDEF(tree_t::const_reverse_iterator) const_reverse_iterator; //! <b>Effects</b>: Default constructs an empty flat_multiset. //! //! <b>Complexity</b>: Constant. explicit flat_multiset() : m_flat_tree() {} //! <b>Effects</b>: Constructs an empty flat_multiset using the specified //! comparison object and allocator. //! //! <b>Complexity</b>: Constant. explicit flat_multiset(const Compare& comp, const allocator_type& a = allocator_type()) : m_flat_tree(comp, a) {} //! <b>Effects</b>: Constructs an empty flat_multiset using the specified allocator. //! //! <b>Complexity</b>: Constant. explicit flat_multiset(const allocator_type& a) : m_flat_tree(a) {} template <class InputIterator> flat_multiset(InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(false, first, last, comp, a) {} //! <b>Effects</b>: Constructs an empty flat_multiset using the specified comparison object and //! allocator, and inserts elements from the ordered range [first ,last ). This function //! is more efficient than the normal range creation for ordered ranges. //! //! <b>Requires</b>: [first ,last) must be ordered according to the predicate. //! //! <b>Complexity</b>: Linear in N. //! //! <b>Note</b>: Non-standard extension. template <class InputIterator> flat_multiset(ordered_range_t, InputIterator first, InputIterator last, const Compare& comp = Compare(), const allocator_type& a = allocator_type()) : m_flat_tree(ordered_range, first, last, comp, a) {} //! <b>Effects</b>: Copy constructs a flat_multiset. //! //! <b>Complexity</b>: Linear in x.size(). flat_multiset(const flat_multiset& x) : m_flat_tree(x.m_flat_tree) {} //! <b>Effects</b>: Move constructs a flat_multiset. Constructs *this using x's resources. //! //! <b>Complexity</b>: Constant. //! //! <b>Postcondition</b>: x is emptied. flat_multiset(BOOST_RV_REF(flat_multiset) mx) : m_flat_tree(lslboost::move(mx.m_flat_tree)) {} //! <b>Effects</b>: Copy constructs a flat_multiset using the specified allocator. //! //! <b>Complexity</b>: Linear in x.size(). flat_multiset(const flat_multiset& x, const allocator_type &a) : m_flat_tree(x.m_flat_tree, a) {} //! <b>Effects</b>: Move constructs a flat_multiset using the specified allocator. //! Constructs *this using x's resources. //! //! <b>Complexity</b>: Constant if a == mx.get_allocator(), linear otherwise flat_multiset(BOOST_RV_REF(flat_multiset) mx, const allocator_type &a) : m_flat_tree(lslboost::move(mx.m_flat_tree), a) {} //! <b>Effects</b>: Makes *this a copy of x. //! //! <b>Complexity</b>: Linear in x.size(). flat_multiset& operator=(BOOST_COPY_ASSIGN_REF(flat_multiset) x) { m_flat_tree = x.m_flat_tree; return *this; } //! <b>Effects</b>: Makes *this a copy of x. //! //! <b>Complexity</b>: Linear in x.size(). flat_multiset& operator=(BOOST_RV_REF(flat_multiset) mx) { m_flat_tree = lslboost::move(mx.m_flat_tree); return *this; } //! <b>Effects</b>: Returns a copy of the Allocator that //! was passed to the object's constructor. //! //! <b>Complexity</b>: Constant. allocator_type get_allocator() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_allocator(); } //! <b>Effects</b>: Returns a reference to the internal allocator. //! //! <b>Throws</b>: Nothing //! //! <b>Complexity</b>: Constant. //! //! <b>Note</b>: Non-standard extension. stored_allocator_type &get_stored_allocator() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_stored_allocator(); } //! <b>Effects</b>: Returns a reference to the internal allocator. //! //! <b>Throws</b>: Nothing //! //! <b>Complexity</b>: Constant. //! //! <b>Note</b>: Non-standard extension. const stored_allocator_type &get_stored_allocator() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.get_stored_allocator(); } //! <b>Effects</b>: Returns an iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. iterator begin() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.begin(); } //! <b>Effects</b>: Returns a const_iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator begin() const { return m_flat_tree.begin(); } //! <b>Effects</b>: Returns a const_iterator to the first element contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator cbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.cbegin(); } //! <b>Effects</b>: Returns an iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. iterator end() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.end(); } //! <b>Effects</b>: Returns a const_iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator end() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.end(); } //! <b>Effects</b>: Returns a const_iterator to the end of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_iterator cend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.cend(); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. reverse_iterator rbegin() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rbegin(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator rbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rbegin(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the beginning //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator crbegin() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.crbegin(); } //! <b>Effects</b>: Returns a reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. reverse_iterator rend() BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rend(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator rend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.rend(); } //! <b>Effects</b>: Returns a const_reverse_iterator pointing to the end //! of the reversed container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. const_reverse_iterator crend() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.crend(); } ////////////////////////////////////////////// // // capacity // ////////////////////////////////////////////// //! <b>Effects</b>: Returns true if the container contains no elements. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. bool empty() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.empty(); } //! <b>Effects</b>: Returns the number of the elements contained in the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type size() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.size(); } //! <b>Effects</b>: Returns the largest possible size of the container. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type max_size() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.max_size(); } //! <b>Effects</b>: Number of elements for which memory has been allocated. //! capacity() is always greater than or equal to size(). //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. size_type capacity() const BOOST_CONTAINER_NOEXCEPT { return m_flat_tree.capacity(); } //! <b>Effects</b>: If n is less than or equal to capacity(), this call has no //! effect. Otherwise, it is a request for allocation of additional memory. //! If the request is successful, then capacity() is greater than or equal to //! n; otherwise, capacity() is unchanged. In either case, size() is unchanged. //! //! <b>Throws</b>: If memory allocation allocation throws or Key's copy constructor throws. //! //! <b>Note</b>: If capacity() is less than "cnt", iterators and references to //! to values might be invalidated. void reserve(size_type cnt) { m_flat_tree.reserve(cnt); } //! <b>Effects</b>: Tries to deallocate the excess of memory created // with previous allocations. The size of the vector is unchanged //! //! <b>Throws</b>: If memory allocation throws, or Key's copy constructor throws. //! //! <b>Complexity</b>: Linear to size(). void shrink_to_fit() { m_flat_tree.shrink_to_fit(); } ////////////////////////////////////////////// // // modifiers // ////////////////////////////////////////////// #if defined(BOOST_CONTAINER_PERFECT_FORWARDING) || defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts an object of type Key constructed with //! std::forward<Args>(args)... and returns the iterator pointing to the //! newly inserted element. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class... Args> iterator emplace(Args&&... args) { return m_flat_tree.emplace_equal(lslboost::forward<Args>(args)...); } //! <b>Effects</b>: Inserts an object of type Key constructed with //! std::forward<Args>(args)... in the container. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent //! to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class... Args> iterator emplace_hint(const_iterator hint, Args&&... args) { return m_flat_tree.emplace_hint_equal(hint, lslboost::forward<Args>(args)...); } #else //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #define BOOST_PP_LOCAL_MACRO(n) \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ { return m_flat_tree.emplace_equal(BOOST_PP_ENUM(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ \ BOOST_PP_EXPR_IF(n, template<) BOOST_PP_ENUM_PARAMS(n, class P) BOOST_PP_EXPR_IF(n, >) \ iterator emplace_hint(const_iterator hint \ BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_LIST, _)) \ { return m_flat_tree.emplace_hint_equal \ (hint BOOST_PP_ENUM_TRAILING(n, BOOST_CONTAINER_PP_PARAM_FORWARD, _)); } \ //! #define BOOST_PP_LOCAL_LIMITS (0, BOOST_CONTAINER_MAX_CONSTRUCTOR_PARAMETERS) #include BOOST_PP_LOCAL_ITERATE() #endif //#ifdef BOOST_CONTAINER_PERFECT_FORWARDING #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts x and returns the iterator pointing to the //! newly inserted element. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(const value_type &x); //! <b>Effects</b>: Inserts a new value_type move constructed from x //! and returns the iterator pointing to the newly inserted element. //! //! <b>Complexity</b>: Logarithmic search time plus linear insertion //! to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(value_type &&x); #else BOOST_MOVE_CONVERSION_AWARE_CATCH(insert, value_type, iterator, this->priv_insert) #endif #if defined(BOOST_CONTAINER_DOXYGEN_INVOKED) //! <b>Effects</b>: Inserts a copy of x in the container. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent //! to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(const_iterator p, const value_type &x); //! <b>Effects</b>: Inserts a new value move constructed from x in the container. //! p is a hint pointing to where the insert should start to search. //! //! <b>Returns</b>: An iterator pointing to the element with key equivalent //! to the key of x. //! //! <b>Complexity</b>: Logarithmic search time (constant if x is inserted //! right before p) plus insertion linear to the elements with bigger keys than x. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. iterator insert(const_iterator position, value_type &&x); #else BOOST_MOVE_CONVERSION_AWARE_CATCH_1ARG(insert, value_type, iterator, this->priv_insert, const_iterator, const_iterator) #endif //! <b>Requires</b>: first, last are not iterators into *this. //! //! <b>Effects</b>: inserts each element from the range [first,last) . //! //! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last) //! search time plus N*size() insertion time. //! //! <b>Note</b>: If an element is inserted it might invalidate elements. template <class InputIterator> void insert(InputIterator first, InputIterator last) { m_flat_tree.insert_equal(first, last); } //! <b>Requires</b>: first, last are not iterators into *this and //! must be ordered according to the predicate. //! //! <b>Effects</b>: inserts each element from the range [first,last) .This function //! is more efficient than the normal range creation for ordered ranges. //! //! <b>Complexity</b>: At most N log(size()+N) (N is the distance from first to last) //! search time plus N*size() insertion time. //! //! <b>Note</b>: Non-standard extension. If an element is inserted it might invalidate elements. template <class InputIterator> void insert(ordered_range_t, InputIterator first, InputIterator last) { m_flat_tree.insert_equal(ordered_range, first, last); } //! <b>Effects</b>: Erases the element pointed to by position. //! //! <b>Returns</b>: Returns an iterator pointing to the element immediately //! following q prior to the element being erased. If no such element exists, //! returns end(). //! //! <b>Complexity</b>: Linear to the elements with keys bigger than position //! //! <b>Note</b>: Invalidates elements with keys //! not less than the erased element. iterator erase(const_iterator position) { return m_flat_tree.erase(position); } //! <b>Effects</b>: Erases all elements in the container with key equivalent to x. //! //! <b>Returns</b>: Returns the number of erased elements. //! //! <b>Complexity</b>: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. size_type erase(const key_type& x) { return m_flat_tree.erase(x); } //! <b>Effects</b>: Erases all the elements in the range [first, last). //! //! <b>Returns</b>: Returns last. //! //! <b>Complexity</b>: size()*N where N is the distance from first to last. //! //! <b>Complexity</b>: Logarithmic search time plus erasure time //! linear to the elements with bigger keys. iterator erase(const_iterator first, const_iterator last) { return m_flat_tree.erase(first, last); } //! <b>Effects</b>: Swaps the contents of *this and x. //! //! <b>Throws</b>: Nothing. //! //! <b>Complexity</b>: Constant. void swap(flat_multiset& x) { m_flat_tree.swap(x.m_flat_tree); } //! <b>Effects</b>: erase(a.begin(),a.end()). //! //! <b>Postcondition</b>: size() == 0. //! //! <b>Complexity</b>: linear in size(). void clear() BOOST_CONTAINER_NOEXCEPT { m_flat_tree.clear(); } ////////////////////////////////////////////// // // observers // ////////////////////////////////////////////// //! <b>Effects</b>: Returns the comparison object out //! of which a was constructed. //! //! <b>Complexity</b>: Constant. key_compare key_comp() const { return m_flat_tree.key_comp(); } //! <b>Effects</b>: Returns an object of value_compare constructed out //! of the comparison object. //! //! <b>Complexity</b>: Constant. value_compare value_comp() const { return m_flat_tree.key_comp(); } ////////////////////////////////////////////// // // set operations // ////////////////////////////////////////////// //! <b>Returns</b>: An iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic. iterator find(const key_type& x) { return m_flat_tree.find(x); } //! <b>Returns</b>: Allocator const_iterator pointing to an element with the key //! equivalent to x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic.s const_iterator find(const key_type& x) const { return m_flat_tree.find(x); } //! <b>Returns</b>: The number of elements with key equivalent to x. //! //! <b>Complexity</b>: log(size())+count(k) size_type count(const key_type& x) const { return m_flat_tree.count(x); } //! <b>Returns</b>: An iterator pointing to the first element with key not less //! than k, or a.end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic iterator lower_bound(const key_type& x) { return m_flat_tree.lower_bound(x); } //! <b>Returns</b>: Allocator const iterator pointing to the first element with key not //! less than k, or a.end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic const_iterator lower_bound(const key_type& x) const { return m_flat_tree.lower_bound(x); } //! <b>Returns</b>: An iterator pointing to the first element with key not less //! than x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic iterator upper_bound(const key_type& x) { return m_flat_tree.upper_bound(x); } //! <b>Returns</b>: Allocator const iterator pointing to the first element with key not //! less than x, or end() if such an element is not found. //! //! <b>Complexity</b>: Logarithmic const_iterator upper_bound(const key_type& x) const { return m_flat_tree.upper_bound(x); } //! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! <b>Complexity</b>: Logarithmic std::pair<const_iterator, const_iterator> equal_range(const key_type& x) const { return m_flat_tree.equal_range(x); } //! <b>Effects</b>: Equivalent to std::make_pair(this->lower_bound(k), this->upper_bound(k)). //! //! <b>Complexity</b>: Logarithmic std::pair<iterator,iterator> equal_range(const key_type& x) { return m_flat_tree.equal_range(x); } /// @cond template <class K1, class C1, class A1> friend bool operator== (const flat_multiset<K1,C1,A1>&, const flat_multiset<K1,C1,A1>&); template <class K1, class C1, class A1> friend bool operator< (const flat_multiset<K1,C1,A1>&, const flat_multiset<K1,C1,A1>&); private: template <class KeyType> iterator priv_insert(BOOST_FWD_REF(KeyType) x) { return m_flat_tree.insert_equal(::lslboost::forward<KeyType>(x)); } template <class KeyType> iterator priv_insert(const_iterator p, BOOST_FWD_REF(KeyType) x) { return m_flat_tree.insert_equal(p, ::lslboost::forward<KeyType>(x)); } /// @endcond }; template <class Key, class Compare, class Allocator> inline bool operator==(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return x.m_flat_tree == y.m_flat_tree; } template <class Key, class Compare, class Allocator> inline bool operator<(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return x.m_flat_tree < y.m_flat_tree; } template <class Key, class Compare, class Allocator> inline bool operator!=(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return !(x == y); } template <class Key, class Compare, class Allocator> inline bool operator>(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return y < x; } template <class Key, class Compare, class Allocator> inline bool operator<=(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return !(y < x); } template <class Key, class Compare, class Allocator> inline bool operator>=(const flat_multiset<Key,Compare,Allocator>& x, const flat_multiset<Key,Compare,Allocator>& y) { return !(x < y); } template <class Key, class Compare, class Allocator> inline void swap(flat_multiset<Key,Compare,Allocator>& x, flat_multiset<Key,Compare,Allocator>& y) { x.swap(y); } /// @cond } //namespace container { //!has_trivial_destructor_after_move<> == true_type //!specialization for optimizations template <class Key, class C, class Allocator> struct has_trivial_destructor_after_move<lslboost::container::flat_multiset<Key, C, Allocator> > { static const bool value = has_trivial_destructor_after_move<Allocator>::value && has_trivial_destructor_after_move<C>::value; }; namespace container { /// @endcond }} #include <lslboost/container/detail/config_end.hpp> #endif /* BOOST_CONTAINER_FLAT_SET_HPP */
{ "language": "C++" }